instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void addRequiredDecision(InformationRequirement requiredDecision) {
this.requiredDecisions.add(requiredDecision);
}
public List<InformationRequirement> getRequiredInputs() {
return requiredInputs;
}
public void setRequiredInputs(List<InformationRequirement> requiredInputs) {
this.requiredInputs = requiredInputs;
}
public void addRequiredInput(InformationRequirement requiredInput) {
this.requiredInputs.add(requiredInput);
}
public List<AuthorityRequirement> getAuthorityRequirements() {
return authorityRequirements;
}
public void setAuthorityRequirements(List<AuthorityRequirement> authorityRequirements) {
this.authorityRequirements = authorityRequirements;
}
public void addAuthorityRequirement(AuthorityRequirement authorityRequirement) {
this.authorityRequirements.add(authorityRequirement);
}
public Expression getExpression() {
return expression;
}
public void setExpression(Expression expression) {
this.expression = expression;
}
|
public boolean isForceDMN11() {
return forceDMN11;
}
public void setForceDMN11(boolean forceDMN11) {
this.forceDMN11 = forceDMN11;
}
@JsonIgnore
public DmnDefinition getDmnDefinition() {
return dmnDefinition;
}
public void setDmnDefinition(DmnDefinition dmnDefinition) {
this.dmnDefinition = dmnDefinition;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\Decision.java
| 1
|
请完成以下Java代码
|
private int search (String url, String exactURL)
{
String sql = "SELECT W_ClickCount_ID, TargetURL FROM W_ClickCount WHERE TargetURL LIKE ?";
int W_ClickCount_ID = 0;
int exactW_ClickCount_ID = 0;
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setString(1, "%" + url + "%");
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
W_ClickCount_ID = rs.getInt(1);
if (exactURL.equals(rs.getString(2)))
{
exactW_ClickCount_ID = W_ClickCount_ID;
break;
}
}
rs.close();
pstmt.close();
pstmt = null;
}
catch (SQLException ex)
{
log.error(sql, ex);
}
try
{
if (pstmt != null)
pstmt.close();
}
catch (SQLException ex1)
{
}
pstmt = null;
// Set Click Count
if (exactW_ClickCount_ID != 0)
W_ClickCount_ID = exactW_ClickCount_ID;
return W_ClickCount_ID;
} // search
/**
* Before Save
* @param newRecord new
* @return true
|
*/
protected boolean beforeSave (boolean newRecord)
{
if (getW_ClickCount_ID() == 0)
setW_ClickCount_ID();
return true;
} // beforeSave
/**************************************************************************
* Test
* @param args ignored
*/
public static void main (String[] args)
{
Adempiere.startup(true);
Env.setContext(Env.getCtx(), "#AD_Client_ID", 1000000);
MClick[] clicks = getUnprocessed(Env.getCtx());
int counter = 0;
for (int i = 0; i < clicks.length; i++)
{
MClick click = clicks[i];
if (click.getW_ClickCount_ID() == 0)
{
click.setW_ClickCount_ID();
if (click.getW_ClickCount_ID() != 0)
{
click.save();
counter++;
}
}
}
System.out.println("#" + counter);
} // main
} // MClick
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MClick.java
| 1
|
请完成以下Java代码
|
public class CamundaConstraintImpl extends BpmnModelElementInstanceImpl implements CamundaConstraint {
protected static Attribute<String> camundaNameAttribute;
protected static Attribute<String> camundaConfigAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaConstraint.class, CAMUNDA_ELEMENT_CONSTRAINT)
.namespaceUri(CAMUNDA_NS)
.instanceProvider(new ModelTypeInstanceProvider<CamundaConstraint>() {
public CamundaConstraint newInstance(ModelTypeInstanceContext instanceContext) {
return new CamundaConstraintImpl(instanceContext);
}
});
camundaNameAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_NAME)
.namespace(CAMUNDA_NS)
.build();
camundaConfigAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CONFIG)
.namespace(CAMUNDA_NS)
.build();
|
typeBuilder.build();
}
public CamundaConstraintImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getCamundaName() {
return camundaNameAttribute.getValue(this);
}
public void setCamundaName(String camundaName) {
camundaNameAttribute.setValue(this, camundaName);
}
public String getCamundaConfig() {
return camundaConfigAttribute.getValue(this);
}
public void setCamundaConfig(String camundaConfig) {
camundaConfigAttribute.setValue(this, camundaConfig);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaConstraintImpl.java
| 1
|
请完成以下Java代码
|
private static ImmutableMap<DocumentId, PPOrderLineRow> buildRecordsByIdMap(@NonNull final List<PPOrderLineRow> rows)
{
if (rows.isEmpty())
{
return ImmutableMap.of();
}
final ImmutableMap.Builder<DocumentId, PPOrderLineRow> rowsById = ImmutableMap.builder();
rows.forEach(row -> indexByIdRecursively(rowsById, row));
return rowsById.build();
}
private static void indexByIdRecursively(
@NonNull final ImmutableMap.Builder<DocumentId, PPOrderLineRow> collector,
@NonNull final PPOrderLineRow row)
{
collector.put(row.getRowId().toDocumentId(), row);
row.getIncludedRows().forEach(includedRow -> indexByIdRecursively(collector, includedRow));
}
public PPOrderLineRow getById(@NonNull final PPOrderLineRowId rowId)
{
final DocumentId documentId = rowId.toDocumentId();
final PPOrderLineRow row = allRowsById.get(documentId);
if (row == null)
{
throw new EntityNotFoundException("No document found for rowId=" + rowId);
}
return row;
}
|
public Stream<PPOrderLineRow> streamByIds(@NonNull final DocumentIdsSelection documentIds)
{
if (documentIds == null || documentIds.isEmpty())
{
return Stream.empty();
}
else if (documentIds.isAll())
{
return topLevelRows.stream();
}
else
{
return documentIds.stream()
.distinct()
.map(allRowsById::get)
.filter(Objects::nonNull);
}
}
public Stream<PPOrderLineRow> stream()
{
return topLevelRows.stream();
}
public long size()
{
return topLevelRows.size();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLinesViewData.java
| 1
|
请完成以下Java代码
|
public de.metas.payment.sepa.model.I_SEPA_Export_Line getSEPA_Export_Line_Retry()
{
return get_ValueAsPO(COLUMNNAME_SEPA_Export_Line_Retry_ID, de.metas.payment.sepa.model.I_SEPA_Export_Line.class);
}
@Override
public void setSEPA_Export_Line_Retry(de.metas.payment.sepa.model.I_SEPA_Export_Line SEPA_Export_Line_Retry)
{
set_ValueFromPO(COLUMNNAME_SEPA_Export_Line_Retry_ID, de.metas.payment.sepa.model.I_SEPA_Export_Line.class, SEPA_Export_Line_Retry);
}
/** Set SEPA_Export_Line_Retry_ID.
@param SEPA_Export_Line_Retry_ID SEPA_Export_Line_Retry_ID */
@Override
public void setSEPA_Export_Line_Retry_ID (int SEPA_Export_Line_Retry_ID)
{
if (SEPA_Export_Line_Retry_ID < 1)
set_Value (COLUMNNAME_SEPA_Export_Line_Retry_ID, null);
else
set_Value (COLUMNNAME_SEPA_Export_Line_Retry_ID, Integer.valueOf(SEPA_Export_Line_Retry_ID));
}
/** Get SEPA_Export_Line_Retry_ID.
@return SEPA_Export_Line_Retry_ID */
@Override
public int getSEPA_Export_Line_Retry_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SEPA_Export_Line_Retry_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set SEPA_MandateRefNo.
@param SEPA_MandateRefNo SEPA_MandateRefNo */
@Override
public void setSEPA_MandateRefNo (java.lang.String SEPA_MandateRefNo)
{
set_Value (COLUMNNAME_SEPA_MandateRefNo, SEPA_MandateRefNo);
}
/** Get SEPA_MandateRefNo.
@return SEPA_MandateRefNo */
@Override
public java.lang.String getSEPA_MandateRefNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_SEPA_MandateRefNo);
}
/** Set StructuredRemittanceInfo.
@param StructuredRemittanceInfo
Structured Remittance Information
*/
@Override
public void setStructuredRemittanceInfo (java.lang.String StructuredRemittanceInfo)
{
set_Value (COLUMNNAME_StructuredRemittanceInfo, StructuredRemittanceInfo);
}
/** Get StructuredRemittanceInfo.
@return Structured Remittance Information
*/
@Override
public java.lang.String getStructuredRemittanceInfo ()
{
return (java.lang.String)get_Value(COLUMNNAME_StructuredRemittanceInfo);
}
/** Set Swift code.
@param SwiftCode
Swift Code or BIC
*/
@Override
public void setSwiftCode (java.lang.String SwiftCode)
{
set_Value (COLUMNNAME_SwiftCode, SwiftCode);
}
|
/** Get Swift code.
@return Swift Code or BIC
*/
@Override
public java.lang.String getSwiftCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_SwiftCode);
}
@Override
public void setIsGroupLine (final boolean IsGroupLine)
{
set_Value (COLUMNNAME_IsGroupLine, IsGroupLine);
}
@Override
public boolean isGroupLine()
{
return get_ValueAsBoolean(COLUMNNAME_IsGroupLine);
}
@Override
public void setNumberOfReferences (final int NumberOfReferences)
{
set_Value (COLUMNNAME_NumberOfReferences, NumberOfReferences);
}
@Override
public int getNumberOfReferences()
{
return get_ValueAsInt(COLUMNNAME_NumberOfReferences);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export_Line.java
| 1
|
请完成以下Java代码
|
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
if (log.isDebugEnabled()) {
log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
}
/**
* 发布事件
*
* @param event 事件
|
*/
public static void publishEvent(ApplicationEvent event) {
if (applicationContext == null) {
return;
}
applicationContext.publishEvent(event);
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() {
SpringUtil.clearHolder();
}
}
|
repos\spring-boot-demo-master\demo-dynamic-datasource\src\main\java\com\xkcoding\dynamic\datasource\utils\SpringUtil.java
| 1
|
请完成以下Java代码
|
DerKurierClient createClient(@NonNull final DerKurierShipperConfig shipperConfig)
{
final RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder()
.rootUri(shipperConfig.getRestApiBaseUrl());
final RestTemplate restTemplate = restTemplateBuilder.build();
extractAndConfigureObjectMapperOfRestTemplate(restTemplate);
return new DerKurierClient(
restTemplate,
converters,
derKurierDeliveryOrderService,
derKurierDeliveryOrderRepository);
}
/**
* Put JavaTimeModule into the rest template's jackson object mapper.
* <b>
* Note 1: there have to be better ways to achieve this, but i don't know them.
* thx to https://stackoverflow.com/a/47176770/1012103
* <b>
* Note 2: visible because this is the object mapper we run with; we want our unit tests to use it as well.
*/
|
@VisibleForTesting
public static ObjectMapper extractAndConfigureObjectMapperOfRestTemplate(@NonNull final RestTemplate restTemplate)
{
final MappingJackson2HttpMessageConverter messageConverter = restTemplate
.getMessageConverters()
.stream()
.filter(MappingJackson2HttpMessageConverter.class::isInstance)
.map(MappingJackson2HttpMessageConverter.class::cast)
.findFirst().orElseThrow(() -> new RuntimeException("MappingJackson2HttpMessageConverter not found"));
final ObjectMapper objectMapper = messageConverter.getObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
return objectMapper;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\DerKurierClientFactory.java
| 1
|
请完成以下Java代码
|
public int getPP_Order_NodeNext_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_NodeNext_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@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();
}
/** Set Transition Code.
@param TransitionCode
Code resulting in TRUE of FALSE
*/
@Override
public void setTransitionCode (java.lang.String TransitionCode)
{
set_Value (COLUMNNAME_TransitionCode, TransitionCode);
}
/** Get Transition Code.
@return Code resulting in TRUE of FALSE
*/
@Override
public java.lang.String getTransitionCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransitionCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_NodeNext.java
| 1
|
请完成以下Java代码
|
public final void setNClob(final int parameterIndex, final Reader reader) throws SQLException
{
traceSqlParam(parameterIndex, reader);
delegate.setNClob(parameterIndex, reader);
}
@Override
public final void setNString(final int parameterIndex, final String value) throws SQLException
{
traceSqlParam(parameterIndex, value);
delegate.setNString(parameterIndex, value);
}
@Override
public final ResultSet executeQuery() throws SQLException
{
return trace(() -> delegate.executeQuery());
}
@Override
public ResultSet executeQueryAndLogMigationScripts() throws SQLException
{
return trace(() -> delegate.executeQueryAndLogMigationScripts());
}
@Override
public final int executeUpdate() throws SQLException
{
return trace(() -> delegate.executeUpdate());
}
@Override
public final void clearParameters() throws SQLException
{
delegate.clearParameters();
}
@Override
|
public final boolean execute() throws SQLException
{
return trace(() -> delegate.execute());
}
@Override
public final void addBatch() throws SQLException
{
trace(() -> {
delegate.addBatch();
return null;
});
}
@Override
public final ResultSetMetaData getMetaData() throws SQLException
{
return delegate.getMetaData();
}
@Override
public final ParameterMetaData getParameterMetaData() throws SQLException
{
return delegate.getParameterMetaData();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\sql\impl\TracingPreparedStatement.java
| 1
|
请完成以下Java代码
|
public class PlanItemDelegateExpressionActivityBehavior extends CoreCmmnTriggerableActivityBehavior {
protected String expression;
protected List<FieldExtension> fieldExtensions;
public PlanItemDelegateExpressionActivityBehavior(String expression, List<FieldExtension> fieldExtensions) {
this.expression = expression;
this.fieldExtensions = fieldExtensions;
}
@Override
public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
Expression expressionObject = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getExpressionManager().createExpression(expression);
Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expressionObject, planItemInstanceEntity, fieldExtensions);
if (delegate instanceof PlanItemActivityBehavior) {
((PlanItemActivityBehavior) delegate).execute(planItemInstanceEntity);
} else if (delegate instanceof CmmnActivityBehavior) {
((CmmnActivityBehavior) delegate).execute(planItemInstanceEntity);
} else if (delegate instanceof PlanItemJavaDelegate) {
PlanItemJavaDelegateActivityBehavior behavior = new PlanItemJavaDelegateActivityBehavior((PlanItemJavaDelegate) delegate);
behavior.execute(planItemInstanceEntity);
} else if (delegate instanceof PlanItemFutureJavaDelegate) {
PlanItemFutureJavaDelegateActivityBehavior behavior = new PlanItemFutureJavaDelegateActivityBehavior((PlanItemFutureJavaDelegate<?>) delegate);
behavior.execute(planItemInstanceEntity);
} else {
throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did neither resolve to an implementation of " +
PlanItemActivityBehavior.class + ", " + CmmnActivityBehavior.class + ", " + PlanItemJavaDelegate.class + " nor "
|
+ PlanItemFutureJavaDelegate.class);
}
}
@Override
public void trigger(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
Expression expressionObject = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getExpressionManager().createExpression(expression);
Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expressionObject, planItemInstanceEntity, fieldExtensions);
if (delegate instanceof CmmnTriggerableActivityBehavior) { // includes CmmnTriggerableActivityBehavior
((CmmnTriggerableActivityBehavior) delegate).trigger(planItemInstanceEntity);
} else {
throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did neither resolve to an implementation of "
+ CmmnTriggerableActivityBehavior.class);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\PlanItemDelegateExpressionActivityBehavior.java
| 1
|
请完成以下Spring Boot application配置
|
#CHANGE
server.port=5000
logging.level.org.springframework=info
management.endpoints.web.exposure.include=*
#spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.defer-datasource-initialization=true
spring.jpa.show-sql=true
#spring.datasource.url=jdbc:mysql://localhost:3306/social-media-database
#spring.datasource.username=social-media-user
#spring.datasource.password=dummypassword
spring.datasource.url=jdbc:mysql://${RDS_HOSTNAME:localhost}:${RDS_PORT:3306}/${RDS_DB_NAME:social-media-database}
spring.datasource.username=${RDS_USERNAME:social-media-user}
spring.datasource.password=${RDS_PASSWORD:dummypassword}
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
#CHANGE
spring.security.user.name=in28minutes
spring.security.user.password=dummy
# \connect social-media-user@localhost:3306
#d
|
ocker run --detach
#--env MYSQL_ROOT_PASSWORD=dummypassword
#--env MYSQL_USER=social-media-user
#--env MYSQL_PASSWORD=dummypassword
#--env MYSQL_DATABASE=social-media-database
#--name mysql
#--publish 3306:3306
#mysql:8-oracle
#EC2 - sg-0d9e3dd9e29e3650f (awseb-e-xvdadum3ns-stack-AWSEBSecurityGroup-1A4SWB8EWXXLJ)
#DB - sg-042c448703d7d42d6 > sg-0d9e3dd9e29e3650f
|
repos\master-spring-and-spring-boot-main\91-aws\02-rest-api-mysql\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public Builder setC_LocTo_ID(final int C_LocTo_ID)
{
setSegmentValue(AcctSegmentType.LocationTo, C_LocTo_ID);
return this;
}
public Builder setC_SalesRegion_ID(@Nullable final SalesRegionId C_SalesRegion_ID)
{
setSegmentValue(AcctSegmentType.SalesRegion, SalesRegionId.toRepoId(C_SalesRegion_ID));
return this;
}
public Builder setC_Project_ID(final int C_Project_ID)
{
setSegmentValue(AcctSegmentType.Project, C_Project_ID);
return this;
}
public Builder setC_Campaign_ID(final int C_Campaign_ID)
{
setSegmentValue(AcctSegmentType.Campaign, C_Campaign_ID);
return this;
}
public Builder setC_Activity_ID(final int C_Activity_ID)
{
setSegmentValue(AcctSegmentType.Activity, C_Activity_ID);
return this;
}
public Builder setSalesOrderId(final int C_OrderSO_ID)
{
setSegmentValue(AcctSegmentType.SalesOrder, C_OrderSO_ID);
return this;
}
public Builder setUser1_ID(final int user1_ID)
{
setSegmentValue(AcctSegmentType.UserList1, user1_ID);
return this;
}
public Builder setUser2_ID(final int user2_ID)
{
setSegmentValue(AcctSegmentType.UserList2, user2_ID);
return this;
}
public Builder setUserElement1_ID(final int userElement1_ID)
{
setSegmentValue(AcctSegmentType.UserElement1, userElement1_ID);
return this;
}
public Builder setUserElement2_ID(final int userElement2_ID)
{
setSegmentValue(AcctSegmentType.UserElement2, userElement2_ID);
return this;
}
public Builder setUserElementString1(final String userElementString1)
{
|
setSegmentValue(AcctSegmentType.UserElementString1, userElementString1);
return this;
}
public Builder setUserElementString2(final String userElementString2)
{
setSegmentValue(AcctSegmentType.UserElementString2, userElementString2);
return this;
}
public Builder setUserElementString3(final String userElementString3)
{
setSegmentValue(AcctSegmentType.UserElementString3, userElementString3);
return this;
}
public Builder setUserElementString4(final String userElementString4)
{
setSegmentValue(AcctSegmentType.UserElementString4, userElementString4);
return this;
}
public Builder setUserElementString5(final String userElementString5)
{
setSegmentValue(AcctSegmentType.UserElementString5, userElementString5);
return this;
}
public Builder setUserElementString6(final String userElementString6)
{
setSegmentValue(AcctSegmentType.UserElementString6, userElementString6);
return this;
}
public Builder setUserElementString7(final String userElementString7)
{
setSegmentValue(AcctSegmentType.UserElementString7, userElementString7);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AccountDimension.java
| 1
|
请完成以下Java代码
|
private ExplainedOptional<NameAndGreeting> computeForSingleContact(@NonNull final ComputeNameAndGreetingRequest.Contact contact, final boolean isMembershipContact)
{
final String nameComposite =
contact.getFirstName()
+" "+
contact.getLastName();
return ExplainedOptional.of(NameAndGreeting.builder()
.name(nameComposite)
.greetingId(isMembershipContact ? contact.getGreetingId() : null)
.build());
}
@NonNull
private ExplainedOptional<NameAndGreeting> computeForTwoContacts(
@NonNull final ComputeNameAndGreetingRequest.Contact person1,
@NonNull final ComputeNameAndGreetingRequest.Contact person2,
@NonNull final String adLanguage)
{
final GreetingId greetingId = greetingRepo.getComposite(person1.getGreetingId(), person2.getGreetingId())
.map(Greeting::getId)
.orElse(null);
if (!Objects.equals(person1.getLastName(), person2.getLastName()))
{
final String nameComposite = TranslatableStrings.builder()
.append(person1.getFirstName())
.append(" ")
.append(person1.getLastName())
.append(" ")
.appendADMessage(MSG_And)
.append(" ")
.append(person2.getFirstName())
.append(" ")
.append(person2.getLastName())
.build()
.translate(adLanguage);
return ExplainedOptional.of(NameAndGreeting.builder()
.name(nameComposite)
.greetingId(greetingId)
.build());
}
|
else
{
final String nameComposite = TranslatableStrings.builder()
.append(person1.getFirstName())
.append(" ")
.appendADMessage(MSG_And)
.append(" ")
.append(person2.getFirstName())
.append(" ")
.append(person1.getLastName())
.build()
.translate(adLanguage);
return ExplainedOptional.of(NameAndGreeting.builder()
.name(nameComposite)
.greetingId(greetingId)
.build());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\name\strategy\MembershipContactBPartnerNameAndGreetingStrategy.java
| 1
|
请完成以下Java代码
|
public void setM_InOutLine_ID (final int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID);
}
@Override
public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public I_M_InOut_Cost getReversal()
{
return get_ValueAsPO(COLUMNNAME_Reversal_ID, I_M_InOut_Cost.class);
}
|
@Override
public void setReversal(final I_M_InOut_Cost Reversal)
{
set_ValueFromPO(COLUMNNAME_Reversal_ID, I_M_InOut_Cost.class, Reversal);
}
@Override
public void setReversal_ID (final int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
else
set_Value (COLUMNNAME_Reversal_ID, Reversal_ID);
}
@Override
public int getReversal_ID()
{
return get_ValueAsInt(COLUMNNAME_Reversal_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOut_Cost.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CustomUserAttrController {
@GetMapping(path = "/users")
public String getUserInfo(Model model) {
final DefaultOidcUser user = (DefaultOidcUser) SecurityContextHolder.getContext()
.getAuthentication()
.getPrincipal();
String dob = "";
String userId = "";
OidcIdToken token = user.getIdToken();
Map<String, Object> customClaims = token.getClaims();
|
if (customClaims.containsKey("user_id")) {
userId = String.valueOf(customClaims.get("user_id"));
}
if (customClaims.containsKey("DOB")) {
dob = String.valueOf(customClaims.get("DOB"));
}
model.addAttribute("username", user.getName());
model.addAttribute("userID", userId);
model.addAttribute("dob", dob);
return "userInfo";
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-adapters\src\main\java\com\baeldung\keycloak\CustomUserAttrController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Integer getConcurrencyLimit() {
return this.concurrencyLimit;
}
public void setConcurrencyLimit(@Nullable Integer concurrencyLimit) {
this.concurrencyLimit = concurrencyLimit;
}
}
public static class Shutdown {
/**
* Whether the executor should wait for scheduled tasks to complete on shutdown.
*/
private boolean awaitTermination;
/**
* Maximum time the executor should wait for remaining tasks to complete.
*/
private @Nullable Duration awaitTerminationPeriod;
public boolean isAwaitTermination() {
|
return this.awaitTermination;
}
public void setAwaitTermination(boolean awaitTermination) {
this.awaitTermination = awaitTermination;
}
public @Nullable Duration getAwaitTerminationPeriod() {
return this.awaitTerminationPeriod;
}
public void setAwaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) {
this.awaitTerminationPeriod = awaitTerminationPeriod;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskSchedulingProperties.java
| 2
|
请完成以下Java代码
|
protected void assertAuth() {userSession.assertLoggedIn();}
protected void resetAdditional(@NonNull final JsonCacheResetResponse response, @NonNull final JsonCacheResetRequest request)
{
{
final boolean forgetNotSavedDocuments = request.getValueAsBoolean(CACHE_RESET_PARAM_forgetNotSavedDocuments);
final String documentsResult = documentCollection.cacheReset(forgetNotSavedDocuments);
response.addLog("documents: " + documentsResult + " (" + CACHE_RESET_PARAM_forgetNotSavedDocuments + "=" + forgetNotSavedDocuments + ")");
}
{
menuTreeRepo.cacheReset();
response.addLog("menuTreeRepo: cache invalidated");
}
{
processesController.cacheReset();
response.addLog("processesController: cache invalidated");
}
{
ViewColumnHelper.cacheReset();
response.addLog("viewColumnHelper: cache invalidated");
|
}
}
@GetMapping("/lookups/stats")
public JsonGetStatsResponse getLookupCacheStats()
{
assertAuth();
return lookupDataSourceFactory.getCacheStats()
.stream()
.sorted(DEFAULT_ORDER_BY)
.map(JsonCacheStats::of)
.collect(JsonGetStatsResponse.collect());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\admin\CacheRestController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonResponseReceiptCandidates
{
String transactionKey;
Integer exportSequenceNumber;
List<JsonResponseReceiptCandidate> items;
boolean hasMoreItems;
@Builder
@JsonCreator
private JsonResponseReceiptCandidates(
@JsonProperty("transactionKey") @NonNull final String transactionKey,
@JsonProperty("exportSequenceNumber") @NonNull final Integer exportSequenceNumber,
|
@JsonProperty("items") @Singular @NonNull final List<JsonResponseReceiptCandidate> items,
@JsonProperty("hasMoreItems") @NonNull final Boolean hasMoreItems)
{
this.transactionKey = transactionKey;
this.exportSequenceNumber = exportSequenceNumber;
this.items = items;
this.hasMoreItems = hasMoreItems;
}
public static JsonResponseReceiptCandidates empty(@NonNull final String transactionKey)
{
return builder().transactionKey(transactionKey).hasMoreItems(false)
.exportSequenceNumber(0) // no data is exported, so there is no sequence number
.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-shipping\src\main\java\de\metas\common\shipping\v1\receiptcandidate\JsonResponseReceiptCandidates.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
class HumioPropertiesConfigAdapter extends StepRegistryPropertiesConfigAdapter<HumioProperties> implements HumioConfig {
HumioPropertiesConfigAdapter(HumioProperties properties) {
super(properties);
}
@Override
public String prefix() {
return "management.humio.metrics.export";
}
@Override
public @Nullable String get(String k) {
return null;
}
|
@Override
public String uri() {
return obtain(HumioProperties::getUri, HumioConfig.super::uri);
}
@Override
public @Nullable Map<String, String> tags() {
return get(HumioProperties::getTags, HumioConfig.super::tags);
}
@Override
public @Nullable String apiToken() {
return get(HumioProperties::getApiToken, HumioConfig.super::apiToken);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\humio\HumioPropertiesConfigAdapter.java
| 2
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("modelClass", modelClass)
.add("models", models)
.toString();
}
public <T> List<T> getModels(final Class<T> modelClass)
{
// If loaded models list is empty, we can return an empty list directly
if (models.isEmpty())
{
return ImmutableList.of();
}
|
// If loaded models have the same model class as the requested one
// we can simple cast & return them
if (Objects.equals(modelClass, this.modelClass))
{
@SuppressWarnings("unchecked") final List<T> modelsCasted = (List<T>)models;
return modelsCasted;
}
// If not the same class, we have to wrap them fist.
else
{
return InterfaceWrapperHelper.wrapToImmutableList(models, modelClass);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ViewAsPreconditionsContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getPostalCode()
{
return postalCode;
}
public void setPostalCode(String postalCode)
{
this.postalCode = postalCode;
}
public TaxAddress stateOrProvince(String stateOrProvince)
{
this.stateOrProvince = stateOrProvince;
return this;
}
/**
* The state name that can be used by sellers for tax purpose.
*
* @return stateOrProvince
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The state name that can be used by sellers for tax purpose.")
public String getStateOrProvince()
{
return stateOrProvince;
}
public void setStateOrProvince(String stateOrProvince)
{
this.stateOrProvince = stateOrProvince;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
TaxAddress taxAddress = (TaxAddress)o;
return Objects.equals(this.city, taxAddress.city) &&
Objects.equals(this.countryCode, taxAddress.countryCode) &&
Objects.equals(this.postalCode, taxAddress.postalCode) &&
Objects.equals(this.stateOrProvince, taxAddress.stateOrProvince);
}
|
@Override
public int hashCode()
{
return Objects.hash(city, countryCode, postalCode, stateOrProvince);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class TaxAddress {\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" stateOrProvince: ").append(toIndentedString(stateOrProvince)).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\TaxAddress.java
| 2
|
请完成以下Java代码
|
public void initialize(final ModelValidationEngine engine, final MClient client)
{
if (client != null)
{
m_AD_Client_ID = client.getAD_Client_ID();
}
Check.assume(Services.isAutodetectServices(), "Service auto detection is enabled");
if (!Ini.isSwingClient())
{
// make sure that the handlers defined in this module are registered
Services.get(IReplRequestHandlerBL.class).registerHandlerType("LoadPO", LoadPORequestHandler.class, RequestHandler_Constants.ENTITY_TYPE);
}
}
@Override
|
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{
return null; // nothing to do
}
@Override
public String modelChange(final PO po, final int type) throws Exception
{
return null; // nothing to do
}
@Override
public String docValidate(PO po, int timing)
{
return null; // nothing to do
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\rpl\requesthandler\model\validator\Main_Validator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DisputeAmount value(String value)
{
this.value = value;
return this;
}
/**
* The monetary amount, in the currency specified by the currency field. This field is always returned with any container using Amount type.
*
* @return value
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The monetary amount, in the currency specified by the currency field. This field is always returned with any container using Amount type.")
public String getValue()
{
return value;
}
public void setValue(String value)
{
this.value = value;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
DisputeAmount disputeAmount = (DisputeAmount)o;
return Objects.equals(this.convertedFromCurrency, disputeAmount.convertedFromCurrency) &&
Objects.equals(this.convertedFromValue, disputeAmount.convertedFromValue) &&
Objects.equals(this.currency, disputeAmount.currency) &&
Objects.equals(this.exchangeRate, disputeAmount.exchangeRate) &&
Objects.equals(this.value, disputeAmount.value);
}
@Override
public int hashCode()
{
return Objects.hash(convertedFromCurrency, convertedFromValue, currency, exchangeRate, value);
}
@Override
public String toString()
|
{
StringBuilder sb = new StringBuilder();
sb.append("class DisputeAmount {\n");
sb.append(" convertedFromCurrency: ").append(toIndentedString(convertedFromCurrency)).append("\n");
sb.append(" convertedFromValue: ").append(toIndentedString(convertedFromValue)).append("\n");
sb.append(" currency: ").append(toIndentedString(currency)).append("\n");
sb.append(" exchangeRate: ").append(toIndentedString(exchangeRate)).append("\n");
sb.append(" value: ").append(toIndentedString(value)).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\DisputeAmount.java
| 2
|
请完成以下Java代码
|
public static Color getColorForName(String name, Color defaultColor) {
if (HTMLColors.contains(name.toLowerCase()))
return (Color)HTMLColors.get(name.toLowerCase());
return defaultColor;
}
public static Color decodeColor(String color, Color defaultColor) {
String colorVal = "";
if (color.length() > 0) {
colorVal = color.trim();
if (colorVal.startsWith("#"))
colorVal = colorVal.substring(1);
try {
colorVal = new Integer(Integer.parseInt(colorVal, 16)).toString();
return Color.decode(colorVal.toLowerCase());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
else return defaultColor;
return getColorForName(color, defaultColor);
}
|
public static String encodeColor(Color color) {
return "#"+Integer.toHexString(color.getRGB()-0xFF000000).toUpperCase();
}
public static Color decodeColor(String color) {
return decodeColor(color, Color.white);
}
public static void setBgcolorField(JTextField field) {
Color c = Util.decodeColor(field.getText());
field.setBackground(c);
field.setForeground(new Color(~c.getRGB()));
}
public static void setColorField(JTextField field) {
Color c = Util.decodeColor(field.getText(), Color.black);
field.setForeground(c);
//field.setForeground(new Color(~c.getRGB()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\Util.java
| 1
|
请完成以下Java代码
|
public Properties getCtx()
{
return ctx;
}
@Override
public String getTrxName()
{
if (trx == null)
{
return ITrx.TRXNAME_None;
}
return trx.getTrxName();
}
@Override
public void setTrx(final ITrx trx)
{
this.trx = trx;
}
@Override
public ITrx getTrx()
{
return trx;
}
@Override
public IParams getParams()
|
{
return params;
}
public void setParams(IParams params)
{
this.params = params;
}
@Override
public String toString()
{
return "TrxItemProcessorContext [trx=" + trx + ", params=" + params + "]";
}
/**
* Returning <code>false</code> to ensure that the trx which was set via {@link #setTrx(ITrx)} is actually used, even if it's <code>null</code>.
*/
@Override
public boolean isAllowThreadInherited()
{
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemProcessorContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public OffsetDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Doctor doctor = (Doctor) o;
return Objects.equals(this._id, doctor._id) &&
Objects.equals(this.gender, doctor.gender) &&
Objects.equals(this.titleShort, doctor.titleShort) &&
Objects.equals(this.title, doctor.title) &&
Objects.equals(this.firstName, doctor.firstName) &&
Objects.equals(this.lastName, doctor.lastName) &&
Objects.equals(this.address, doctor.address) &&
Objects.equals(this.postalCode, doctor.postalCode) &&
Objects.equals(this.city, doctor.city) &&
Objects.equals(this.phone, doctor.phone) &&
Objects.equals(this.fax, doctor.fax) &&
Objects.equals(this.timestamp, doctor.timestamp);
}
@Override
public int hashCode() {
return Objects.hash(_id, gender, titleShort, title, firstName, lastName, address, postalCode, city, phone, fax, timestamp);
}
@Override
public String toString() {
|
StringBuilder sb = new StringBuilder();
sb.append("class Doctor {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" gender: ").append(toIndentedString(gender)).append("\n");
sb.append(" titleShort: ").append(toIndentedString(titleShort)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" address: ").append(toIndentedString(address)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" fax: ").append(toIndentedString(fax)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Doctor.java
| 2
|
请完成以下Java代码
|
public static boolean isMessyCode(String strName) {
//去除字符串中的空格 制表符 换行 回车
strName = specialSymbols(strName);
//处理之后转换成字符数组
char[] ch = strName.trim().toCharArray();
for (char c : ch) {
//判断是否是数字或者英文字符
if (!judge(c)) {
//判断是否是中日韩文
if (!isChinese(c)) {
//如果不是数字或者英文字符也不是中日韩文则表示是乱码返回true
return true;
}
}
}
//表示不是乱码 返回false
return false;
}
/**
* 读取文件目录树
*/
public static List<ZtreeNodeVo> getTree(String rootPath) {
List<ZtreeNodeVo> nodes = new ArrayList<>();
File file = new File(fileDir+rootPath);
ZtreeNodeVo node = traverse(file);
nodes.add(node);
return nodes;
}
private static ZtreeNodeVo traverse(File file) {
ZtreeNodeVo pathNodeVo = new ZtreeNodeVo();
pathNodeVo.setId(file.getAbsolutePath().replace(fileDir, "").replace("\\", "/"));
pathNodeVo.setName(file.getName());
pathNodeVo.setPid(file.getParent().replace(fileDir, "").replace("\\", "/"));
|
if (file.isDirectory()) {
List<ZtreeNodeVo> subNodeVos = new ArrayList<>();
File[] subFiles = file.listFiles();
if (subFiles == null) {
return pathNodeVo;
}
for (File subFile : subFiles) {
ZtreeNodeVo subNodeVo = traverse(subFile);
subNodeVos.add(subNodeVo);
}
pathNodeVo.setChildren(subNodeVos);
}
return pathNodeVo;
}
}
|
repos\kkFileView-master\server\src\main\java\cn\keking\utils\RarUtils.java
| 1
|
请完成以下Java代码
|
protected DeleteProcessInstanceBatchConfiguration createJobConfiguration(DeleteProcessInstanceBatchConfiguration configuration, List<String> processIdsForJob) {
return new DeleteProcessInstanceBatchConfiguration(
processIdsForJob,
null,
configuration.getDeleteReason(),
configuration.isSkipCustomListeners(),
configuration.isSkipSubprocesses(),
configuration.isFailIfNotExists(),
configuration.isSkipIoMappings()
);
}
@Override
public void executeHandler(DeleteProcessInstanceBatchConfiguration batchConfiguration,
ExecutionEntity execution,
CommandContext commandContext,
String tenantId) {
commandContext.executeWithOperationLogPrevented(
new DeleteProcessInstancesCmd(
batchConfiguration.getIds(),
batchConfiguration.getDeleteReason(),
batchConfiguration.isSkipCustomListeners(),
true,
batchConfiguration.isSkipSubprocesses(),
batchConfiguration.isFailIfNotExists(),
batchConfiguration.isSkipIoMappings()
));
}
|
@Override
protected void createJobEntities(BatchEntity batch, DeleteProcessInstanceBatchConfiguration configuration, String deploymentId, List<String> processIds,
int invocationsPerBatchJob) {
// handle legacy batch entities (no up-front deployment mapping has been done)
if (deploymentId == null && (configuration.getIdMappings() == null || configuration.getIdMappings().isEmpty())) {
// create deployment mappings for the ids to process
BatchElementConfiguration elementConfiguration = new BatchElementConfiguration();
ProcessInstanceQueryImpl query = new ProcessInstanceQueryImpl();
query.processInstanceIds(new HashSet<>(configuration.getIds()));
elementConfiguration.addDeploymentMappings(query.listDeploymentIdMappings(), configuration.getIds());
// create jobs by deployment id
elementConfiguration.getMappings().forEach(mapping -> super.createJobEntities(batch, configuration, mapping.getDeploymentId(),
mapping.getIds(processIds), invocationsPerBatchJob));
} else {
super.createJobEntities(batch, configuration, deploymentId, processIds, invocationsPerBatchJob);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\deletion\DeleteProcessInstancesJobHandler.java
| 1
|
请完成以下Java代码
|
public String toString() {
StringBuilder result = new StringBuilder();
result.append(super.toString());
result.append("ServiceUrl: ");
result.append(this.serviceUrl);
return result.toString();
}
/**
* If present, removes the artifactParameterName and the corresponding value from the
* query String.
* @param request
* @return the query String minus the artifactParameterName and the corresponding
* value.
*/
private @Nullable String getQueryString(final HttpServletRequest request, final Pattern artifactPattern) {
final String query = request.getQueryString();
if (query == null) {
return null;
}
String result = artifactPattern.matcher(query).replaceFirst("");
if (result.length() == 0) {
return null;
}
// strip off the trailing & only if the artifact was the first query param
return result.startsWith("&") ? result.substring(1) : result;
}
/**
|
* Creates a {@link Pattern} that can be passed into the constructor. This allows the
* {@link Pattern} to be reused for every instance of
* {@link DefaultServiceAuthenticationDetails}.
* @param artifactParameterName
* @return
*/
static Pattern createArtifactPattern(String artifactParameterName) {
Assert.hasLength(artifactParameterName, "artifactParameterName is expected to have a length");
return Pattern.compile("&?" + Pattern.quote(artifactParameterName) + "=[^&]*");
}
/**
* Gets the port from the casServiceURL ensuring to return the proper value if the
* default port is being used.
* @param casServiceUrl the casServerUrl to be used (i.e.
* "https://example.com/context/login/cas")
* @return the port that is configured for the casServerUrl
*/
private static int getServicePort(URL casServiceUrl) {
int port = casServiceUrl.getPort();
if (port == -1) {
port = casServiceUrl.getDefaultPort();
}
return port;
}
}
|
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\authentication\DefaultServiceAuthenticationDetails.java
| 1
|
请完成以下Java代码
|
public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor<LocalDate> {
public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
public LocalDateStringJavaDescriptor() {
super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE);
}
@Override
public String toString(LocalDate value) {
return DateTimeFormatter.ISO_LOCAL_DATE.format(value);
}
@Override
public LocalDate fromString(CharSequence string) {
return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse(string));
}
@Override
public <X> X unwrap(LocalDate value, Class<X> type, WrapperOptions options) {
if (value == null)
return null;
if (String.class.isAssignableFrom(type))
return (X) DateTimeFormatter.ISO_LOCAL_DATE.format(value);
throw unknownUnwrap(type);
}
|
@Override
public <X> LocalDate wrap(X value, WrapperOptions options) {
if (value == null)
return null;
if(String.class.isInstance(value))
return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse((CharSequence) value));
throw unknownWrap(value.getClass());
}
@Override
public BasicType<?> resolveType(TypeConfiguration typeConfiguration, Dialect dialect, BasicType basicType, ColumnTypeInformation columnTypeInformation, JdbcTypeIndicators jdbcTypeIndicators) {
return null;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\LocalDateStringJavaDescriptor.java
| 1
|
请完成以下Java代码
|
public class DrawSupersampledCircle {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame("SupersampledCircle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new CirclePanel());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
static class CirclePanel extends JPanel {
private final BufferedImage hiResImage;
private final int finalSize = 6;
public CirclePanel() {
int scale = 3;
float stroke = 6f;
hiResImage = makeSupersampledCircle(scale, stroke);
setPreferredSize(new Dimension(finalSize + 32, finalSize + 32));
setBackground(Color.WHITE);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
try {
int x = (getWidth() - finalSize) / 2;
int y = (getHeight() - finalSize) / 2;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.drawImage(hiResImage, x, y, finalSize, finalSize, null);
} finally {
g2.dispose();
|
}
}
private BufferedImage makeSupersampledCircle(int scale, float stroke) {
int hi = finalSize * scale;
BufferedImage img = new BufferedImage(hi, hi, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
double d = hi - stroke;
Shape circle = new Ellipse2D.Double(stroke / 2.0, stroke / 2.0, d, d);
g2.setPaint(new Color(0xBBDEFB));
g2.fill(circle);
g2.setPaint(new Color(0x0D47A1));
g2.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.draw(circle);
} finally {
g2.dispose();
}
return img;
}
}
}
|
repos\tutorials-master\image-processing\src\main\java\com\baeldung\drawcircle\DrawSupersampledCircle.java
| 1
|
请完成以下Java代码
|
public class BasicAuthenticationEncoder extends AbstractEncoder<UsernamePasswordMetadata> {
public BasicAuthenticationEncoder() {
super(UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE);
}
@Override
public Flux<DataBuffer> encode(Publisher<? extends UsernamePasswordMetadata> inputStream,
DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType,
@Nullable Map<String, Object> hints) {
return Flux.from(inputStream)
.map((credentials) -> encodeValue(credentials, bufferFactory, elementType, mimeType, hints));
}
@Override
public DataBuffer encodeValue(UsernamePasswordMetadata credentials, DataBufferFactory bufferFactory,
ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
String username = credentials.getUsername();
String password = credentials.getPassword();
byte[] usernameBytes = username.getBytes(StandardCharsets.UTF_8);
byte[] usernameBytesLengthBytes = ByteBuffer.allocate(4).putInt(usernameBytes.length).array();
DataBuffer metadata = bufferFactory.allocateBuffer();
boolean release = true;
|
try {
metadata.write(usernameBytesLengthBytes);
metadata.write(usernameBytes);
metadata.write(password.getBytes(StandardCharsets.UTF_8));
release = false;
return metadata;
}
finally {
if (release) {
DataBufferUtils.release(metadata);
}
}
}
}
|
repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\metadata\BasicAuthenticationEncoder.java
| 1
|
请完成以下Java代码
|
public int getC_BPartner_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set MSV3 Customer Config.
@param MSV3_Customer_Config_ID MSV3 Customer Config */
@Override
public void setMSV3_Customer_Config_ID (int MSV3_Customer_Config_ID)
{
if (MSV3_Customer_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_Customer_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_Customer_Config_ID, Integer.valueOf(MSV3_Customer_Config_ID));
}
/** Get MSV3 Customer Config.
@return MSV3 Customer Config */
@Override
public int getMSV3_Customer_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Customer_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Kennwort.
@param Password Kennwort */
@Override
public void setPassword (java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
|
}
/** Get Kennwort.
@return Kennwort */
@Override
public java.lang.String getPassword ()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
/** Set Nutzerkennung.
@param UserID Nutzerkennung */
@Override
public void setUserID (java.lang.String UserID)
{
set_Value (COLUMNNAME_UserID, UserID);
}
/** Get Nutzerkennung.
@return Nutzerkennung */
@Override
public java.lang.String getUserID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java-gen\de\metas\vertical\pharma\msv3\server\model\X_MSV3_Customer_Config.java
| 1
|
请完成以下Java代码
|
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setStartDay (final int StartDay)
{
set_Value (COLUMNNAME_StartDay, StartDay);
}
|
@Override
public int getStartDay()
{
return get_ValueAsInt(COLUMNNAME_StartDay);
}
@Override
public void setStartMonth (final int StartMonth)
{
set_Value (COLUMNNAME_StartMonth, StartMonth);
}
@Override
public int getStartMonth()
{
return get_ValueAsInt(COLUMNNAME_StartMonth);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscrDiscount_Line.java
| 1
|
请完成以下Java代码
|
public AdempiereException markAsUserValidationError()
{
userValidationError = true;
return this;
}
public final boolean isUserValidationError()
{
return userValidationError;
}
public static boolean isUserValidationError(final Throwable ex)
{
return (ex instanceof AdempiereException) && ((AdempiereException)ex).isUserValidationError();
}
/**
* Fluent version of {@link #addSuppressed(Throwable)}
*/
public AdempiereException suppressing(@NonNull final Throwable exception)
|
{
addSuppressed(exception);
return this;
}
/**
* Override with a method returning false if your exception is more of a signal than an error
* and shall not clutter the log when it is caught and rethrown by the transaction manager.
* <p>
* To be invoked by {@link AdempiereException#isThrowableLoggedInTrxManager(Throwable)}.
*/
protected boolean isLoggedInTrxManager()
{
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\AdempiereException.java
| 1
|
请完成以下Java代码
|
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public LocalDate getCreationDate() {
return creationDate;
}
public List<Possession> getPossessionList() {
return possessionList;
}
public void setPossessionList(List<Possession> possessionList) {
this.possessionList = possessionList;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [name=").append(name).append(", id=").append(id).append("]");
return builder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
age == user.age &&
Objects.equals(name, user.name) &&
|
Objects.equals(creationDate, user.creationDate) &&
Objects.equals(email, user.email) &&
Objects.equals(status, user.status);
}
@Override
public int hashCode() {
return Objects.hash(id, name, creationDate, age, email, status);
}
public LocalDate getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(LocalDate lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\User.java
| 1
|
请完成以下Java代码
|
public class OAuth2AuthorizationCodeAuthenticationProvider implements AuthenticationProvider {
private static final String INVALID_STATE_PARAMETER_ERROR_CODE = "invalid_state_parameter";
private final OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
/**
* Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the
* provided parameters.
* @param accessTokenResponseClient the client used for requesting the access token
* credential from the Token Endpoint
*/
public OAuth2AuthorizationCodeAuthenticationProvider(
OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange()
.getAuthorizationResponse();
if (authorizationResponse.statusError()) {
throw new OAuth2AuthorizationException(authorizationResponse.getError());
}
OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange()
|
.getAuthorizationRequest();
if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
throw new OAuth2AuthorizationException(oauth2Error);
}
OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenResponseClient.getTokenResponse(
new OAuth2AuthorizationCodeGrantRequest(authorizationCodeAuthentication.getClientRegistration(),
authorizationCodeAuthentication.getAuthorizationExchange()));
OAuth2AuthorizationCodeAuthenticationToken authenticationResult = new OAuth2AuthorizationCodeAuthenticationToken(
authorizationCodeAuthentication.getClientRegistration(),
authorizationCodeAuthentication.getAuthorizationExchange(), accessTokenResponse.getAccessToken(),
accessTokenResponse.getRefreshToken(), accessTokenResponse.getAdditionalParameters());
authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
return authenticationResult;
}
@Override
public boolean supports(Class<?> authentication) {
return OAuth2AuthorizationCodeAuthenticationToken.class.isAssignableFrom(authentication);
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\authentication\OAuth2AuthorizationCodeAuthenticationProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void sendSimpleMail(String to, String subject, String content, String... cc) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
if (ArrayUtil.isNotEmpty(cc)) {
message.setCc(cc);
}
mailSender.send(message);
}
/**
* 发送HTML邮件
*
* @param to 收件人地址
* @param subject 邮件主题
* @param content 邮件内容
* @param cc 抄送地址
* @throws MessagingException 邮件发送异常
*/
@Override
public void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (ArrayUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
mailSender.send(message);
}
/**
* 发送带附件的邮件
*
* @param to 收件人地址
* @param subject 邮件主题
* @param content 邮件内容
* @param filePath 附件地址
* @param cc 抄送地址
* @throws MessagingException 邮件发送异常
*/
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
|
if (ArrayUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
mailSender.send(message);
}
/**
* 发送正文中有静态资源的邮件
*
* @param to 收件人地址
* @param subject 邮件主题
* @param content 邮件内容
* @param rscPath 静态资源地址
* @param rscId 静态资源id
* @param cc 抄送地址
* @throws MessagingException 邮件发送异常
*/
@Override
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (ArrayUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
}
}
|
repos\spring-boot-demo-master\demo-email\src\main\java\com\xkcoding\email\service\impl\MailServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class BazzNewMappingsExampleController {
@GetMapping
public ResponseEntity<?> getBazzs() throws JsonProcessingException{
List<Bazz> data = Arrays.asList(
new Bazz("1", "Bazz1"),
new Bazz("2", "Bazz2"),
new Bazz("3", "Bazz3"),
new Bazz("4", "Bazz4"));
return new ResponseEntity<>(data, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<?> getBazz(@PathVariable String id){
return new ResponseEntity<>(new Bazz(id, "Bazz"+id), HttpStatus.OK);
}
@PostMapping
public ResponseEntity<?> newBazz(@RequestParam("name") String name){
|
return new ResponseEntity<>(new Bazz("5", name), HttpStatus.OK);
}
@PutMapping("/{id}")
public ResponseEntity<?> updateBazz(@PathVariable String id,
@RequestParam("name") String name){
return new ResponseEntity<>(new Bazz(id, name), HttpStatus.OK);
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteBazz(@PathVariable String id){
return new ResponseEntity<>(new Bazz(id), HttpStatus.OK);
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\requestmapping\BazzNewMappingsExampleController.java
| 2
|
请完成以下Java代码
|
public class ConditionalBranches {
/**
* Multiple if/else/else if statements examples. Shows different syntax usage.
*/
public static void ifElseStatementsExamples() {
int count = 2; // Initial count value.
// Basic syntax. Only one statement follows. No brace usage.
if (count > 1)
System.out.println("Count is higher than 1");
// Basic syntax. More than one statement can be included. Braces are used (recommended syntax).
if (count > 1) {
System.out.println("Count is higher than 1");
System.out.println("Count is equal to: " + count);
}
// If/Else syntax. Two different courses of action can be included.
if (count > 2) {
System.out.println("Count is higher than 2");
} else {
System.out.println("Count is lower or equal than 2");
}
// If/Else/Else If syntax. Three or more courses of action can be included.
if (count > 2) {
System.out.println("Count is higher than 2");
} else if (count <= 0) {
System.out.println("Count is less or equal than zero");
} else {
System.out.println("Count is either equal to one, or two");
}
}
/**
* Ternary Operator example.
* @see ConditionalBranches#ifElseStatementsExamples()
*/
public static void ternaryExample() {
int count = 2;
System.out.println(count > 2 ? "Count is higher than 2" : "Count is lower or equal than 2");
}
/**
* Switch structure example. Shows how to replace multiple if/else statements with one structure.
|
*/
public static void switchExample() {
int count = 3;
switch (count) {
case 0:
System.out.println("Count is equal to 0");
break;
case 1:
System.out.println("Count is equal to 1");
break;
case 2:
System.out.println("Count is equal to 2");
break;
default:
System.out.println("Count is either negative, or higher than 2");
break;
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-syntax\src\main\java\com\baeldung\core\controlstructures\ConditionalBranches.java
| 1
|
请完成以下Java代码
|
private ImportRecordResult doNothingAndUsePreviousDiscountSchema(@NonNull final I_I_DiscountSchema importRecord, @NonNull final I_I_DiscountSchema previousImportRecord)
{
importRecord.setM_DiscountSchema_ID(previousImportRecord.getM_DiscountSchema_ID());
InterfaceWrapperHelper.save(importRecord);
return ImportRecordResult.Nothing;
}
private void importDiscountSchemaBreak(@NonNull final I_I_DiscountSchema importRecord)
{
I_M_DiscountSchemaBreak schemaBreak = importRecord.getM_DiscountSchemaBreak();
if (schemaBreak == null)
{
schemaBreak = InterfaceWrapperHelper.create(getCtx(), I_M_DiscountSchemaBreak.class, ITrx.TRXNAME_ThreadInherited);
schemaBreak.setM_DiscountSchema_ID(importRecord.getM_DiscountSchema_ID());
}
setDiscountSchemaBreakFields(importRecord, schemaBreak);
ModelValidationEngine.get().fireImportValidate(this, importRecord, schemaBreak, IImportInterceptor.TIMING_AFTER_IMPORT);
InterfaceWrapperHelper.save(schemaBreak);
importRecord.setM_DiscountSchemaBreak_ID(schemaBreak.getM_DiscountSchemaBreak_ID());
}
private void setDiscountSchemaBreakFields(@NonNull final I_I_DiscountSchema importRecord, @NonNull final I_M_DiscountSchemaBreak schemaBreak)
{
schemaBreak.setSeqNo(10);
schemaBreak.setBreakDiscount(importRecord.getBreakDiscount());
schemaBreak.setBreakValue(importRecord.getBreakValue());
|
//
if (importRecord.getDiscount() != null && importRecord.getDiscount().signum() > 0)
{
schemaBreak.setPaymentDiscount(importRecord.getDiscount());
}
schemaBreak.setM_Product_ID(importRecord.getM_Product_ID());
schemaBreak.setC_PaymentTerm_ID(importRecord.getC_PaymentTerm_ID());
//
setPricingFields(importRecord, schemaBreak);
}
private void setPricingFields(@NonNull final I_I_DiscountSchema importRecord, @NonNull final I_M_DiscountSchemaBreak schemaBreak)
{
schemaBreak.setPriceBase(importRecord.getPriceBase());
schemaBreak.setBase_PricingSystem_ID(importRecord.getBase_PricingSystem_ID());
schemaBreak.setPriceStdFixed(importRecord.getPriceStdFixed());
schemaBreak.setPricingSystemSurchargeAmt(importRecord.getPricingSystemSurchargeAmt());
schemaBreak.setC_Currency_ID(importRecord.getC_Currency_ID());
}
@Override
protected void markImported(@NonNull final I_I_DiscountSchema importRecord)
{
importRecord.setI_IsImported(X_I_DiscountSchema.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\impexp\DiscountSchemaImportProcess.java
| 1
|
请完成以下Java代码
|
public Map<String, TriggerVariableValueDto> getVariables() {
return variables;
}
public void setVariables(Map<String, TriggerVariableValueDto> variables) {
this.variables = variables;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getTransitionId() {
return transitionId;
}
public void setTransitionId(String transitionId) {
this.transitionId = transitionId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getTransitionInstanceId() {
return transitionInstanceId;
}
public void setTransitionInstanceId(String transitionInstanceId) {
this.transitionInstanceId = transitionInstanceId;
}
public String getAncestorActivityInstanceId() {
return ancestorActivityInstanceId;
}
public void setAncestorActivityInstanceId(String ancestorActivityInstanceId) {
this.ancestorActivityInstanceId = ancestorActivityInstanceId;
}
public boolean isCancelCurrentActiveActivityInstances() {
return cancelCurrentActiveActivityInstances;
}
public void setCancelCurrentActiveActivityInstances(boolean cancelCurrentActiveActivityInstances) {
this.cancelCurrentActiveActivityInstances = cancelCurrentActiveActivityInstances;
|
}
public abstract void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper mapper);
public abstract void applyTo(InstantiationBuilder<?> builder, ProcessEngine engine, ObjectMapper mapper);
protected String buildErrorMessage(String message) {
return "For instruction type '" + type + "': " + message;
}
protected void applyVariables(ActivityInstantiationBuilder<?> builder,
ProcessEngine engine, ObjectMapper mapper) {
if (variables != null) {
for (Map.Entry<String, TriggerVariableValueDto> variableValue : variables.entrySet()) {
TriggerVariableValueDto value = variableValue.getValue();
if (value.isLocal()) {
builder.setVariableLocal(variableValue.getKey(), value.toTypedValue(engine, mapper));
}
else {
builder.setVariable(variableValue.getKey(), value.toTypedValue(engine, mapper));
}
}
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\modification\ProcessInstanceModificationInstructionDto.java
| 1
|
请完成以下Java代码
|
public void setValues(DmnElement otherElement) {
setId(otherElement.getId());
extensionElements = new LinkedHashMap<>();
if (otherElement.getExtensionElements() != null && !otherElement.getExtensionElements().isEmpty()) {
for (String key : otherElement.getExtensionElements().keySet()) {
List<DmnExtensionElement> otherElementList = otherElement.getExtensionElements().get(key);
if (otherElementList != null && !otherElementList.isEmpty()) {
List<DmnExtensionElement> elementList = new ArrayList<>();
for (DmnExtensionElement extensionElement : otherElementList) {
elementList.add(extensionElement.clone());
}
extensionElements.put(key, elementList);
}
}
}
|
attributes = new LinkedHashMap<>();
if (otherElement.getAttributes() != null && !otherElement.getAttributes().isEmpty()) {
for (String key : otherElement.getAttributes().keySet()) {
List<DmnExtensionAttribute> otherAttributeList = otherElement.getAttributes().get(key);
if (otherAttributeList != null && !otherAttributeList.isEmpty()) {
List<DmnExtensionAttribute> attributeList = new ArrayList<>();
for (DmnExtensionAttribute extensionAttribute : otherAttributeList) {
attributeList.add(extensionAttribute.clone());
}
attributes.put(key, attributeList);
}
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnElement.java
| 1
|
请完成以下Java代码
|
public void setSeqNo(final I_M_ProductPrice productPrice)
{
if (productPrice.getSeqNo() <= 0)
{
final int lastSeqNo = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_ProductPrice.class, productPrice)
.addEqualsFilter(I_M_ProductPrice.COLUMNNAME_M_PriceList_Version_ID, productPrice.getM_PriceList_Version_ID())
.addNotEqualsFilter(I_M_ProductPrice.COLUMNNAME_M_ProductPrice_ID, productPrice.getM_ProductPrice_ID())
.create()
.aggregate(I_M_ProductPrice.COLUMNNAME_SeqNo, Aggregate.MAX, int.class);
final int nextSeqNo = (lastSeqNo <= 0 ? 0 : lastSeqNo) / 10 * 10 + 10;
productPrice.setSeqNo(nextSeqNo);
}
}
/**
* Make sure Scale price and Attribute price are never both used.
*
* @param productPrice
*/
|
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_M_ProductPrice.COLUMNNAME_UseScalePrice,
I_M_ProductPrice.COLUMNNAME_IsAttributeDependant
})
public void checkFlags(final I_M_ProductPrice productPrice)
{
// Should never happen.
Check.assumeNotNull(productPrice, "Product price not null");
if (productPrice.isAttributeDependant() && !Objects.equals(productPrice.getUseScalePrice(), X_M_ProductPrice.USESCALEPRICE_DonTUseScalePrice))
{
final Properties ctx = InterfaceWrapperHelper.getCtx(productPrice);
throw new AdempiereException(Services.get(IMsgBL.class).getMsg(ctx, IPricingBL.PRODUCTPRICE_FLAG_ERROR));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\pricing\modelvalidator\M_ProductPrice.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void transferProdIdCountJson(OrderInsertReq orderInsertReq) {
if (orderInsertReq != null && StringUtils.isNotEmpty(orderInsertReq.getProdIdCountJson())) {
try {
Map<String, Long> prodIdCountMapPre = JSON.parse(orderInsertReq.getProdIdCountJson(), Map.class);
Map<String, Integer> prodIdCountMap = Maps.newHashMap();
if (prodIdCountMapPre.size() > 0) {
for (String key : prodIdCountMapPre.keySet()) {
prodIdCountMap.put(key, (Integer) prodIdCountMapPre.get(key).intValue());
}
}
orderInsertReq.setProdIdCountMap(prodIdCountMap);
} catch (ParseException e) {
throw new CommonBizException(ExpCodeEnum.JSONERROR);
}
}
}
@Override
public Result<String> pay(String orderId, HttpServletRequest httpReq) {
// 获取买家ID
String buyerId = getUserId(httpReq);
// 支付
String html = orderService.pay(orderId, buyerId);
// 成功
return Result.newSuccessResult(html);
}
@Override
public Result cancelOrder(String orderId, HttpServletRequest httpReq) {
// 获取买家ID
String buyerId = getUserId(httpReq);
// 取消订单
orderService.cancelOrder(orderId, buyerId);
// 成功
return Result.newSuccessResult();
}
@Override
public Result confirmDelivery(String orderId, String expressNo, HttpServletRequest httpReq) {
// 获取卖家ID
String sellerId = getUserId(httpReq);
|
// 确认收货
orderService.confirmDelivery(orderId, expressNo, sellerId);
// 成功
return Result.newSuccessResult();
}
@Override
public Result confirmReceive(String orderId, HttpServletRequest httpReq) {
// 获取买家ID
String buyerId = getUserId(httpReq);
// 确认收货
orderService.confirmReceive(orderId, buyerId);
// 成功
return Result.newSuccessResult();
}
/**
* 获取用户ID
* @param httpReq HTTP请求
* @return 用户ID
*/
private String getUserId(HttpServletRequest httpReq) {
UserEntity userEntity = userUtil.getUser(httpReq);
if (userEntity == null) {
throw new CommonBizException(ExpCodeEnum.UNLOGIN);
}
return userEntity.getId();
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\java\com\gaoxi\controller\order\OrderControllerImpl.java
| 2
|
请完成以下Java代码
|
private static void timeunitSleep(Integer iterations, Integer secondsToSleep) {
for (Integer i = 0; i < iterations; i++) {
System.out.println("This is loop iteration number " + i.toString());
try {
TimeUnit.SECONDS.sleep(secondsToSleep);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
private static void delayedServiceTask(Integer delayInSeconds) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule(Delay::someTask1, delayInSeconds, TimeUnit.SECONDS);
executorService.shutdown();
}
private static void fixedRateServiceTask(Integer delayInSeconds) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
|
ScheduledFuture<?> sf = executorService.scheduleAtFixedRate(Delay::someTask2, 0, delayInSeconds,
TimeUnit.SECONDS);
try {
TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
sf.cancel(true);
executorService.shutdown();
}
private static void someTask1() {
System.out.println("Task 1 completed.");
}
private static void someTask2() {
System.out.println("Task 2 completed.");
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-basic\src\main\java\com\baeldung\concurrent\delay\Delay.java
| 1
|
请完成以下Java代码
|
public Properties getCtx()
{
return InterfaceWrapperHelper.getCtx(candidate);
}
@Override
public I_C_BPartner getC_BPartner()
{
return candidate.getC_BPartner();
}
@Override
public boolean isContractedProduct()
{
final I_C_Flatrate_DataEntry flatrateDataEntry = getC_Flatrate_DataEntry();
if (flatrateDataEntry == null)
{
return false;
}
// Consider that we have a contracted product only if the data entry has the Price or the QtyPlanned set (FRESH-568)
return Services.get(IPMMContractsBL.class).hasPriceOrQty(flatrateDataEntry);
}
@Override
public I_M_Product getM_Product()
{
return candidate.getM_Product();
}
@Override
public int getProductId()
{
return candidate.getM_Product_ID();
}
@Override
public I_C_UOM getC_UOM()
{
return candidate.getC_UOM();
}
@Override
public I_C_Flatrate_Term getC_Flatrate_Term()
{
final I_C_Flatrate_DataEntry flatrateDataEntry = getC_Flatrate_DataEntry();
if(flatrateDataEntry == null)
{
return null;
}
return flatrateDataEntry.getC_Flatrate_Term();
}
@Override
public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry()
{
return InterfaceWrapperHelper.create(candidate.getC_Flatrate_DataEntry(), I_C_Flatrate_DataEntry.class);
}
@Override
|
public Object getWrappedModel()
{
return candidate;
}
@Override
public Timestamp getDate()
{
return candidate.getDatePromised();
}
@Override
public BigDecimal getQty()
{
// TODO: shall we use QtyToOrder instead... but that could affect our price (if we have some prices defined on breaks)
return candidate.getQtyPromised();
}
@Override
public void setM_PricingSystem_ID(int M_PricingSystem_ID)
{
candidate.setM_PricingSystem_ID(M_PricingSystem_ID);
}
@Override
public void setM_PriceList_ID(int M_PriceList_ID)
{
candidate.setM_PriceList_ID(M_PriceList_ID);
}
@Override
public void setCurrencyId(final CurrencyId currencyId)
{
candidate.setC_Currency_ID(CurrencyId.toRepoId(currencyId));
}
@Override
public void setPrice(BigDecimal priceStd)
{
candidate.setPrice(priceStd);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPricingAware_PurchaseCandidate.java
| 1
|
请完成以下Java代码
|
public class BasicAuthenticationDecoder extends AbstractDecoder<UsernamePasswordMetadata> {
public BasicAuthenticationDecoder() {
super(UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE);
}
@Override
public Flux<UsernamePasswordMetadata> decode(Publisher<DataBuffer> input, ResolvableType elementType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
return Flux.from(input).map(DataBuffer::asByteBuffer).map((byteBuffer) -> {
byte[] sizeBytes = new byte[4];
byteBuffer.get(sizeBytes);
int usernameSize = 4;
byte[] usernameBytes = new byte[usernameSize];
byteBuffer.get(usernameBytes);
byte[] passwordBytes = new byte[byteBuffer.remaining()];
byteBuffer.get(passwordBytes);
String username = new String(usernameBytes);
String password = new String(passwordBytes);
return new UsernamePasswordMetadata(username, password);
});
}
|
@Override
public Mono<UsernamePasswordMetadata> decodeToMono(Publisher<DataBuffer> input, ResolvableType elementType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
return Mono.from(input).map(DataBuffer::asByteBuffer).map((byteBuffer) -> {
int usernameSize = byteBuffer.getInt();
byte[] usernameBytes = new byte[usernameSize];
byteBuffer.get(usernameBytes);
byte[] passwordBytes = new byte[byteBuffer.remaining()];
byteBuffer.get(passwordBytes);
String username = new String(usernameBytes);
String password = new String(passwordBytes);
return new UsernamePasswordMetadata(username, password);
});
}
}
|
repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\metadata\BasicAuthenticationDecoder.java
| 1
|
请完成以下Java代码
|
public class QueryMaxResultsLimitUtil {
public static void checkMaxResultsLimit(int resultsCount, int maxResultsLimit,
boolean isUserAuthenticated) {
if (isUserAuthenticated && maxResultsLimit < Integer.MAX_VALUE) {
if (resultsCount == Integer.MAX_VALUE) {
throw new BadUserRequestException("An unbound number of results is forbidden!");
} else if (resultsCount > maxResultsLimit) {
throw new BadUserRequestException("Max results limit of " + maxResultsLimit + " exceeded!");
}
}
}
public static void checkMaxResultsLimit(int resultsCount,
ProcessEngineConfigurationImpl processEngineConfig) {
// method is used in webapps
int maxResultsLimit = processEngineConfig.getQueryMaxResultsLimit();
checkMaxResultsLimit(resultsCount, maxResultsLimit, isUserAuthenticated(processEngineConfig));
}
public static void checkMaxResultsLimit(int resultsCount) {
ProcessEngineConfigurationImpl processEngineConfiguration =
Context.getProcessEngineConfiguration();
if (processEngineConfiguration == null) {
throw new ProcessEngineException("Command context unset.");
}
checkMaxResultsLimit(resultsCount, getMaxResultsLimit(processEngineConfiguration),
isUserAuthenticated(processEngineConfiguration));
}
|
protected static boolean isUserAuthenticated(ProcessEngineConfigurationImpl processEngineConfig) {
String userId = getAuthenticatedUserId(processEngineConfig);
return userId != null && !userId.isEmpty();
}
protected static String getAuthenticatedUserId(
ProcessEngineConfigurationImpl processEngineConfig) {
IdentityService identityService = processEngineConfig.getIdentityService();
Authentication currentAuthentication = identityService.getCurrentAuthentication();
if(currentAuthentication == null) {
return null;
} else {
return currentAuthentication.getUserId();
}
}
protected static int getMaxResultsLimit(ProcessEngineConfigurationImpl processEngineConfig) {
return processEngineConfig.getQueryMaxResultsLimit();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\QueryMaxResultsLimitUtil.java
| 1
|
请完成以下Java代码
|
public class DefaultScriptTrace implements ScriptTrace, ScriptTraceEnhancer.ScriptTraceContext {
protected Duration duration;
protected ScriptEngineRequest request;
protected Throwable exception;
protected Map<String, String> traceTags = new LinkedHashMap<>();
public DefaultScriptTrace(Duration duration, ScriptEngineRequest request, Throwable caughtException) {
this.duration = duration;
this.request = request;
this.exception = caughtException;
}
public static DefaultScriptTrace successTrace(Duration duration, ScriptEngineRequest request) {
return new DefaultScriptTrace(duration, request, null);
}
public static DefaultScriptTrace errorTrace(Duration duration, ScriptEngineRequest request, Throwable caughtException) {
return new DefaultScriptTrace(duration, request, caughtException);
}
@Override
public ScriptTraceEnhancer.ScriptTraceContext addTraceTag(String tag, String value) {
this.traceTags.put(tag, value);
return this;
}
@Override
public ScriptEngineRequest getRequest() {
return request;
}
|
@Override
public Throwable getException() {
return exception;
}
@Override
public Map<String, String> getTraceTags() {
return traceTags;
}
@Override
public Duration getDuration() {
return duration;
}
@Override
public String toString() {
return new StringJoiner(", ", DefaultScriptTrace.class.getSimpleName() + "[", "]")
.add("duration=" + duration)
.add("request=" + request)
.add("exception=" + exception)
.add("traceTags=" + traceTags)
.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\DefaultScriptTrace.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setResourceSuffixes(List<String> resourceSuffixes) {
this.resourceSuffixes = resourceSuffixes;
}
public boolean isDeployResources() {
return deployResources;
}
public void setDeployResources(boolean deployResources) {
this.deployResources = deployResources;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isHistoryEnabled() {
return historyEnabled;
}
public void setHistoryEnabled(boolean historyEnabled) {
|
this.historyEnabled = historyEnabled;
}
public boolean isEnableSafeXml() {
return enableSafeXml;
}
public void setEnableSafeXml(boolean enableSafeXml) {
this.enableSafeXml = enableSafeXml;
}
public boolean isStrictMode() {
return strictMode;
}
public void setStrictMode(boolean strictMode) {
this.strictMode = strictMode;
}
public FlowableServlet getServlet() {
return servlet;
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\dmn\FlowableDmnProperties.java
| 2
|
请完成以下Java代码
|
class Animal {
}
class Dog extends Animal {
}
class Lion extends Animal {
}
public class ClassCast {
private static Logger LOGGER = LoggerFactory.getLogger(ClassCast.class);
|
public static void main(String[] args) {
try {
Animal animalOne = new Dog(); // At runtime the instance is dog
Dog bruno = (Dog) animalOne; // Downcasting
Animal animalTwo = new Lion(); // At runtime the instance is animal
Dog tommy = (Dog) animalTwo; // Downcasting
} catch (ClassCastException e) {
LOGGER.error("ClassCastException caught!");
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-exceptions-5\src\main\java\com\baeldung\exceptions\common\ClassCast.java
| 1
|
请完成以下Java代码
|
public Author author() {
return new Author(this, Keys.ARTICLE__XXX);
}
@Override
public Article as(String alias) {
return new Article(DSL.name(alias), this);
}
@Override
public Article as(Name alias) {
return new Article(alias, this);
}
/**
* Rename this table
*/
@Override
public Article rename(String name) {
return new Article(DSL.name(name), null);
|
}
/**
* Rename this table
*/
@Override
public Article rename(Name name) {
return new Article(name, null);
}
// -------------------------------------------------------------------------
// Row4 type methods
// -------------------------------------------------------------------------
@Override
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
}
|
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\Article.java
| 1
|
请完成以下Java代码
|
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity completeDistributionWFActivity)
{
final HUConsolidationJob job = getHUConsolidationJob(wfProcess);
return computeActivityState(job);
}
public static WFActivityStatus computeActivityState(final HUConsolidationJob ignoredJob)
{
// TODO
return WFActivityStatus.NOT_STARTED;
}
private JsonHUConsolidationJob toJson(@NonNull final HUConsolidationJob job)
{
final RenderedAddressProvider renderedAddressProvider = documentLocationBL.newRenderedAddressProvider();
final String shipToAddress = renderedAddressProvider.getAddress(job.getShipToBPLocationId());
return JsonHUConsolidationJob.builder()
.id(job.getId())
.shipToAddress(shipToAddress)
.pickingSlots(toJsonHUConsolidationJobPickingSlots(job.getPickingSlotIds()))
.currentTarget(JsonHUConsolidationTarget.ofNullable(job.getCurrentTarget()))
.build();
|
}
private ImmutableList<JsonHUConsolidationJobPickingSlot> toJsonHUConsolidationJobPickingSlots(final Set<PickingSlotId> pickingSlotIds)
{
if (pickingSlotIds.isEmpty())
{
return ImmutableList.of();
}
final Set<PickingSlotIdAndCaption> pickingSlotIdAndCaptions = pickingSlotService.getPickingSlotIdAndCaptions(pickingSlotIds);
final PickingSlotQueuesSummary summary = pickingSlotService.getNotEmptyQueuesSummary(PickingSlotQueueQuery.onlyPickingSlotIds(pickingSlotIds));
return pickingSlotIdAndCaptions.stream()
.map(pickingSlotIdAndCaption -> JsonHUConsolidationJobPickingSlot.builder()
.pickingSlotId(pickingSlotIdAndCaption.getPickingSlotId())
.pickingSlotQRCode(PickingSlotQRCode.ofPickingSlotIdAndCaption(pickingSlotIdAndCaption).toPrintableQRCode().toJsonDisplayableQRCode())
.countHUs(summary.getCountHUs(pickingSlotIdAndCaption.getPickingSlotId()).orElse(0))
.build())
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\workflows_api\activity_handlers\HUConsolidateWFActivityHandler.java
| 1
|
请完成以下Java代码
|
public final class CustomizableThreadFactory implements ThreadFactory
{
public static final Builder builder()
{
return new Builder();
}
/**
* Counts the instances of CustomizableThreadFactory and includes the number in each instance's thread name prefix.
*/
private static final AtomicInteger poolNumber = new AtomicInteger(1);
/**
* Thread group used to create to new threads
*/
private final ThreadGroup group;
/**
* Current thread number in this factory.
*/
private final AtomicInteger threadNumber = new AtomicInteger(1);
/**
* Name prefix to be used when creating new threads
*/
private final String namePrefix;
/**
* Shall we create Daemon threads?
*/
private final boolean daemon;
private CustomizableThreadFactory(final Builder builder)
{
super();
final SecurityManager s = System.getSecurityManager();
this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.namePrefix = builder.getThreadNamePrefix() + "-pool-" + poolNumber.getAndIncrement() + "-thread-";
this.daemon = builder.isDaemon();
}
/**
* {@inheritDoc}
*
* <p>
* This implementation creates a new thread with priority {@link Thread#NORM_PRIORITY}, using {@link #isDaemon()} to decide if the thread shall be a daemon thread or not.
*/
@Override
public Thread newThread(Runnable r)
{
String threadName = namePrefix + threadNumber.getAndIncrement();
final Thread t = new Thread(group, r, threadName, 0); // stackSize=0
if (t.isDaemon() != daemon)
{
t.setDaemon(daemon);
}
if (t.getPriority() != Thread.NORM_PRIORITY)
{
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
/**
* @return the daemon
*/
public boolean isDaemon()
{
return daemon;
}
public static final class Builder
|
{
private String threadNamePrefix;
private boolean daemon = false;
private Builder()
{
super();
}
public CustomizableThreadFactory build()
{
return new CustomizableThreadFactory(this);
}
public Builder setThreadNamePrefix(String threadNamePrefix)
{
this.threadNamePrefix = threadNamePrefix;
return this;
}
private final String getThreadNamePrefix()
{
Check.assumeNotEmpty(threadNamePrefix, "threadNamePrefix not empty");
return threadNamePrefix;
}
/**
* Decides if the threads shall be daemon threads or user threads.
*
* @param daemon the daemon to set
*/
public Builder setDaemon(boolean daemon)
{
this.daemon = daemon;
return this;
}
private final boolean isDaemon()
{
return daemon;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\CustomizableThreadFactory.java
| 1
|
请完成以下Java代码
|
SingleCommentResponse postComment(
AuthToken commenterToken, @PathVariable String slug, @RequestBody WriteCommentRequest request) {
var article = articleService.getArticle(slug);
var commenter = userService.getUser(commenterToken.userId());
var comment = articleCommentService.write(
new ArticleComment(article, commenter, request.comment().body()));
return new SingleCommentResponse(comment);
}
@GetMapping("/api/articles/{slug}/comments")
MultipleCommentsResponse getComment(AuthToken readersToken, @PathVariable String slug) {
var article = articleService.getArticle(slug);
var comments = articleCommentService.getComments(article);
if (this.isAnonymousUser(readersToken)) {
return new MultipleCommentsResponse(
comments.stream().map(ArticleCommentResponse::new).toList());
}
|
var reader = userService.getUser(readersToken.userId());
return new MultipleCommentsResponse(comments.stream()
.map(comment -> new ArticleCommentResponse(
comment, userRelationshipService.isFollowing(reader, comment.getAuthor())))
.toList());
}
@SuppressWarnings("MVCPathVariableInspection")
@DeleteMapping("/api/articles/{slug}/comments/{id}")
void deleteComment(AuthToken commenterToken, @PathVariable("id") int commentId) {
var commenter = userService.getUser(commenterToken.userId());
var comment = articleCommentService.getComment(commentId);
articleCommentService.delete(commenter, comment);
}
}
|
repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\api\ArticleCommentController.java
| 1
|
请完成以下Java代码
|
class FilteredReactiveWebContextResource extends AbstractResource {
private final String path;
FilteredReactiveWebContextResource(String path) {
this.path = path;
}
@Override
public boolean exists() {
return false;
}
@Override
public Resource createRelative(String relativePath) throws IOException {
|
String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
return new FilteredReactiveWebContextResource(pathToUse);
}
@Override
public String getDescription() {
return "ReactiveWebContext resource [" + this.path + "]";
}
@Override
public InputStream getInputStream() throws IOException {
throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\context\reactive\FilteredReactiveWebContextResource.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setProductName (final java.lang.String ProductName)
{
set_Value (COLUMNNAME_ProductName, ProductName);
}
@Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setScannedBarcode (final @Nullable java.lang.String ScannedBarcode)
{
set_Value (COLUMNNAME_ScannedBarcode, ScannedBarcode);
}
@Override
|
public java.lang.String getScannedBarcode()
{
return get_ValueAsString(COLUMNNAME_ScannedBarcode);
}
@Override
public void setTaxAmt (final BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_OrderLine.java
| 2
|
请完成以下Java代码
|
public final class DefaultMessageSecurityMetadataSource implements MessageSecurityMetadataSource {
private final Map<MessageMatcher<?>, Collection<ConfigAttribute>> messageMap;
public DefaultMessageSecurityMetadataSource(
LinkedHashMap<MessageMatcher<?>, Collection<ConfigAttribute>> messageMap) {
this.messageMap = messageMap;
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
final Message message = (Message) object;
for (Map.Entry<MessageMatcher<?>, Collection<ConfigAttribute>> entry : this.messageMap.entrySet()) {
if (entry.getKey().matches(message)) {
return entry.getValue();
}
}
|
return Collections.emptyList();
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
Set<ConfigAttribute> allAttributes = new HashSet<>();
for (Collection<ConfigAttribute> entry : this.messageMap.values()) {
allAttributes.addAll(entry);
}
return allAttributes;
}
@Override
public boolean supports(Class<?> clazz) {
return Message.class.isAssignableFrom(clazz);
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\messaging\access\intercept\DefaultMessageSecurityMetadataSource.java
| 1
|
请完成以下Java代码
|
public class FileProperties {
/** 文件大小限制 */
private Long maxSize;
/** 头像大小限制 */
private Long avatarMaxSize;
private ElPath mac;
private ElPath linux;
private ElPath windows;
public ElPath getPath(){
String os = System.getProperty("os.name");
if(os.toLowerCase().startsWith(ElConstant.WIN)) {
|
return windows;
} else if(os.toLowerCase().startsWith(ElConstant.MAC)){
return mac;
}
return linux;
}
@Data
public static class ElPath{
private String path;
private String avatar;
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\properties\FileProperties.java
| 1
|
请完成以下Java代码
|
public void put(K key, V value) {
V previousValue = delegate.put(key, value);
if (previousValue == null) {
keys.add(key);
keyToIndex.put(key, keys.size() - 1);
}
}
public V remove(K key) {
V removedValue = delegate.remove(key);
if (removedValue != null) {
Integer index = keyToIndex.remove(key);
if (index != null) {
removeKeyAtIndex(index);
}
}
return removedValue;
}
private void removeKeyAtIndex(int index) {
int lastIndex = keys.size() - 1;
if (index == lastIndex) {
keys.remove(lastIndex);
return;
}
|
K lastKey = keys.get(lastIndex);
keys.set(index, lastKey);
keyToIndex.put(lastKey, index);
keys.remove(lastIndex);
}
public V getRandomValue() {
if (keys.isEmpty()) {
return null;
}
int randomIndex = ThreadLocalRandom.current().nextInt(keys.size());
K randomKey = keys.get(randomIndex);
return delegate.get(randomKey);
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-maps-9\src\main\java\com\baeldung\map\randommapkey\OptimizedRandomKeyTrackingMap.java
| 1
|
请完成以下Java代码
|
public void afterPropertiesSet() throws Exception {
Assert.state(this.dataSource != null, "DataSource for DataSourceHealthIndicator must be specified");
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
if (this.dataSource == null) {
builder.up().withDetail("database", "unknown");
}
else {
doDataSourceHealthCheck(builder);
}
}
private void doDataSourceHealthCheck(Health.Builder builder) {
Assert.state(this.jdbcTemplate != null, "'jdbcTemplate' must not be null");
builder.up().withDetail("database", getProduct(this.jdbcTemplate));
String validationQuery = this.query;
if (StringUtils.hasText(validationQuery)) {
builder.withDetail("validationQuery", validationQuery);
// Avoid calling getObject as it breaks MySQL on Java 7 and later
List<Object> results = this.jdbcTemplate.query(validationQuery, new SingleColumnRowMapper());
Object result = DataAccessUtils.requiredSingleResult(results);
builder.withDetail("result", result);
}
else {
builder.withDetail("validationQuery", "isValid()");
boolean valid = isConnectionValid(this.jdbcTemplate);
builder.status((valid) ? Status.UP : Status.DOWN);
}
}
private String getProduct(JdbcTemplate jdbcTemplate) {
return jdbcTemplate.execute((ConnectionCallback<String>) this::getProduct);
}
private String getProduct(Connection connection) throws SQLException {
return connection.getMetaData().getDatabaseProductName();
}
private Boolean isConnectionValid(JdbcTemplate jdbcTemplate) {
return jdbcTemplate.execute((ConnectionCallback<Boolean>) this::isConnectionValid);
}
private Boolean isConnectionValid(Connection connection) throws SQLException {
return connection.isValid(0);
}
/**
* Set the {@link DataSource} to use.
* @param dataSource the data source
*/
public void setDataSource(DataSource dataSource) {
|
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
/**
* Set a specific validation query to use to validate a connection. If none is set, a
* validation based on {@link Connection#isValid(int)} is used.
* @param query the validation query to use
*/
public void setQuery(String query) {
this.query = query;
}
/**
* Return the validation query or {@code null}.
* @return the query
*/
public @Nullable String getQuery() {
return this.query;
}
/**
* {@link RowMapper} that expects and returns results from a single column.
*/
private static final class SingleColumnRowMapper implements RowMapper<Object> {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
if (columns != 1) {
throw new IncorrectResultSetColumnCountException(1, columns);
}
Object result = JdbcUtils.getResultSetValue(rs, 1);
Assert.state(result != null, "'result' must not be null");
return result;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\health\DataSourceHealthIndicator.java
| 1
|
请完成以下Java代码
|
public String getGroup() {
return group;
}
public WeightConfig setGroup(String group) {
this.group = group;
return this;
}
public String getRouteId() {
return routeId;
}
public WeightConfig setRouteId(String routeId) {
this.routeId = routeId;
return this;
}
|
public int getWeight() {
return weight;
}
public WeightConfig setWeight(int weight) {
this.weight = weight;
return this;
}
@Override
public String toString() {
return new ToStringCreator(this).append("group", group)
.append("routeId", routeId)
.append("weight", weight)
.toString();
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\WeightConfig.java
| 1
|
请完成以下Java代码
|
private boolean isPassedToParent(Throwable ex) {
return isLogConfigurationMessage(ex) || !isRegistered(ex);
}
/**
* Check if the exception is a log configuration message, i.e. the log call might not
* have actually output anything.
* @param ex the source exception
* @return {@code true} if the exception contains a log configuration message
*/
private boolean isLogConfigurationMessage(@Nullable Throwable ex) {
if (ex == null) {
return false;
}
if (ex instanceof InvocationTargetException) {
return isLogConfigurationMessage(ex.getCause());
}
String message = ex.getMessage();
if (message != null) {
for (String candidate : LOG_CONFIGURATION_MESSAGES) {
if (message.contains(candidate)) {
return true;
}
}
}
return false;
}
private boolean isRegistered(@Nullable Throwable ex) {
if (ex == null) {
return false;
}
if (this.loggedExceptions.contains(ex)) {
return true;
}
if (ex instanceof InvocationTargetException) {
return isRegistered(ex.getCause());
}
return false;
}
|
static SpringBootExceptionHandler forCurrentThread() {
return handler.get();
}
/**
* Thread local used to attach and track handlers.
*/
private static final class LoggedExceptionHandlerThreadLocal extends ThreadLocal<SpringBootExceptionHandler> {
@Override
protected SpringBootExceptionHandler initialValue() {
SpringBootExceptionHandler handler = new SpringBootExceptionHandler(
Thread.currentThread().getUncaughtExceptionHandler());
Thread.currentThread().setUncaughtExceptionHandler(handler);
return handler;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringBootExceptionHandler.java
| 1
|
请完成以下Java代码
|
public void detectedPa(Class<?> paClass) {
logInfo(
"015",
"Detected @ProcessApplication class '{}'",
paClass.getName());
}
public void alreadyDeployed() {
logWarn(
"016",
"Ignoring call of deploy() on process application that is already deployed.");
}
public void notDeployed() {
logWarn(
"017",
"Calling undeploy() on process application that is not deployed.");
}
public void couldNotRemoveDefinitionsFromCache(Throwable t) {
logError(
"018",
"Unregistering process application for deployment but could not remove process definitions from deployment cache.", t);
}
public ProcessEngineException exceptionWhileRegisteringDeploymentsWithJobExecutor(Exception e) {
return new ProcessEngineException(exceptionMessage(
"019",
"Exception while registering deployment with job executor"), e);
}
public void exceptionWhileUnregisteringDeploymentsWithJobExecutor(Exception e) {
logError(
"020",
"Exceptions while unregistering deployments with job executor", e);
}
public void registrationSummary(String string) {
logInfo(
"021",
string);
}
public void exceptionWhileLoggingRegistrationSummary(Throwable e) {
logError(
"022",
"Exception while logging registration summary",
|
e);
}
public boolean isContextSwitchLoggable() {
return isDebugEnabled();
}
public void debugNoTargetProcessApplicationFound(ExecutionEntity execution, ProcessApplicationManager processApplicationManager) {
logDebug("023",
"No target process application found for Execution[{}], ProcessDefinition[{}], Deployment[{}] Registrations[{}]",
execution.getId(),
execution.getProcessDefinitionId(),
execution.getProcessDefinition().getDeploymentId(),
processApplicationManager.getRegistrationSummary());
}
public void debugNoTargetProcessApplicationFoundForCaseExecution(CaseExecutionEntity execution, ProcessApplicationManager processApplicationManager) {
logDebug("024",
"No target process application found for CaseExecution[{}], CaseDefinition[{}], Deployment[{}] Registrations[{}]",
execution.getId(),
execution.getCaseDefinitionId(),
((CaseDefinitionEntity)execution.getCaseDefinition()).getDeploymentId(),
processApplicationManager.getRegistrationSummary());
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\ProcessApplicationLogger.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Author fetchAuthorReadOnlyMode() {
System.out.println("Persistent Context before fetching read-only entity:");
briefOverviewOfPersistentContextContent();
Author author = authorRepository.findByName("Joana Nimar");
System.out.println("\n\nPersistent Context after fetching read-only entity:");
briefOverviewOfPersistentContextContent();
return author;
}
@Transactional
public void updateAuthor(Author author) {
authorRepository.save(author);
System.out.println("\n\nPersistent Context after update the entity:");
briefOverviewOfPersistentContextContent();
}
private void briefOverviewOfPersistentContextContent() {
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
int managedEntities = persistenceContext.getNumberOfManagedEntities();
Map collectionEntries = persistenceContext.getCollectionEntries();
System.out.println("\n-----------------------------------");
System.out.println("Total number of managed entities: " + managedEntities);
if (collectionEntries != null) {
|
System.out.println("Total number of collection entries: "
+ (collectionEntries.values().size()));
}
Map entities = persistenceContext.getEntitiesByKey();
entities.forEach((key, value) -> System.out.println(key + ":" + value));
entities.values().forEach(entry
-> {
EntityEntry ee = persistenceContext.getEntry(entry);
System.out.println(
"Entity name: " + ee.getEntityName()
+ " | Status: " + ee.getStatus()
+ " | State: " + Arrays.toString(ee.getLoadedState()));
});
System.out.println("\n-----------------------------------\n");
}
private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() {
SharedSessionContractImplementor sharedSession = entityManager.unwrap(
SharedSessionContractImplementor.class
);
return sharedSession.getPersistenceContext();
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootReadOnlyQueries\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setAD_Window(org.compiere.model.I_AD_Window AD_Window)
{
set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window);
}
/** Set Fenster.
@param AD_Window_ID
Data entry or display window
*/
@Override
public void setAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Window_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID));
}
/** Get Fenster.
@return Data entry or display window
*/
@Override
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
|
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lesen und Schreiben.
@param IsReadWrite
Field is read / write
*/
@Override
public void setIsReadWrite (boolean IsReadWrite)
{
set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite));
}
/** Get Lesen und Schreiben.
@return Field is read / write
*/
@Override
public boolean isReadWrite ()
{
Object oo = get_Value(COLUMNNAME_IsReadWrite);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Window_Access.java
| 1
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext) {
if (deploymentId == null) {
throw new FlowableIllegalArgumentException("deploymentId is null");
}
// Update all entities
DmnDeploymentEntity deployment = CommandContextUtil.getDeploymentEntityManager(commandContext).findById(deploymentId);
if (deployment == null) {
throw new FlowableObjectNotFoundException("Could not find deployment with id " + deploymentId);
}
deployment.setTenantId(newTenantId);
// Doing process instances, executions and tasks with direct SQL updates
// (otherwise would not be performant)
|
CommandContextUtil.getDecisionEntityManager(commandContext).updateDecisionTenantIdForDeployment(deploymentId, newTenantId);
// Doing decision tables in memory, cause we need to clear the decision table cache
List<DmnDecision> decisionTables = new DecisionQueryImpl().deploymentId(deploymentId).list();
for (DmnDecision decisionTable : decisionTables) {
CommandContextUtil.getDmnEngineConfiguration().getDefinitionCache().remove(decisionTable.getId());
}
CommandContextUtil.getDeploymentEntityManager(commandContext).update(deployment);
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\cmd\SetDeploymentTenantIdCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private List<I_AD_PrinterRouting> fetchPrinterRoutings0(@NonNull final PrinterRoutingsQuery query)
{
logger.debug("fetchPrinterRoutings - Invoked with query={}", query);
final IQueryBuilder<I_AD_Printer> printerQueryBuilder = queryBL
.createQueryBuilder(I_AD_Printer.class)// only routings that reference active printers
.addOnlyActiveRecordsFilter();
if (Check.isNotBlank(query.getPrinterType()))
{
printerQueryBuilder.addEqualsFilter(I_AD_Printer.COLUMNNAME_PrinterType, query.getPrinterType());
}
final IQueryBuilder<I_AD_PrinterRouting> routingQueryBuilder = printerQueryBuilder
.andCollectChildren(I_AD_PrinterRouting.COLUMN_AD_Printer_ID)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_AD_PrinterRouting.COLUMNNAME_AD_Client_ID, query.getClientId(), ClientId.SYSTEM)
.addInArrayFilter(I_AD_PrinterRouting.COLUMNNAME_AD_Org_ID, query.getOrgId(), OrgId.ANY);
if (query.getDocTypeId() != null)
{ // do allow printer-routings without a doctype, but order such that they come last ("NULLS LAST")
routingQueryBuilder.addInArrayFilter(I_AD_PrinterRouting.COLUMNNAME_C_DocType_ID, query.getDocTypeId(), null);
routingQueryBuilder.orderBy(I_AD_PrinterRouting.COLUMNNAME_C_DocType_ID);
}
if (query.getProcessId() != null)
{
routingQueryBuilder.addInArrayFilter(I_AD_PrinterRouting.COLUMNNAME_AD_Process_ID, query.getProcessId(), null);
routingQueryBuilder.orderBy(I_AD_PrinterRouting.COLUMNNAME_AD_Process_ID);
}
if (query.getTableId() != null)
{
routingQueryBuilder.addInArrayFilter(I_AD_PrinterRouting.COLUMNNAME_AD_Table_ID, query.getTableId(), null);
routingQueryBuilder.orderBy(I_AD_PrinterRouting.COLUMNNAME_AD_Table_ID);
}
if (query.getRoleId() != null)
{
routingQueryBuilder.addInArrayFilter(I_AD_PrinterRouting.COLUMNNAME_AD_Role_ID, query.getRoleId(), null);
routingQueryBuilder.orderBy(I_AD_PrinterRouting.COLUMNNAME_AD_Role_ID);
}
if (query.getUserId() != null)
{
routingQueryBuilder.addInArrayFilter(I_AD_PrinterRouting.COLUMNNAME_AD_User_ID, query.getUserId(), null);
routingQueryBuilder.orderBy(I_AD_PrinterRouting.COLUMNNAME_AD_User_ID);
}
routingQueryBuilder
.orderBy(I_AD_PrinterRouting.COLUMNNAME_SeqNo)
.orderByDescending(I_AD_PrinterRouting.COLUMNNAME_AD_Client_ID)
.orderByDescending(I_AD_PrinterRouting.COLUMNNAME_AD_Org_ID)
.orderBy(I_AD_PrinterRouting.COLUMNNAME_AD_PrinterRouting_ID);
|
return routingQueryBuilder
.create()
.list();
}
@Override
public I_AD_Printer findPrinterByName(@Nullable final String printerName)
{
if (Check.isBlank(printerName))
{
return null;
}
return queryBL.createQueryBuilderOutOfTrx(I_AD_Printer.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_Printer.COLUMNNAME_PrinterName, printerName)
.addOnlyContextClientOrSystem()
.create()
.firstOnly(I_AD_Printer.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\PrinterRoutingDAO.java
| 2
|
请完成以下Java代码
|
protected List<String> getUnstructuredRemittanceInfoList()
{
return getEntryTransaction()
.stream()
.findFirst()
.map(EntryTransaction2::getRmtInf)
.map(RemittanceInformation5::getUstrd)
.orElse(ImmutableList.of())
.stream()
.map(str -> Arrays.asList(str.split(" ")))
.flatMap(List::stream)
.filter(Check::isNotBlank)
.collect(Collectors.toList());
}
@Override
@NonNull
protected String getLineDescription(@NonNull final String delimiter)
{
return getLineDescriptionList().stream()
.filter(Check::isNotBlank)
.collect(Collectors.joining(delimiter));
}
@Override
@NonNull
protected List<String> getLineDescriptionList()
{
final List<String> lineDesc = new ArrayList<>();
final String addtlNtryInfStr = entry.getAddtlNtryInf();
if (addtlNtryInfStr != null)
{
lineDesc.addAll( Arrays.stream(addtlNtryInfStr.split(" "))
.filter(Check::isNotBlank)
.collect(Collectors.toList()));
}
final List<String> trxDetails = getEntryTransaction()
.stream()
.map(EntryTransaction2::getAddtlTxInf)
.filter(Objects::nonNull)
.map(str -> Arrays.asList(str.split(" ")))
.flatMap(List::stream)
.filter(Check::isNotBlank)
.collect(Collectors.toList());
|
lineDesc.addAll(trxDetails);
return lineDesc;
}
@Override
@Nullable
protected String getCcy()
{
return entry.getAmt().getCcy();
}
@Override
@Nullable
protected BigDecimal getAmtValue()
{
return entry.getAmt().getValue();
}
public boolean isBatchTransaction() {return getEntryTransaction().size() > 1;}
@Override
public List<ITransactionDtlsWrapper> getTransactionDtlsWrapper()
{
return getEntryTransaction()
.stream()
.map(tr -> TransactionDtls2Wrapper.builder().entryDtls(tr).build())
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\v02\BatchReportEntry2Wrapper.java
| 1
|
请完成以下Java代码
|
public static Authentication getAuthentication(HttpServletRequest req) {
String token = req.getHeader("Authorization");
if (token != null) {
String user = Jwts.parser()
.verifyWith(SIGNINGKEY)
.build().parseClaimsJws(token.replace(PREFIX, "").trim()).getPayload()
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
}
}
return null;
}
|
public static String getTenant(HttpServletRequest req) {
String token = req.getHeader("Authorization");
if (token == null) {
return null;
}
String tenant = Jwts.parser()
.setSigningKey(SIGNINGKEY)
.build().parseClaimsJws(token.replace(PREFIX, "").trim())
.getBody()
.getAudience()
.iterator()
.next();
return tenant;
}
}
|
repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\multitenant\security\AuthenticationService.java
| 1
|
请完成以下Java代码
|
public boolean isAllowAnyProduct() {return productId == null;}
public Optional<I_C_UOM> getUom() {return qtyCUsPerTU != null ? Optional.of(qtyCUsPerTU.getUOM()) : Optional.empty();}
public boolean isFiniteTU() {return !id.isVirtualHU() && !isInfiniteCapacity();}
public boolean isInfiniteCapacity() {return qtyCUsPerTU == null;}
@NonNull
public Quantity getQtyCUsPerTU() {return Check.assumeNotNull(qtyCUsPerTU, "Expecting finite capacity: {}", this);}
private void assertProductMatches(@NonNull final ProductId productId)
{
if (this.productId != null && !ProductId.equals(this.productId, productId))
{
throw new AdempiereException("Product ID " + productId + " does not match the product of " + this);
}
}
@NonNull
public QtyTU computeQtyTUsOfTotalCUs(@NonNull final Quantity totalCUs, @NonNull final ProductId productId)
{
return computeQtyTUsOfTotalCUs(totalCUs, productId, QuantityUOMConverters.noConversion());
}
@NonNull
public QtyTU computeQtyTUsOfTotalCUs(@NonNull final Quantity totalCUs, @NonNull final ProductId productId, @NonNull final QuantityUOMConverter uomConverter)
{
assertProductMatches(productId);
if (totalCUs.signum() <= 0)
{
return QtyTU.ZERO;
}
// Infinite capacity
if (qtyCUsPerTU == null)
{
return QtyTU.ONE;
}
final Quantity totalCUsConv = uomConverter.convertQuantityTo(totalCUs, productId, qtyCUsPerTU.getUomId());
final BigDecimal qtyTUs = totalCUsConv.toBigDecimal().divide(qtyCUsPerTU.toBigDecimal(), 0, RoundingMode.UP);
return QtyTU.ofBigDecimal(qtyTUs);
}
@NonNull
public Quantity computeQtyCUsOfQtyTUs(@NonNull final QtyTU qtyTU)
{
if (qtyCUsPerTU == null)
|
{
throw new AdempiereException("Cannot calculate qty of CUs for infinite capacity");
}
return qtyTU.computeTotalQtyCUsUsingQtyCUsPerTU(qtyCUsPerTU);
}
public Capacity toCapacity()
{
if (productId == null)
{
throw new AdempiereException("Cannot convert to Capacity when no product is specified")
.setParameter("huPIItemProduct", this);
}
if (qtyCUsPerTU == null)
{
throw new AdempiereException("Cannot determine the UOM of " + this)
.setParameter("huPIItemProduct", this);
}
return Capacity.createCapacity(qtyCUsPerTU, productId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUPIItemProduct.java
| 1
|
请完成以下Java代码
|
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
|
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getSeqNo()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestProcessor_Route.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ShiroRealm extends AuthorizingRealm {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserDao userService;
@Autowired
private PermissionDao permissionService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
logger.info("doGetAuthorizationInfo+"+principalCollection.toString());
User user = userService.getByUserName((String) principalCollection.getPrimaryPrincipal());
//把principals放session中 key=userId value=principals
SecurityUtils.getSubject().getSession().setAttribute(String.valueOf(user.getId()),SecurityUtils.getSubject().getPrincipals());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//赋予角色
for(Role userRole:user.getRoles()){
info.addRole(userRole.getName());
}
//赋予权限
for(Permission permission:permissionService.getByUserId(user.getId())){
// if(StringUtils.isNotBlank(permission.getPermCode()))
info.addStringPermission(permission.getName());
}
//设置登录次数、时间
// userService.updateUserLogin(user);
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
|
logger.info("doGetAuthenticationInfo +" + authenticationToken.toString());
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String userName=token.getUsername();
logger.info(userName+token.getPassword());
User user = userService.getByUserName(token.getUsername());
if (user != null) {
// byte[] salt = Encodes.decodeHex(user.getSalt());
// ShiroUser shiroUser=new ShiroUser(user.getId(), user.getLoginName(), user.getName());
//设置用户session
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute("user", user);
return new SimpleAuthenticationInfo(userName,user.getPassword(),getName());
} else {
return null;
}
// return null;
}
}
|
repos\springBoot-master\springboot-shiro\src\main\java\com\us\shiro\ShiroRealm.java
| 2
|
请完成以下Java代码
|
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Org Column.
@param OrgColumn
Fully qualified Organization column (AD_Org_ID)
*/
public void setOrgColumn (String OrgColumn)
{
set_Value (COLUMNNAME_OrgColumn, OrgColumn);
}
/** Get Org Column.
@return Fully qualified Organization column (AD_Org_ID)
*/
public String getOrgColumn ()
{
return (String)get_Value(COLUMNNAME_OrgColumn);
}
/** Set Measure Calculation.
@param PA_MeasureCalc_ID
Calculation method for measuring performance
*/
public void setPA_MeasureCalc_ID (int PA_MeasureCalc_ID)
{
if (PA_MeasureCalc_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_MeasureCalc_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_MeasureCalc_ID, Integer.valueOf(PA_MeasureCalc_ID));
}
/** Get Measure Calculation.
@return Calculation method for measuring performance
*/
public int getPA_MeasureCalc_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_MeasureCalc_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Product Column.
@param ProductColumn
Fully qualified Product column (M_Product_ID)
*/
public void setProductColumn (String ProductColumn)
{
set_Value (COLUMNNAME_ProductColumn, ProductColumn);
}
|
/** Get Product Column.
@return Fully qualified Product column (M_Product_ID)
*/
public String getProductColumn ()
{
return (String)get_Value(COLUMNNAME_ProductColumn);
}
/** Set Sql SELECT.
@param SelectClause
SQL SELECT clause
*/
public void setSelectClause (String SelectClause)
{
set_Value (COLUMNNAME_SelectClause, SelectClause);
}
/** Get Sql SELECT.
@return SQL SELECT clause
*/
public String getSelectClause ()
{
return (String)get_Value(COLUMNNAME_SelectClause);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_MeasureCalc.java
| 1
|
请完成以下Java代码
|
protected boolean canWriteValue(TypedValue typedValue) {
if (!(typedValue instanceof SerializableValue) && !(typedValue instanceof UntypedValueImpl)) {
return false;
}
if (typedValue instanceof SerializableValue) {
SerializableValue serializableValue = (SerializableValue) typedValue;
String requestedDataFormat = serializableValue.getSerializationDataFormat();
if (!serializableValue.isDeserialized()) {
// serialized object => dataformat must match
return serializationDataFormat.equals(requestedDataFormat);
} else {
final boolean canSerialize = typedValue.getValue() == null || dataFormat.canMap(typedValue.getValue());
return canSerialize && (requestedDataFormat == null || serializationDataFormat.equals(requestedDataFormat));
}
} else {
return typedValue.getValue() == null || dataFormat.canMap(typedValue.getValue());
}
}
@Override
protected boolean canReadValue(TypedValueField typedValueField) {
Map<String, Object> valueInfo = typedValueField.getValueInfo();
String serializationDataformat = (String) valueInfo.get(VALUE_INFO_SERIALIZATION_DATA_FORMAT);
Object value = typedValueField.getValue();
|
return (value == null || value instanceof String) && getSerializationDataformat().equals(serializationDataformat);
}
protected ObjectValue createDeserializedValue(Object deserializedObject, String serializedValue, TypedValueField typedValueField) {
String objectTypeName = readObjectNameFromFields(typedValueField);
return new ObjectValueImpl(deserializedObject, serializedValue, serializationDataFormat, objectTypeName, true);
}
protected ObjectValue createSerializedValue(String serializedValue, TypedValueField typedValueField) {
String objectTypeName = readObjectNameFromFields(typedValueField);
return new ObjectValueImpl(null, serializedValue, serializationDataFormat, objectTypeName, false);
}
protected String readObjectNameFromFields(TypedValueField typedValueField) {
Map<String, Object> valueInfo = typedValueField.getValueInfo();
return (String) valueInfo.get(VALUE_INFO_OBJECT_TYPE_NAME);
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\mapper\ObjectValueMapper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
|
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", "false");
return hibernateProperties;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\immutable\PersistenceConfig.java
| 2
|
请完成以下Java代码
|
public void initializeTarget(SnmpDeviceProfileTransportConfiguration profileTransportConfig, SnmpDeviceTransportConfiguration deviceTransportConfig) throws Exception {
log.trace("Initializing target for SNMP session of device {}", device);
this.target = snmpTransportContext.getSnmpAuthService().setUpSnmpTarget(profileTransportConfig, deviceTransportConfig);
log.debug("SNMP target initialized: {}", target);
}
public void close() {
isActive = false;
}
public String getToken() {
return token;
}
@Override
public int nextMsgId() {
return msgIdSeq.incrementAndGet();
}
@Override
public void onGetAttributesResponse(GetAttributeResponseMsg getAttributesResponse) {
}
@Override
public void onAttributeUpdate(UUID sessionId, AttributeUpdateNotificationMsg attributeUpdateNotification) {
log.trace("[{}] Received attributes update notification to device", sessionId);
try {
snmpTransportContext.getSnmpTransportService().onAttributeUpdate(this, attributeUpdateNotification);
} catch (Exception e) {
snmpTransportContext.getTransportService().errorEvent(getTenantId(), getDeviceId(), SnmpCommunicationSpec.SHARED_ATTRIBUTES_SETTING.getLabel(), e);
}
}
@Override
public void onRemoteSessionCloseCommand(UUID sessionId, SessionCloseNotificationProto sessionCloseNotification) {
log.trace("[{}] Received the remote command to close the session: {}", sessionId, sessionCloseNotification.getMessage());
|
if (sessionCloseNotification.getMessage().equals(DefaultTransportService.SESSION_EXPIRED_MESSAGE)) {
if (sessionTimeoutHandler != null) {
sessionTimeoutHandler.run();
}
}
}
@Override
public void onToDeviceRpcRequest(UUID sessionId, ToDeviceRpcRequestMsg toDeviceRequest) {
log.trace("[{}] Received RPC command to device", sessionId);
try {
snmpTransportContext.getSnmpTransportService().onToDeviceRpcRequest(this, toDeviceRequest);
snmpTransportContext.getTransportService().process(getSessionInfo(), toDeviceRequest, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY);
} catch (Exception e) {
snmpTransportContext.getTransportService().errorEvent(getTenantId(), getDeviceId(), SnmpCommunicationSpec.TO_DEVICE_RPC_REQUEST.getLabel(), e);
}
}
@Override
public void onToServerRpcResponse(ToServerRpcResponseMsg toServerResponse) {
}
}
|
repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\session\DeviceSessionContext.java
| 1
|
请完成以下Java代码
|
public int getC_Region_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Region_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Standard.
@param IsDefault
Default value
*/
@Override
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Standard.
@return Default value
*/
@Override
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
|
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Region.java
| 1
|
请完成以下Java代码
|
public @Nullable PublicKeyCredentialUserEntity findByUsername(String username) {
Assert.hasText(username, "name cannot be null or empty");
List<PublicKeyCredentialUserEntity> result = this.jdbcOperations.query(FIND_USER_BY_NAME_SQL,
this.userEntityRowMapper, username);
return !result.isEmpty() ? result.get(0) : null;
}
@Override
public void save(PublicKeyCredentialUserEntity userEntity) {
Assert.notNull(userEntity, "userEntity cannot be null");
int rows = updateUserEntity(userEntity);
if (rows == 0) {
insertUserEntity(userEntity);
}
}
private void insertUserEntity(PublicKeyCredentialUserEntity userEntity) {
List<SqlParameterValue> parameters = this.userEntityParametersMapper.apply(userEntity);
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray());
this.jdbcOperations.update(SAVE_USER_SQL, pss);
}
private int updateUserEntity(PublicKeyCredentialUserEntity userEntity) {
List<SqlParameterValue> parameters = this.userEntityParametersMapper.apply(userEntity);
SqlParameterValue userEntityId = parameters.remove(0);
parameters.add(userEntityId);
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray());
return this.jdbcOperations.update(UPDATE_USER_SQL, pss);
}
@Override
public void delete(Bytes id) {
Assert.notNull(id, "id cannot be null");
SqlParameterValue[] parameters = new SqlParameterValue[] {
new SqlParameterValue(Types.VARCHAR, id.toBase64UrlString()), };
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters);
this.jdbcOperations.update(DELETE_USER_SQL, pss);
|
}
private static class UserEntityParametersMapper
implements Function<PublicKeyCredentialUserEntity, List<SqlParameterValue>> {
@Override
public List<SqlParameterValue> apply(PublicKeyCredentialUserEntity userEntity) {
List<SqlParameterValue> parameters = new ArrayList<>();
parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getId().toBase64UrlString()));
parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getName()));
parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getDisplayName()));
return parameters;
}
}
private static class UserEntityRecordRowMapper implements RowMapper<PublicKeyCredentialUserEntity> {
@Override
public PublicKeyCredentialUserEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
Bytes id = Bytes.fromBase64(new String(rs.getString("id").getBytes()));
String name = rs.getString("name");
String displayName = rs.getString("display_name");
return ImmutablePublicKeyCredentialUserEntity.builder().id(id).name(name).displayName(displayName).build();
}
}
}
|
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\management\JdbcPublicKeyCredentialUserEntityRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringIdmEngineConfiguration extends IdmEngineConfiguration implements ApplicationContextAware {
protected PlatformTransactionManager transactionManager;
protected ApplicationContext applicationContext;
protected Integer transactionSynchronizationAdapterOrder;
public SpringIdmEngineConfiguration() {
this.transactionsExternallyManaged = true;
}
@Override
public IdmEngine buildEngine() {
IdmEngine idmEngine = super.buildEngine();
IdmEngines.setInitialized(true);
return idmEngine;
}
public void setTransactionSynchronizationAdapterOrder(Integer transactionSynchronizationAdapterOrder) {
this.transactionSynchronizationAdapterOrder = transactionSynchronizationAdapterOrder;
}
@Override
public void initDefaultCommandConfig() {
if (defaultCommandConfig == null) {
defaultCommandConfig = new CommandConfig().setContextReusePossible(true);
}
}
@Override
public CommandInterceptor createTransactionInterceptor() {
if (transactionManager == null) {
throw new FlowableException("transactionManager is required property for SpringIdmEngineConfiguration, use " + StandaloneIdmEngineConfiguration.class.getName() + " otherwise");
}
return new SpringTransactionInterceptor(transactionManager);
}
@Override
public void initTransactionContextFactory() {
if (transactionContextFactory == null && transactionManager != null) {
transactionContextFactory = new SpringTransactionContextFactory(transactionManager, transactionSynchronizationAdapterOrder);
}
|
}
@Override
public IdmEngineConfiguration setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
return (IdmEngineConfiguration) super.setDataSource(dataSource);
} else {
// Wrap datasource in Transaction-aware proxy
DataSource proxiedDataSource = new TransactionAwareDataSourceProxy(dataSource);
return (IdmEngineConfiguration) super.setDataSource(proxiedDataSource);
}
}
public PlatformTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-spring\src\main\java\org\flowable\idm\spring\SpringIdmEngineConfiguration.java
| 2
|
请完成以下Java代码
|
private static void applyMultiplication(List<String> validExpressions, Equation equation, int endIndex, StringBuilder currentExpression, long currentResult,
long currentOperandValue, long lastOperand) {
appendToExpression(currentExpression, Operator.MULTIPLICATION, currentOperandValue);
evaluateExpressions(validExpressions, equation, endIndex + 1, currentExpression, currentResult - lastOperand + (lastOperand * currentOperandValue),
lastOperand * currentOperandValue);
removeFromExpression(currentExpression, Operator.MULTIPLICATION, currentOperandValue);
}
private static void appendToExpression(StringBuilder currentExpression, Operator operator, long currentOperand) {
currentExpression.append(operator.getSymbol())
.append(currentOperand);
}
private static void removeFromExpression(StringBuilder currentExpression, Operator operator, long currentOperand) {
currentExpression.setLength(currentExpression.length() - operator.getSymbolLength() - String.valueOf(currentOperand)
.length());
}
private enum Operator {
ADDITION("+"),
SUBTRACTION("-"),
MULTIPLICATION("*"),
NONE("");
private final String symbol;
private final int symbolLength;
Operator(String symbol) {
this.symbol = symbol;
this.symbolLength = symbol.length();
}
|
public String getSymbol() {
return symbol;
}
public int getSymbolLength() {
return symbolLength;
}
}
private static class Equation {
private final String digits;
private final int target;
public Equation(String digits, int target) {
this.digits = digits;
this.target = target;
}
public String getDigits() {
return digits;
}
public int getTarget() {
return target;
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-algorithms-5\src\main\java\com\baeldung\backtracking\Backtracking.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void customize(ResourceHandlerRegistration registration) {
Resources.Chain properties = this.resourceProperties.getChain();
configureResourceChain(properties, registration.resourceChain(properties.isCache()));
}
private void configureResourceChain(Resources.Chain properties, ResourceChainRegistration chain) {
Resources.Chain.Strategy strategy = properties.getStrategy();
if (properties.isCompressed()) {
chain.addResolver(new EncodedResourceResolver());
}
if (strategy.getFixed().isEnabled() || strategy.getContent().isEnabled()) {
chain.addResolver(getVersionResourceResolver(strategy));
}
}
private ResourceResolver getVersionResourceResolver(Resources.Chain.Strategy properties) {
|
VersionResourceResolver resolver = new VersionResourceResolver();
if (properties.getFixed().isEnabled()) {
String version = properties.getFixed().getVersion();
String[] paths = properties.getFixed().getPaths();
Assert.state(version != null, "'version' must not be null");
resolver.addFixedVersionStrategy(version, paths);
}
if (properties.getContent().isEnabled()) {
String[] paths = properties.getContent().getPaths();
resolver.addContentVersionStrategy(paths);
}
return resolver;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\autoconfigure\ResourceChainResourceHandlerRegistrationCustomizer.java
| 2
|
请完成以下Java代码
|
public class EngineRestVariable {
private String name;
private String type;
private Object value;
private String valueUrl;
@ApiModelProperty(example = "myVariable", value = "Name of the variable")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "string", value = "Type of the variable.", notes = "When writing a variable and this value is omitted, the type will be deducted from the raw JSON-attribute request type and is limited to either string, double, integer and boolean. It’s advised to always include a type to make sure no wrong assumption about the type can be done. Some known types are: string, integer, long, short, double, instant, date, localDate, localDateTime, boolean, json")
@JsonInclude(JsonInclude.Include.NON_NULL)
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@ApiModelProperty(example = "test", value = "Value of the variable.", notes = "When writing a variable and value is omitted, null will be used as value.")
|
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@ApiModelProperty(example = "http://....", notes = "When reading a variable of type binary or serializable, this attribute will point to the URL where the raw binary data can be fetched from.")
public void setValueUrl(String valueUrl) {
this.valueUrl = valueUrl;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public String getValueUrl() {
return valueUrl;
}
}
|
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\EngineRestVariable.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setConfig (final java.lang.String Config)
{
set_Value (COLUMNNAME_Config, Config);
}
@Override
public java.lang.String getConfig()
{
return get_ValueAsString(COLUMNNAME_Config);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
|
@Override
public void setS_GithubConfig_ID (final int S_GithubConfig_ID)
{
if (S_GithubConfig_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_GithubConfig_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_GithubConfig_ID, S_GithubConfig_ID);
}
@Override
public int getS_GithubConfig_ID()
{
return get_ValueAsInt(COLUMNNAME_S_GithubConfig_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_GithubConfig.java
| 2
|
请完成以下Java代码
|
public List<Quantity> spreadEqually(final int count)
{
if (count <= 0)
{
throw new AdempiereException("count shall be greater than zero, but it was " + count);
}
else if (count == 1)
{
return ImmutableList.of(this);
}
else // count > 1
{
final ImmutableList.Builder<Quantity> result = ImmutableList.builder();
final Quantity qtyPerPart = divide(count);
Quantity qtyRemainingToSpread = this;
for (int i = 1; i <= count; i++)
{
|
final boolean isLast = i == count;
if (isLast)
{
result.add(qtyRemainingToSpread);
}
else
{
result.add(qtyPerPart);
qtyRemainingToSpread = qtyRemainingToSpread.subtract(qtyPerPart);
}
}
return result.build();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantity.java
| 1
|
请完成以下Java代码
|
public void onResponse(CompositeObservation observation, Registration registration, ObserveCompositeResponse response) {
log.trace("Update Composite Observation [{}: {}].", observation.getRegistrationId(), observation.getPaths());
service.onUpdateValueAfterReadCompositeResponse(registration, response);
}
@Override
public void onError(Observation observation, Registration registration, Exception error) {
if (error != null) {
var path = observation instanceof SingleObservation ? "Single Observation Cancel: " + ((SingleObservation) observation).getPath() : "Composite Observation Cancel: " + ((CompositeObservation) observation).getPaths();
var msgError = path + ": " + error.getMessage();
log.trace("Unable to handle notification [RegistrationId:{}]: [{}].", observation.getRegistrationId(), msgError);
service.onErrorObservation(registration, msgError);
}
}
@Override
public void newObservation(Observation observation, Registration registration) {
log.trace("Successful start newObservation [RegistrationId:{}: {}].", observation.getRegistrationId(), observation instanceof SingleObservation ?
"Single: " + ((SingleObservation) observation).getPath() :
"Composite: " + ((CompositeObservation) observation).getPaths());
}
};
public final SendListener sendListener = new SendListener() {
|
@Override
public void dataReceived(Registration registration, TimestampedLwM2mNodes data, SendRequest request) {
log.trace("Received Send request from [{}] containing value: [{}], coapRequest: [{}]", registration.getEndpoint(), data.toString(), request.getCoapRequest().toString());
if (registration != null) {
service.onUpdateValueWithSendRequest(registration, data);
}
}
@Override
public void onError(Registration registration, String errorMessage, Exception error) {
}
};
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\LwM2mServerListener.java
| 1
|
请完成以下Java代码
|
private void assertNotClosed() throws ClosedChannelException {
if (this.closed) {
throw new ClosedChannelException();
}
}
/**
* Resources used by the channel and suitable for registration with a {@link Cleaner}.
*/
static class Resources implements Runnable {
private final ZipContent zipContent;
private final CloseableDataBlock data;
Resources(Path path, String nestedEntryName) throws IOException {
this.zipContent = ZipContent.open(path, nestedEntryName);
this.data = this.zipContent.openRawZipData();
}
DataBlock getData() {
return this.data;
}
@Override
public void run() {
releaseAll();
}
private void releaseAll() {
|
IOException exception = null;
try {
this.data.close();
}
catch (IOException ex) {
exception = ex;
}
try {
this.zipContent.close();
}
catch (IOException ex) {
if (exception != null) {
ex.addSuppressed(exception);
}
exception = ex;
}
if (exception != null) {
throw new UncheckedIOException(exception);
}
}
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedByteChannel.java
| 1
|
请完成以下Java代码
|
public void extend(String name) {
this.extendedClassName = name;
}
/**
* Implement the given interfaces.
* @param names the names of the interfaces to implement
*/
public void implement(Collection<String> names) {
this.implementsClassNames = List.copyOf(names);
}
/**
* Implement the given interfaces.
* @param names the names of the interfaces to implement
*/
public void implement(String... names) {
this.implementsClassNames = List.of(names);
}
@Override
public AnnotationContainer annotations() {
return this.annotations;
|
}
public String getName() {
return this.name;
}
public String getExtends() {
return this.extendedClassName;
}
public List<String> getImplements() {
return this.implementsClassNames;
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\TypeDeclaration.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<CommissionInstance> createCommissionInstance(@NonNull final CommissionTriggerDocument commissionTriggerDocument)
{
// request might be not present, if there are no matching contracts and/or settings
final Optional<CreateCommissionSharesRequest> request = commissionInstanceRequestFactory.createRequestFor(commissionTriggerDocument);
if (request.isPresent())
{
final CommissionInstance result = CommissionInstance
.builder()
.currentTriggerData(request.get().getTrigger().getCommissionTriggerData())
.shares(commissionAlgorithmInvoker.createCommissionShares(request.get()))
.build();
return Optional.of(result);
}
return Optional.empty();
}
public void createAndAddMissingShares(
@NonNull final CommissionInstance instance,
@NonNull final CommissionTriggerDocument commissionTriggerDocument)
{
final Optional<CreateCommissionSharesRequest> request = commissionInstanceRequestFactory.createRequestFor(commissionTriggerDocument);
if (!request.isPresent())
{
return;
}
final Optional<HierarchyLevel> existingSharesHierarchyTopLevel = instance
.getShares()
.stream()
.filter(share -> share.getLevel() != null)
.map(CommissionShare::getLevel)
|
.max(HierarchyLevel::compareTo);
final HierarchyLevel startingHierarchyLevel = existingSharesHierarchyTopLevel.isPresent()
? existingSharesHierarchyTopLevel.get().incByOne()
: HierarchyLevel.ZERO;
final ImmutableSet<CommissionConfig> existingConfigs = instance.getShares()
.stream()
.map(CommissionShare::getConfig)
.collect(ImmutableSet.toImmutableSet());
final CreateCommissionSharesRequest sparsedOutRequest = request.get()
.withoutConfigs(existingConfigs)
.toBuilder()
.startingHierarchyLevel(startingHierarchyLevel)
.build();
if (sparsedOutRequest.getConfigs().isEmpty())
{
logger.debug("There are no CommissionConfigs that were not already applied to the commission instance");
return;
}
final ImmutableList<CommissionShare> additionalShares = commissionAlgorithmInvoker.createCommissionShares(sparsedOutRequest);
instance.addShares(additionalShares);
logger.debug("Added {} additional salesCommissionShares to instance", additionalShares.size());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionInstanceService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Dao implements AuthorDao {
@PersistenceContext
private EntityManager entityManager;
@Override
@Transactional(readOnly = true)
public List<AuthorDtoNoSetters> fetchAuthorsNoSetters() {
Query query = entityManager
.createNativeQuery("SELECT name, age FROM author")
.unwrap(org.hibernate.query.NativeQuery.class)
.setResultTransformer(
new AliasToBeanConstructorResultTransformer(
AuthorDtoNoSetters.class.getConstructors()[0]
)
);
List<AuthorDtoNoSetters> authors = query.getResultList();
return authors;
}
@Override
@Transactional(readOnly = true)
public List<AuthorDtoWithSetters> fetchAuthorsWithSetters() {
Query query = entityManager
|
.createNativeQuery("SELECT name, age FROM author")
.unwrap(org.hibernate.query.NativeQuery.class)
.setResultTransformer(
Transformers.aliasToBean(AuthorDtoWithSetters.class)
);
List<AuthorDtoWithSetters> authors = query.getResultList();
return authors;
}
protected EntityManager getEntityManager() {
return entityManager;
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoResultTransformer\src\main\java\com\bookstore\dao\Dao.java
| 2
|
请完成以下Java代码
|
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
}
@Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setFileName_Override (final @Nullable java.lang.String FileName_Override)
{
set_Value (COLUMNNAME_FileName_Override, FileName_Override);
}
@Override
public java.lang.String getFileName_Override()
{
return get_ValueAsString(COLUMNNAME_FileName_Override);
|
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment_MultiRef.java
| 1
|
请完成以下Java代码
|
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 Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Read Only.
@param IsReadOnly
Field is read only
*/
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Read Only.
@return Field is read only
*/
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
|
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set User updateable.
@param IsUserUpdateable
The field can be updated by the user
*/
public void setIsUserUpdateable (boolean IsUserUpdateable)
{
set_Value (COLUMNNAME_IsUserUpdateable, Boolean.valueOf(IsUserUpdateable));
}
/** Get User updateable.
@return The field can be updated by the user
*/
public boolean isUserUpdateable ()
{
Object oo = get_Value(COLUMNNAME_IsUserUpdateable);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Win.java
| 1
|
请完成以下Java代码
|
public static List<Pinyin> convert(String complexText, boolean removeTone)
{
List<Pinyin> pinyinList = convert(complexText);
if (removeTone)
{
makeToneToTheSame(pinyinList);
}
return pinyinList;
}
/**
* 将混合文本转为拼音
* @param complexText 混合汉字、拼音、输入法头的文本,比如“飞流zh下sqianch”
* @param removeTone
* @return 一个键值对,键为拼音列表,值为类型(true表示这是一个拼音,false表示这是一个输入法头)
*/
public static Pair<List<Pinyin>, List<Boolean>> convert2Pair(String complexText, boolean removeTone)
{
List<Pinyin> pinyinList = new LinkedList<Pinyin>();
List<Boolean> booleanList = new LinkedList<Boolean>();
Collection<Token> tokenize = trie.tokenize(complexText);
for (Token token : tokenize)
{
String fragment = token.getFragment();
if (token.isMatch())
{
// 是拼音或拼音的一部分,用map转
Pinyin pinyin = convertSingle(fragment);
pinyinList.add(pinyin);
if (fragment.length() == pinyin.getPinyinWithoutTone().length())
{
booleanList.add(true);
}
else
{
booleanList.add(false);
}
}
else
{
List<Pinyin> pinyinListFragment = PinyinDictionary.convertToPinyin(fragment);
pinyinList.addAll(pinyinListFragment);
for (int i = 0; i < pinyinListFragment.size(); ++i)
{
booleanList.add(true);
}
}
}
makeToneToTheSame(pinyinList);
return new Pair<List<Pinyin>, List<Boolean>>(pinyinList, booleanList);
}
/**
* 将单个音节转为拼音
* @param single
* @return
*/
|
public static Pinyin convertSingle(String single)
{
Pinyin pinyin = map.get(single);
if (pinyin == null) return Pinyin.none5;
return pinyin;
}
/**
* 将拼音的音调统统转为5调或者最大的音调
* @param p
* @return
*/
public static Pinyin convert2Tone5(Pinyin p)
{
return tone2tone5[p.ordinal()];
}
/**
* 将所有音调都转为1
* @param pinyinList
* @return
*/
public static List<Pinyin> makeToneToTheSame(List<Pinyin> pinyinList)
{
ListIterator<Pinyin> listIterator = pinyinList.listIterator();
while (listIterator.hasNext())
{
listIterator.set(convert2Tone5(listIterator.next()));
}
return pinyinList;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\py\String2PinyinConverter.java
| 1
|
请完成以下Java代码
|
public void setIsMandatory (boolean IsMandatory)
{
set_Value (COLUMNNAME_IsMandatory, Boolean.valueOf(IsMandatory));
}
/** Get Pflichtangabe.
@return Data entry is required in this column
*/
@Override
public boolean isMandatory ()
{
Object oo = get_Value(COLUMNNAME_IsMandatory);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/**
* PersonalDataCategory AD_Reference_ID=540857
* Reference name: PersonalDataCategory
*/
public static final int PERSONALDATACATEGORY_AD_Reference_ID=540857;
/** NotPersonal = NP */
public static final String PERSONALDATACATEGORY_NotPersonal = "NP";
/** Personal = P */
public static final String PERSONALDATACATEGORY_Personal = "P";
/** SensitivePersonal = SP */
public static final String PERSONALDATACATEGORY_SensitivePersonal = "SP";
/** Set Datenschutz-Kategorie.
@param PersonalDataCategory Datenschutz-Kategorie */
@Override
public void setPersonalDataCategory (java.lang.String PersonalDataCategory)
{
set_Value (COLUMNNAME_PersonalDataCategory, PersonalDataCategory);
}
|
/** Get Datenschutz-Kategorie.
@return Datenschutz-Kategorie */
@Override
public java.lang.String getPersonalDataCategory ()
{
return (java.lang.String)get_Value(COLUMNNAME_PersonalDataCategory);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@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\de\metas\dataentry\model\X_DataEntry_Field.java
| 1
|
请完成以下Java代码
|
public List<LockRecordsByFilter> getSelection_Filters()
{
return _filters;
}
public AdTableId getSelection_AD_Table_ID()
{
return _selection_AD_Table_ID;
}
public PInstanceId getSelection_PInstanceId()
{
return _selection_pinstanceId;
}
public Iterator<TableRecordReference> getRecordsIterator()
{
|
return _records == null ? null : _records.iterator();
}
public void addRecordByModel(final Object model)
{
final TableRecordReference record = TableRecordReference.of(model);
addRecords(Collections.singleton(record));
}
public void addRecordByModels(final Collection<?> models)
{
final Collection<TableRecordReference> records = convertModelsToRecords(models);
addRecords(records);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockRecords.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public List<Role> getAuthorities() {
return authorities;
}
public void setAuthorities(List<Role> authorities) {
this.authorities = authorities;
}
/**
* 用户账号是否过期
*/
@Override
public boolean isAccountNonExpired() {
return true;
}
/**
* 用户账号是否被锁定
|
*/
@Override
public boolean isAccountNonLocked() {
return true;
}
/**
* 用户密码是否过期
*/
@Override
public boolean isCredentialsNonExpired() {
return true;
}
/**
* 用户是否可用
*/
@Override
public boolean isEnabled() {
return true;
}
}
|
repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\entity\User.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public SuperStreamBuilder initialClusterSize(int count) {
return withArgument("x-initial-cluster-size", count);
}
/**
* Set extra argument which is not covered by builder's methods.
* @param key argument name
* @param value argument value
* @return the builder
*/
public SuperStreamBuilder withArgument(String key, Object value) {
if ("x-queue-type".equals(key) && !"stream".equals(value)) {
throw new IllegalArgumentException("Changing x-queue-type argument is not permitted");
}
this.arguments.put(key, value);
return this;
}
/**
* Set the stream name.
* @param name the stream name.
* @return the builder
*/
public SuperStreamBuilder name(String name) {
this.name = name;
return this;
}
/**
* Set the partitions number.
* @param partitions the partitions number
* @return the builder
*/
public SuperStreamBuilder partitions(int partitions) {
this.partitions = partitions;
return this;
}
/**
* Set a strategy to determine routing keys to use for the
* partitions. The first parameter is the queue name, the second the number of
* partitions, the returned list must have a size equal to the partitions.
* @param routingKeyStrategy the strategy
* @return the builder
|
*/
public SuperStreamBuilder routingKeyStrategy(BiFunction<String, Integer, List<String>> routingKeyStrategy) {
this.routingKeyStrategy = routingKeyStrategy;
return this;
}
/**
* Builds a final Super Stream.
* @return the Super Stream instance
*/
public SuperStream build() {
if (!StringUtils.hasText(this.name)) {
throw new IllegalArgumentException("Stream name can't be empty");
}
if (this.partitions <= 0) {
throw new IllegalArgumentException(
String.format("Partitions number should be great then zero. Current value; %d", this.partitions)
);
}
if (this.routingKeyStrategy == null) {
return new SuperStream(this.name, this.partitions, this.arguments);
}
return new SuperStream(this.name, this.partitions, this.routingKeyStrategy, this.arguments);
}
}
|
repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\config\SuperStreamBuilder.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class StudentService {
private static final List<Student> students = new ArrayList<>();
private final SecureRandom random = new SecureRandom();
static {
//Initialize Data
Course courseOne = new Course("Course1", "Spring", "10Steps",
List.of("Learn Maven", "Import Project", "First Example", "Second Example"));
Course courseTwo = new Course("Course2", "Spring MVC", "10 Examples",
List.of("Learn Maven", "Import Project", "First Example", "Second Example"));
Course courseThree = new Course("Course3", "Spring Boot", "6K Students",
List.of("Learn Maven", "Learn Spring", "Learn Spring MVC", "First Example", "Second Example"));
Course courseFour = new Course("Course4", "Maven", "Most popular maven course on internet!",
List.of("Pom.xml", "Build Life Cycle", "Parent POM", "Importing into Eclipse"));
Student ranga = new Student("Student1", "Ranga Karanam", "Hiker, Programmer and Architect",
new ArrayList<>(List.of(courseOne, courseTwo, courseThree, courseFour)));
Student satish = new Student("Student2", "Satish T", "Hiker, Programmer and Architect",
new ArrayList<>(List.of(courseOne, courseTwo, courseThree, courseFour)));
students.add(ranga);
students.add(satish);
}
public List<Student> retrieveAllStudents() {
return students;
}
public Student retrieveStudent(String studentId) {
return students.stream()
.filter(student -> student.id().equals(studentId))
.findAny()
.orElse(null);
}
public List<Course> retrieveCourses(String studentId) {
Student student = retrieveStudent(studentId);
if (studentId.equalsIgnoreCase("Student1")) {
throw new RuntimeException("Something went wrong");
}
return student == null ? null : student.courses();
|
}
public Course retrieveCourse(String studentId, String courseId) {
Student student = retrieveStudent(studentId);
if (student == null) {
return null;
}
return student.courses().stream()
.filter(course -> course.id().equals(courseId))
.findAny()
.orElse(null);
}
public Course addCourse(String studentId, Course course) {
Student student = retrieveStudent(studentId);
if (student == null) {
return null;
}
String randomId = new BigInteger(130, random).toString(32);
new Course(randomId, "", "", Collections.singletonList(""));
student.courses().add(course);
return course;
}
}
|
repos\spring-boot-examples-master\spring-boot-rest-services\src\main\java\com\in28minutes\springboot\service\StudentService.java
| 2
|
请完成以下Java代码
|
public void setSubflowExecution (final @Nullable java.lang.String SubflowExecution)
{
set_Value (COLUMNNAME_SubflowExecution, SubflowExecution);
}
@Override
public java.lang.String getSubflowExecution()
{
return get_ValueAsString(COLUMNNAME_SubflowExecution);
}
@Override
public void setUnitsCycles (final @Nullable BigDecimal UnitsCycles)
{
set_Value (COLUMNNAME_UnitsCycles, UnitsCycles);
}
@Override
public BigDecimal getUnitsCycles()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_UnitsCycles);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWaitingTime (final int WaitingTime)
{
set_Value (COLUMNNAME_WaitingTime, WaitingTime);
}
@Override
public int getWaitingTime()
{
return get_ValueAsInt(COLUMNNAME_WaitingTime);
}
@Override
public void setWaitTime (final int WaitTime)
{
set_Value (COLUMNNAME_WaitTime, WaitTime);
}
@Override
public int getWaitTime()
{
return get_ValueAsInt(COLUMNNAME_WaitTime);
}
@Override
public void setWorkflow_ID (final int Workflow_ID)
{
if (Workflow_ID < 1)
set_Value (COLUMNNAME_Workflow_ID, null);
else
set_Value (COLUMNNAME_Workflow_ID, Workflow_ID);
}
@Override
|
public int getWorkflow_ID()
{
return get_ValueAsInt(COLUMNNAME_Workflow_ID);
}
@Override
public void setWorkingTime (final int WorkingTime)
{
set_Value (COLUMNNAME_WorkingTime, WorkingTime);
}
@Override
public int getWorkingTime()
{
return get_ValueAsInt(COLUMNNAME_WorkingTime);
}
@Override
public void setXPosition (final int XPosition)
{
set_Value (COLUMNNAME_XPosition, XPosition);
}
@Override
public int getXPosition()
{
return get_ValueAsInt(COLUMNNAME_XPosition);
}
@Override
public void setYield (final int Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public int getYield()
{
return get_ValueAsInt(COLUMNNAME_Yield);
}
@Override
public void setYPosition (final int YPosition)
{
set_Value (COLUMNNAME_YPosition, YPosition);
}
@Override
public int getYPosition()
{
return get_ValueAsInt(COLUMNNAME_YPosition);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.