instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | protected String getTypeNameForDeserialized(Object deserializedObject) {
return dataFormat.getMapper().getCanonicalTypeName(deserializedObject);
}
protected byte[] serializeToByteArray(Object deserializedObject) throws Exception {
DataFormatMapper mapper = dataFormat.getMapper();
DataFormatWriter writer = dataFormat.getWriter();
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStreamWriter outWriter = new OutputStreamWriter(out, Context.getProcessEngineConfiguration().getDefaultCharset());
BufferedWriter bufferedWriter = new BufferedWriter(outWriter);
try {
Object mappedObject = mapper.mapJavaToInternal(deserializedObject);
writer.writeToWriter(bufferedWriter, mappedObject);
return out.toByteArray();
}
finally {
IoUtil.closeSilently(out);
IoUtil.closeSilently(outWriter);
IoUtil.closeSilently(bufferedWriter);
}
}
protected Object deserializeFromByteArray(byte[] bytes, String objectTypeName) throws Exception {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
DataFormatMapper mapper = dataFormat.getMapper();
DataFormatReader reader = dataFormat.getReader();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader inReader = new InputStreamReader(bais, processEngineConfiguration.getDefaultCharset());
BufferedReader bufferedReader = new BufferedReader(inReader);
try {
Object mappedObject = reader.readInput(bufferedReader);
return mapper.mapInternalToJava(mappedObject, objectTypeName, getValidator(processEngineConfiguration));
}
finally{ | IoUtil.closeSilently(bais);
IoUtil.closeSilently(inReader);
IoUtil.closeSilently(bufferedReader);
}
}
protected boolean canSerializeValue(Object value) {
return dataFormat.getMapper().canMap(value);
}
protected DeserializationTypeValidator getValidator(final ProcessEngineConfigurationImpl processEngineConfiguration) {
if (validator == null && processEngineConfiguration.isDeserializationTypeValidationEnabled()) {
validator = new DeserializationTypeValidator() {
@Override
public boolean validate(String type) {
return processEngineConfiguration.getDeserializationTypeValidator().validate(type);
}
};
}
return validator;
}
} | repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\SpinObjectValueSerializer.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CompensateEventDefinition.class, BPMN_ELEMENT_COMPENSATE_EVENT_DEFINITION)
.namespaceUri(BPMN20_NS)
.extendsType(EventDefinition.class)
.instanceProvider(new ModelTypeInstanceProvider<CompensateEventDefinition>() {
public CompensateEventDefinition newInstance(ModelTypeInstanceContext instanceContext) {
return new CompensateEventDefinitionImpl(instanceContext);
}
});
waitForCompletionAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_WAIT_FOR_COMPLETION)
.build();
activityRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ACTIVITY_REF)
.qNameAttributeReference(Activity.class)
.build();
typeBuilder.build();
} | public CompensateEventDefinitionImpl(ModelTypeInstanceContext context) {
super(context);
}
public boolean isWaitForCompletion() {
return waitForCompletionAttribute.getValue(this);
}
public void setWaitForCompletion(boolean isWaitForCompletion) {
waitForCompletionAttribute.setValue(this, isWaitForCompletion);
}
public Activity getActivity() {
return activityRefAttribute.getReferenceTargetElement(this);
}
public void setActivity(Activity activity) {
activityRefAttribute.setReferenceTargetElement(this, activity);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CompensateEventDefinitionImpl.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
# Enabling H2 Console
spring.h2.console.enabled | =true
spring.h2.console.path=/h2
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true | repos\tutorials-master\spring-boot-modules\spring-caching-3\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setQtyCount (final BigDecimal QtyCount)
{
set_Value (COLUMNNAME_QtyCount, QtyCount);
}
@Override
public BigDecimal getQtyCount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); | return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_Fresh_QtyOnHand_Line.java | 1 |
请完成以下Java代码 | public ProductId getProductId()
{
return storage.getProductId();
}
@Override
public BigDecimal getQty()
{
return storage.getQtyCapacity();
}
@Override
public I_C_UOM getC_UOM()
{
return storage.getC_UOM();
}
@Override
public BigDecimal getQtyAllocated()
{
return storage.getQtyFree();
}
@Override
public BigDecimal getQtyToAllocate()
{
return storage.getQty().toBigDecimal();
}
@Override
public Object getTrxReferencedModel()
{ | return referenceModel;
}
protected IProductStorage getStorage()
{
return storage;
}
@Override
public IAllocationSource createAllocationSource(final I_M_HU hu)
{
return HUListAllocationSourceDestination.of(hu);
}
@Override
public boolean isReadOnly()
{
return readonly;
}
@Override
public void setReadOnly(final boolean readonly)
{
this.readonly = readonly;
}
@Override
public I_M_HU_Item getInnerHUItem()
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocumentLine.java | 1 |
请完成以下Java代码 | public I_C_UOM getC_UOMOrNull()
{
return dao.getC_UOMOrNull(hu);
}
@Override
public boolean isSingleProductWithQtyEqualsTo(@NonNull final ProductId productId, @NonNull final Quantity qty)
{
final List<IHUProductStorage> productStorages = getProductStorages();
return productStorages.size() == 1
&& ProductId.equals(productStorages.get(0).getProductId(), productId)
&& productStorages.get(0).getQty(qty.getUOM()).compareTo(qty) == 0;
}
@Override
public boolean isSingleProductStorageMatching(@NonNull final ProductId productId)
{ | final List<IHUProductStorage> productStorages = getProductStorages();
return isSingleProductStorageMatching(productStorages, productId);
}
private static boolean isSingleProductStorageMatching(@NonNull final List<IHUProductStorage> productStorages, @NotNull final ProductId productId)
{
return productStorages.size() == 1 && ProductId.equals(productStorages.get(0).getProductId(), productId);
}
@Override
public boolean isEmptyOrSingleProductStorageMatching(@NonNull final ProductId productId)
{
final List<IHUProductStorage> productStorages = getProductStorages();
return productStorages.isEmpty() || isSingleProductStorageMatching(productStorages, productId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUStorage.java | 1 |
请完成以下Java代码 | public class PerformanceSettings {
/**
* Experimental setting: if true, whenever an execution is fetched from the data store,
* the whole execution tree is fetched in the same roundtrip.
*
* Less roundtrips to the database outweighs doing many, smaller fetches and often
* multiple executions from the same tree are needed anyway when executing process instances.
*/
protected boolean enableEagerExecutionTreeFetching;
/**
* Experimental setting: keeps a count on each execution that holds
* how many variables, jobs, tasks, event subscriptions, etc. the execution has.
*
* This makes the delete more performant as a query is not needed anymore
* to check if there is related data. However, maintaining the count
* does mean more updates to the execution and potentially more optimistic locking opportunities.
* Typically keeping the counts lead to better performance as deletes are a large part of the
* execution tree maintenance.
*/
protected boolean enableExecutionRelationshipCounts;
/**
* If false, no check will be done on boot.
*/
protected boolean validateExecutionRelationshipCountConfigOnBoot = true;
/**
* Experimental setting: in certain places in the engine (execution/process instance/historic process instance/
* tasks/data objects) localization is supported. When this setting is false,
* localization is completely disabled, which gives a small performance gain.
*/
protected boolean enableLocalization = true;
public boolean isEnableEagerExecutionTreeFetching() {
return enableEagerExecutionTreeFetching;
}
public void setEnableEagerExecutionTreeFetching(boolean enableEagerExecutionTreeFetching) {
this.enableEagerExecutionTreeFetching = enableEagerExecutionTreeFetching; | }
public boolean isEnableExecutionRelationshipCounts() {
return enableExecutionRelationshipCounts;
}
public void setEnableExecutionRelationshipCounts(boolean enableExecutionRelationshipCounts) {
this.enableExecutionRelationshipCounts = enableExecutionRelationshipCounts;
}
public boolean isValidateExecutionRelationshipCountConfigOnBoot() {
return validateExecutionRelationshipCountConfigOnBoot;
}
public void setValidateExecutionRelationshipCountConfigOnBoot(
boolean validateExecutionRelationshipCountConfigOnBoot
) {
this.validateExecutionRelationshipCountConfigOnBoot = validateExecutionRelationshipCountConfigOnBoot;
}
public boolean isEnableLocalization() {
return enableLocalization;
}
public void setEnableLocalization(boolean enableLocalization) {
this.enableLocalization = enableLocalization;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\PerformanceSettings.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class SecurityFilterChainConfiguration {
@Bean
@Order(SecurityFilterProperties.BASIC_AUTH_ORDER)
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) {
http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated());
http.formLogin(withDefaults());
http.httpBasic(withDefaults());
return http.build();
}
}
/**
* Adds the {@link EnableWebSecurity @EnableWebSecurity} annotation if Spring Security
* is on the classpath. This will make sure that the annotation is present with | * default security auto-configuration and also if the user adds custom security and
* forgets to add the annotation. If {@link EnableWebSecurity @EnableWebSecurity} has
* already been added or if a bean with name
* {@value BeanIds#SPRING_SECURITY_FILTER_CHAIN} has been configured by the user, this
* will back-off.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = BeanIds.SPRING_SECURITY_FILTER_CHAIN)
@ConditionalOnClass(EnableWebSecurity.class)
@EnableWebSecurity
static class EnableWebSecurityConfiguration {
}
} | repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\web\servlet\ServletWebSecurityAutoConfiguration.java | 2 |
请完成以下Java代码 | private int computeNumberOfPages()
{
if (!hasData())
{
return 0;
}
PdfReader reader = null;
try
{
reader = new PdfReader(getData());
return reader.getNumberOfPages();
}
catch (final IOException e)
{
throw new AdempiereException("Cannot get number of pages for C_Printing_Queue_ID=" + printingQueueItemId.getRepoId(), e);
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (final Exception ignored)
{
}
}
}
}
public PrintingData onlyWithType(@NonNull final OutputType outputType)
{
final ImmutableList<PrintingSegment> filteredSegments = segments.stream() | .filter(segment -> segment.isMatchingOutputType(outputType))
.collect(ImmutableList.toImmutableList());
return toBuilder()
.clearSegments()
.segments(filteredSegments)
.adjustSegmentPageRanges(false)
.build();
}
public PrintingData onlyQueuedForExternalSystems()
{
final ImmutableList<PrintingSegment> filteredSegments = segments.stream()
.filter(PrintingSegment::isQueuedForExternalSystems)
.collect(ImmutableList.toImmutableList());
return toBuilder()
.clearSegments()
.segments(filteredSegments)
.adjustSegmentPageRanges(false)
.build();
}
public boolean hasSegments() {return !getSegments().isEmpty();}
public int getSegmentsCount() {return getSegments().size();}
public ImmutableSet<String> getPrinterNames()
{
return segments.stream()
.map(segment -> segment.getPrinter().getName())
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingData.java | 1 |
请完成以下Java代码 | public Quantity calculateQtyEntered(@NonNull final I_C_Invoice_Candidate icRecord)
{
final UomId uomId = HandlerTools.retrieveUomId(icRecord);
final I_C_Flatrate_Term term = HandlerTools.retrieveTerm(icRecord);
return new Quantity(
term.getPlannedQtyPerUnit(),
loadOutOfTrx(uomId, I_C_UOM.class));
}
@Override
public Consumer<I_C_Invoice_Candidate> getInvoiceScheduleSetterFunction(@NonNull final Consumer<I_C_Invoice_Candidate> defaultImplementation)
{
return defaultImplementation;
}
@Override
public Timestamp calculateDateOrdered(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord)
{
final I_C_Flatrate_Term term = HandlerTools.retrieveTerm(invoiceCandidateRecord);
final Timestamp dateOrdered;
final boolean termHasAPredecessor = Services.get(IContractsDAO.class).termHasAPredecessor(term);
if (!termHasAPredecessor)
{
dateOrdered = term.getStartDate();
}
// If the term was extended (meaning that there is a predecessor term),
// C_Invoice_Candidate.DateOrdered should rather be the StartDate minus TermOfNoticeDuration/TermOfNoticeUnit
else
{
final Timestamp firstDayOfNewTerm = getGetExtentionDateOfNewTerm(term);
dateOrdered = firstDayOfNewTerm;
}
return dateOrdered;
}
/**
* For the given <code>term</code> and its <code>C_Flatrate_Transition</code> record, this method returns the term's start date minus the period specified by <code>TermOfNoticeDuration</code> and
* <code>TermOfNoticeUnit</code>.
*/
private static Timestamp getGetExtentionDateOfNewTerm(@NonNull final I_C_Flatrate_Term term)
{ | final Timestamp startDateOfTerm = term.getStartDate();
final I_C_Flatrate_Conditions conditions = term.getC_Flatrate_Conditions();
final I_C_Flatrate_Transition transition = conditions.getC_Flatrate_Transition();
final String termOfNoticeUnit = transition.getTermOfNoticeUnit();
final int termOfNotice = transition.getTermOfNotice();
final Timestamp minimumDateToStart;
if (X_C_Flatrate_Transition.TERMOFNOTICEUNIT_MonatE.equals(termOfNoticeUnit))
{
minimumDateToStart = TimeUtil.addMonths(startDateOfTerm, termOfNotice * -1);
}
else if (X_C_Flatrate_Transition.TERMOFNOTICEUNIT_WocheN.equals(termOfNoticeUnit))
{
minimumDateToStart = TimeUtil.addWeeks(startDateOfTerm, termOfNotice * -1);
}
else if (X_C_Flatrate_Transition.TERMOFNOTICEUNIT_TagE.equals(termOfNoticeUnit))
{
minimumDateToStart = TimeUtil.addDays(startDateOfTerm, termOfNotice * -1);
}
else
{
Check.assume(false, "TermOfNoticeDuration " + transition.getTermOfNoticeUnit() + " doesn't exist");
minimumDateToStart = null; // code won't be reached
}
return minimumDateToStart;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\invoicecandidatehandler\FlatrateTermSubscription_Handler.java | 1 |
请完成以下Java代码 | public boolean containsKey(Object key) {
if ( (key==null) || (!String.class.isAssignableFrom(key.getClass())) ) {
return false;
}
return beanFactory.containsBean((String) key);
}
public Set<Object> keySet() {
return Collections.emptySet();
}
public void clear() {
throw new ProcessEngineException("can't clear configuration beans");
}
public boolean containsValue(Object value) {
throw new ProcessEngineException("can't search values in configuration beans");
}
public Set<java.util.Map.Entry<Object, Object>> entrySet() {
throw new ProcessEngineException("unsupported operation on configuration beans");
}
public boolean isEmpty() { | throw new ProcessEngineException("unsupported operation on configuration beans");
}
public Object put(Object key, Object value) {
throw new ProcessEngineException("unsupported operation on configuration beans");
}
public void putAll(Map< ? extends Object, ? extends Object> m) {
throw new ProcessEngineException("unsupported operation on configuration beans");
}
public Object remove(Object key) {
throw new ProcessEngineException("unsupported operation on configuration beans");
}
public int size() {
throw new ProcessEngineException("unsupported operation on configuration beans");
}
public Collection<Object> values() {
throw new ProcessEngineException("unsupported operation on configuration beans");
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\SpringBeanFactoryProxyMap.java | 1 |
请完成以下Java代码 | public static HUPIAttributeId ofRepoId(final int repoId)
{
return new HUPIAttributeId(repoId);
}
@Nullable
public static HUPIAttributeId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<HUPIAttributeId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final HUPIAttributeId id)
{
return id != null ? id.getRepoId() : -1;
}
int repoId;
private HUPIAttributeId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Attribute_ID");
} | @JsonValue
@Override
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final HUPIAttributeId id1, @Nullable final HUPIAttributeId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HUPIAttributeId.java | 1 |
请完成以下Java代码 | public void addDelegate(String contentType, MessageConverter messageConverter) {
this.delegates.put(contentType, messageConverter);
}
/**
* Remove the delegate for the content type.
* @param contentType the content type key to remove {@link MessageConverter} from delegates.
* @return the remove {@link MessageConverter}.
*/
public MessageConverter removeDelegate(String contentType) {
return this.delegates.remove(contentType);
}
@Override
public Object fromMessage(Message message) throws MessageConversionException {
String contentType = message.getMessageProperties().getContentType();
return getConverterForContentType(contentType).fromMessage(message); | }
@Override
public Message toMessage(Object object, MessageProperties messageProperties) {
String contentType = messageProperties.getContentType();
return getConverterForContentType(contentType).toMessage(object, messageProperties);
}
protected MessageConverter getConverterForContentType(String contentType) {
MessageConverter delegate = getDelegates().get(contentType);
if (delegate == null) {
delegate = this.defaultConverter;
}
return delegate;
}
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\ContentTypeDelegatingMessageConverter.java | 1 |
请完成以下Java代码 | public ITrxConstraints setTrxTimeoutSecs(int secs, boolean logOnly)
{
return this;
}
@Override
public int getTrxTimeoutSecs()
{
return 0;
}
@Override
public boolean isTrxTimeoutLogOnly()
{
return false;
}
@Override
public ITrxConstraints setMaxTrx(int max)
{
return this;
}
@Override
public ITrxConstraints incMaxTrx(int num)
{
return this;
}
@Override
public int getMaxTrx()
{
return 0;
}
@Override
public int getMaxSavepoints()
{
return 0;
} | @Override
public ITrxConstraints setMaxSavepoints(int maxSavePoints)
{
return this;
}
@Override
public boolean isAllowTrxAfterThreadEnd()
{
return false;
}
@Override
public ITrxConstraints setAllowTrxAfterThreadEnd(boolean allow)
{
return this;
}
@Override
public void reset()
{
}
@Override
public String toString()
{
return "TrxConstraints have been globally disabled. Add or change AD_SysConfig " + TrxConstraintsBL.SYSCONFIG_TRX_CONSTRAINTS_DISABLED + " to enable them";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraintsDisabled.java | 1 |
请完成以下Java代码 | public int getC_BPartner_Location_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID);
}
@Override
public void setEDI_cctop_000_v_ID (final int EDI_cctop_000_v_ID)
{
if (EDI_cctop_000_v_ID < 1)
set_ValueNoCheck (COLUMNNAME_EDI_cctop_000_v_ID, null);
else
set_ValueNoCheck (COLUMNNAME_EDI_cctop_000_v_ID, EDI_cctop_000_v_ID);
}
@Override
public int getEDI_cctop_000_v_ID()
{ | return get_ValueAsInt(COLUMNNAME_EDI_cctop_000_v_ID);
}
@Override
public void setEdiInvoicRecipientGLN (final @Nullable java.lang.String EdiInvoicRecipientGLN)
{
set_ValueNoCheck (COLUMNNAME_EdiInvoicRecipientGLN, EdiInvoicRecipientGLN);
}
@Override
public java.lang.String getEdiInvoicRecipientGLN()
{
return get_ValueAsString(COLUMNNAME_EdiInvoicRecipientGLN);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_000_v.java | 1 |
请完成以下Java代码 | public CamundaBpmProperties getCamundaBpmProperties() {
return camundaBpmProperties;
}
public void setCamundaBpmProperties(CamundaBpmProperties camundaBpmProperties) {
this.camundaBpmProperties = camundaBpmProperties;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(jdbcTemplate, "a jdbc template must be set");
Assert.notNull(camundaBpmProperties, "Camunda Platform properties must be set");
String historyLevelDefault = camundaBpmProperties.getHistoryLevelDefault();
if (StringUtils.hasText(historyLevelDefault)) {
defaultHistoryLevel = historyLevelDefault;
}
}
@Override
public String determineHistoryLevel() {
Integer historyLevelFromDb = null;
try {
historyLevelFromDb = jdbcTemplate.queryForObject(getSql(), Integer.class);
log.debug("found history '{}' in database", historyLevelFromDb);
} catch (DataAccessException e) {
if (ignoreDataAccessException) {
log.warn("unable to fetch history level from database: {}", e.getMessage());
log.debug("unable to fetch history level from database", e);
} else {
throw e;
}
}
return getHistoryLevelFrom(historyLevelFromDb);
}
protected String getSql() {
String tablePrefix = camundaBpmProperties.getDatabase().getTablePrefix();
if (tablePrefix == null) {
tablePrefix = ""; | }
return SQL_TEMPLATE.replace(TABLE_PREFIX_PLACEHOLDER, tablePrefix);
}
protected String getHistoryLevelFrom(Integer historyLevelFromDb) {
String result = defaultHistoryLevel;
if (historyLevelFromDb != null) {
for (HistoryLevel historyLevel : historyLevels) {
if (historyLevel.getId() == historyLevelFromDb.intValue()) {
result = historyLevel.getName();
log.debug("found matching history level '{}'", result);
break;
}
}
}
return result;
}
public void addCustomHistoryLevels(Collection<HistoryLevel> customHistoryLevels) {
historyLevels.addAll(customHistoryLevels);
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\jdbc\HistoryLevelDeterminatorJdbcTemplateImpl.java | 1 |
请完成以下Java代码 | public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public void setStorageAttributesKey (final @Nullable java.lang.String StorageAttributesKey)
{
set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey);
}
@Override
public java.lang.String getStorageAttributesKey()
{
return get_ValueAsString(COLUMNNAME_StorageAttributesKey);
}
@Override
public void setTransfertTime (final @Nullable BigDecimal TransfertTime)
{
set_Value (COLUMNNAME_TransfertTime, TransfertTime);
}
@Override
public BigDecimal getTransfertTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TransfertTime);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWorkingTime (final @Nullable BigDecimal WorkingTime)
{
set_Value (COLUMNNAME_WorkingTime, WorkingTime);
}
@Override
public BigDecimal getWorkingTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WorkingTime); | return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setYield (final int Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public int getYield()
{
return get_ValueAsInt(COLUMNNAME_Yield);
}
@Override
public void setC_Manufacturing_Aggregation_ID (final int C_Manufacturing_Aggregation_ID)
{
if (C_Manufacturing_Aggregation_ID < 1)
set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, null);
else
set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, C_Manufacturing_Aggregation_ID);
}
@Override
public int getC_Manufacturing_Aggregation_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Manufacturing_Aggregation_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_Planning.java | 1 |
请完成以下Java代码 | public String getUpdateId() {
return updateId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_info.update_id
*
* @param updateId the value for user_info.update_id
*
* @mbg.generated Sun Apr 28 14:54:53 CST 2024
*/
public void setUpdateId(String updateId) {
this.updateId = updateId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_info.enabled
*
* @return the value of user_info.enabled
*
* @mbg.generated Sun Apr 28 14:54:53 CST 2024 | */
public Boolean getEnabled() {
return enabled;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_info.enabled
*
* @param enabled the value for user_info.enabled
*
* @mbg.generated Sun Apr 28 14:54:53 CST 2024
*/
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
} | repos\springboot-demo-master\druid\src\main\java\com\et\druid\entity\UserInfo.java | 1 |
请完成以下Java代码 | public static boolean isValidDMSFormatWithCustomValidation(String coordinateString) {
try {
String[] dmsParts = coordinateString.split("[°',]");
if (dmsParts.length > 6) {
return false;
}
int degreesLatitude = Integer.parseInt(dmsParts[0].trim());
int minutesLatitude = Integer.parseInt(dmsParts[1].trim());
String[] secondPartsLatitude = dmsParts[2].split("\"");
double secondsLatitude = secondPartsLatitude.length > 1 ? Double.parseDouble(secondPartsLatitude[0].trim()) : 0.0;
String hemisphereLatitude = secondPartsLatitude.length > 1 ? secondPartsLatitude[1] : dmsParts[2];
int degreesLongitude = Integer.parseInt(dmsParts[3].trim());
int minutesLongitude = Integer.parseInt(dmsParts[4].trim());
String[] secondPartsLongitude = dmsParts[5].split("\"");
double secondsLongitude = secondPartsLongitude.length > 1 ? Double.parseDouble(secondPartsLongitude[0].trim()) : 0.0;
String hemisphereLongitude = secondPartsLongitude.length > 1 ? secondPartsLongitude[1] : dmsParts[5];
if (isInvalidLatitude(degreesLatitude, minutesLatitude, secondsLatitude, hemisphereLatitude) ||
isInvalidLongitude(degreesLongitude, minutesLongitude, secondsLongitude, hemisphereLongitude)) {
return false;
}
return true; | } catch (NumberFormatException e) {
return false;
}
}
private static boolean isInvalidLatitude(int degrees, int minutes, double seconds, String hemisphere) {
return degrees < 0 || degrees > 90 || minutes < 0 || minutes >= 60 || seconds < 0 || seconds >= 60 ||
(!hemisphere.equalsIgnoreCase("N") && !hemisphere.equalsIgnoreCase("S"));
}
private static boolean isInvalidLongitude(int degrees, int minutes, double seconds, String hemisphere) {
return degrees < 0 || degrees > 180 || minutes < 0 || minutes >= 60 || seconds < 0 || seconds >= 60 ||
(!hemisphere.equalsIgnoreCase("E") && !hemisphere.equalsIgnoreCase("W"));
}
} | repos\tutorials-master\core-java-modules\core-java-lang-math-3\src\main\java\com\baeldung\geocoordinatevalidator\GeoCoordinateValidator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PaymentAllocationPayableItem
{
InvoiceAmtMultiplier amtMultiplier;
Amount openAmt;
Amount payAmt;
Amount discountAmt;
Amount serviceFeeAmt;
ClientAndOrgId clientAndOrgId;
Instant paymentDate;
/**
* Payment-BPartner
*/
BPartnerId bPartnerId;
InvoiceId invoiceId;
BPartnerId invoiceBPartnerId;
String documentNo;
/**
* This property is not about the invoice, but basically about the payment.
*/
SOTrx soTrx;
LocalDate dateInvoiced;
@Builder
private PaymentAllocationPayableItem(
@NonNull final InvoiceAmtMultiplier amtMultiplier,
@NonNull final Amount openAmt, | @NonNull final Amount payAmt,
@NonNull final Amount discountAmt,
@Nullable final Amount serviceFeeAmt,
@NonNull final OrgId orgId,
@NonNull final ClientId clientId,
@Nullable final Instant paymentDate,
@NonNull final BPartnerId bPartnerId,
@NonNull final InvoiceId invoiceId,
@NonNull final BPartnerId invoiceBPartnerId,
@NonNull final String documentNo,
@NonNull final SOTrx soTrx,
@NonNull final LocalDate dateInvoiced)
{
this.amtMultiplier = amtMultiplier;
this.openAmt = openAmt;
this.payAmt = payAmt;
this.discountAmt = discountAmt;
this.serviceFeeAmt = serviceFeeAmt;
this.clientAndOrgId = ClientAndOrgId.ofClientAndOrg(clientId, orgId);
this.paymentDate = CoalesceUtil.coalesce(paymentDate, Instant::now);
this.bPartnerId = bPartnerId;
this.invoiceId = invoiceId;
this.invoiceBPartnerId = invoiceBPartnerId;
this.documentNo = documentNo;
this.soTrx = soTrx;
this.dateInvoiced = dateInvoiced;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\PaymentAllocationPayableItem.java | 2 |
请完成以下Java代码 | public int cols()
{
return getColumnDimension();
}
/**
* 取出第j列作为一个列向量
* @param j
* @return
*/
public Matrix col(int j)
{
double[][] X = new double[m][1];
for (int i = 0; i < m; i++)
{
X[i][0] = A[i][j];
}
return new Matrix(X);
}
/**
* 取出第i行作为一个行向量
* @param i
* @return
*/
public Matrix row(int i)
{
double[][] X = new double[1][n];
for (int j = 0; j < n; j++)
{
X[0][j] = A[i][j];
}
return new Matrix(X);
}
public Matrix block(int i, int j, int p, int q)
{
return getMatrix(i, i + p - 1, j, j + q - 1);
}
/**
* 返回矩阵的立方(以数组形式)
* @return
*/
public double[][] cube()
{
double[][] X = new double[m][n];
for (int i = 0; i < m; i++) | {
for (int j = 0; j < n; j++)
{
X[i][j] = Math.pow(A[i][j], 3.);
}
}
return X;
}
public void setZero()
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = 0.;
}
}
}
public void save(DataOutputStream out) throws Exception
{
out.writeInt(m);
out.writeInt(n);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
out.writeDouble(A[i][j]);
}
}
}
public boolean load(ByteArray byteArray)
{
m = byteArray.nextInt();
n = byteArray.nextInt();
A = new double[m][n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
A[i][j] = byteArray.nextDouble();
}
}
return true;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\Matrix.java | 1 |
请完成以下Java代码 | public String getFormKey() {
return formKey;
}
@Override
public String getExtraValue() {
return extraValue;
}
@Override
public boolean hasVariable(String variableName) {
return variables.containsKey(variableName);
}
@Override
public Object getVariable(String variableName) {
return variables.get(variableName);
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public Map<String, Object> getPlanItemInstanceLocalVariables() {
return localVariables;
}
@Override | public PlanItem getPlanItem() {
return planItem;
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("planItemDefinitionId='" + planItemDefinitionId + "'")
.add("elementId='" + elementId + "'")
.add("caseInstanceId='" + caseInstanceId + "'")
.add("caseDefinitionId='" + caseDefinitionId + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\ReadOnlyDelegatePlanItemInstanceImpl.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAttributeCount() {
return attributeCount;
}
public void setAttributeCount(Integer attributeCount) {
this.attributeCount = attributeCount;
}
public Integer getParamCount() {
return paramCount;
} | public void setParamCount(Integer paramCount) {
this.paramCount = paramCount;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", attributeCount=").append(attributeCount);
sb.append(", paramCount=").append(paramCount);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttributeCategory.java | 1 |
请完成以下Java代码 | private void createNote(MADBoilerPlate text, I_AD_User user, Exception e)
{
final AdMessageId adMessageId = Services.get(IMsgBL.class).getIdByAdMessage(AD_Message_UserNotifyError)
.orElseThrow(() -> new AdempiereException("@NotFound@ @AD_Message_ID@ " + AD_Message_UserNotifyError));
//
final IMsgBL msgBL = Services.get(IMsgBL.class);
final String reference = msgBL.parseTranslation(getCtx(), "@AD_BoilerPlate_ID@: " + text.get_Translation(MADBoilerPlate.COLUMNNAME_Name))
+ ", " + msgBL.parseTranslation(getCtx(), "@AD_User_ID@: " + user.getName())
// +", "+Msg.parseTranslation(getCtx(), "@AD_PInstance_ID@: "+getAD_PInstance_ID())
;
final MNote note = new MNote(getCtx(),
adMessageId.getRepoId(),
getFromUserId().getRepoId(),
InterfaceWrapperHelper.getModelTableId(user), user.getAD_User_ID(),
reference,
e.getLocalizedMessage(), | get_TrxName());
note.setAD_Org_ID(0);
note.saveEx();
m_count_notes++;
}
static List<EMailAddress> toEMailAddresses(final String string)
{
final StringTokenizer st = new StringTokenizer(string, " ,;", false);
final ArrayList<EMailAddress> result = new ArrayList<>();
while (st.hasMoreTokens())
{
result.add(EMailAddress.ofString(st.nextToken()));
}
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilderPlate_SendToUsers.java | 1 |
请完成以下Java代码 | private void logVersionInfo()
{
try
{
final Enumeration<URL> resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
while (resEnum.hasMoreElements())
{
try
{
final URL url = resEnum.nextElement();
final InputStream is = url.openStream();
if (is != null)
{
final Manifest manifest = new Manifest(is);
final Attributes mainAttribs = manifest.getMainAttributes();
final String version = mainAttribs.getValue("Implementation-Version");
if (version != null)
{
logger.info("Resource " + url + " has version " + version);
}
}
}
catch (final Exception e)
{
// Silently ignore wrong manifests on classpath?
}
}
}
catch (final IOException e1)
{
// Silently ignore wrong manifests on classpath?
} | }
private void run()
{
final Context context = Context.getContext();
context.addSource(new ConfigFileContext());
logVersionInfo();
//
// Start the client
final PrintingClient client = new PrintingClient();
client.start();
final Thread clientThread = client.getDaemonThread();
try
{
clientThread.join();
}
catch (final InterruptedException e)
{
logger.log(Level.INFO, "Interrupted. Exiting.", e);
client.stop();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\PrintingClientStandaloneService.java | 1 |
请完成以下Java代码 | public Set<String> getMappableAttributes() {
return this.mappableAttributes;
}
/**
* Loads the web.xml file using the configured <tt>ResourceLoader</tt> and parses the
* role-name elements from it, using these as the set of <tt>mappableAttributes</tt>.
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.resourceLoader, "resourceLoader cannot be null");
Resource webXml = this.resourceLoader.getResource("/WEB-INF/web.xml");
Document doc = getDocument(webXml.getInputStream());
NodeList webApp = doc.getElementsByTagName("web-app");
Assert.isTrue(webApp.getLength() == 1, () -> "Failed to find 'web-app' element in resource" + webXml);
NodeList securityRoles = ((Element) webApp.item(0)).getElementsByTagName("security-role");
List<String> roleNames = getRoleNames(webXml, securityRoles);
this.mappableAttributes = Collections.unmodifiableSet(new HashSet<>(roleNames));
}
private List<String> getRoleNames(Resource webXml, NodeList securityRoles) {
ArrayList<String> roleNames = new ArrayList<>();
for (int i = 0; i < securityRoles.getLength(); i++) {
Element securityRoleElement = (Element) securityRoles.item(i);
NodeList roles = securityRoleElement.getElementsByTagName("role-name");
if (roles.getLength() > 0) {
String roleName = roles.item(0).getTextContent().trim();
roleNames.add(roleName);
this.logger.info("Retrieved role-name '" + roleName + "' from web.xml");
}
else {
this.logger.info("No security-role elements found in " + webXml);
}
}
return roleNames;
}
/**
* @return Document for the specified InputStream
*/
private Document getDocument(InputStream aStream) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new MyEntityResolver());
return builder.parse(aStream);
}
catch (FactoryConfigurationError | IOException | SAXException | ParserConfigurationException ex) { | throw new RuntimeException("Unable to parse document object", ex);
}
finally {
try {
aStream.close();
}
catch (IOException ex) {
this.logger.warn("Failed to close input stream for web.xml", ex);
}
}
}
/**
* We do not need to resolve external entities, so just return an empty String.
*/
private static final class MyEntityResolver implements EntityResolver {
@Override
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(new StringReader(""));
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\j2ee\WebXmlMappableAttributesRetriever.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DataPoint save(String accountName, Account account) {
Instant instant = LocalDate.now().atStartOfDay()
.atZone(ZoneId.systemDefault()).toInstant();
DataPointId pointId = new DataPointId(accountName, Date.from(instant));
Set<ItemMetric> incomes = account.getIncomes().stream()
.map(this::createItemMetric)
.collect(Collectors.toSet());
Set<ItemMetric> expenses = account.getExpenses().stream()
.map(this::createItemMetric)
.collect(Collectors.toSet());
Map<StatisticMetric, BigDecimal> statistics = createStatisticMetrics(incomes, expenses, account.getSaving());
DataPoint dataPoint = new DataPoint();
dataPoint.setId(pointId);
dataPoint.setIncomes(incomes);
dataPoint.setExpenses(expenses);
dataPoint.setStatistics(statistics);
dataPoint.setRates(ratesService.getCurrentRates());
log.debug("new datapoint has been created: {}", pointId);
return repository.save(dataPoint);
}
private Map<StatisticMetric, BigDecimal> createStatisticMetrics(Set<ItemMetric> incomes, Set<ItemMetric> expenses, Saving saving) {
BigDecimal savingAmount = ratesService.convert(saving.getCurrency(), Currency.getBase(), saving.getAmount());
BigDecimal expensesAmount = expenses.stream()
.map(ItemMetric::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal incomesAmount = incomes.stream() | .map(ItemMetric::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return ImmutableMap.of(
StatisticMetric.EXPENSES_AMOUNT, expensesAmount,
StatisticMetric.INCOMES_AMOUNT, incomesAmount,
StatisticMetric.SAVING_AMOUNT, savingAmount
);
}
/**
* Normalizes given item amount to {@link Currency#getBase()} currency with
* {@link TimePeriod#getBase()} time period
*/
private ItemMetric createItemMetric(Item item) {
BigDecimal amount = ratesService
.convert(item.getCurrency(), Currency.getBase(), item.getAmount())
.divide(item.getPeriod().getBaseRatio(), 4, RoundingMode.HALF_UP);
return new ItemMetric(item.getTitle(), amount);
}
} | repos\piggymetrics-master\statistics-service\src\main\java\com\piggymetrics\statistics\service\StatisticsServiceImpl.java | 2 |
请完成以下Java代码 | private String elementToString(@Nullable final Object element)
{
if (element == null)
{
return null;
}
try
{
final StringResult result = new StringResult();
marshaller.marshal(element, result);
return cleanupPdfData(result.toString());
}
catch (final Exception ex) | {
throw new AdempiereException("Failed converting " + element + " to String", ex);
}
}
/**
* remove the pdfdata since it's long and useless and we also attach it to the PO record
*/
@NonNull
@VisibleForTesting
static String cleanupPdfData(@NonNull final String s)
{
return s.replaceAll(PARCELLABELS_PDF_REGEX, PARCELLABELS_PDF_REPLACEMENT_TEXT);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java\de\metas\shipper\gateway\dpd\logger\DpdClientLogEvent.java | 1 |
请完成以下Java代码 | public class PickingShipmentCandidate
{
@NonNull @Delegate private final PickingShipmentCandidateKey key;
@NonNull @Getter private final ImmutableSet<HuId> onlyLUIds;
@NonNull @Getter private final CreateShipmentPolicy createShipmentPolicy;
@NonNull private final HashSet<ShipmentScheduleAndJobScheduleId> scheduleIds = new HashSet<>();
@Builder
private PickingShipmentCandidate(
@NonNull final PickingShipmentCandidateKey key,
@Nullable final Set<HuId> onlyLUIds,
@Nullable final CreateShipmentPolicy createShipmentPolicy)
{
this.key = key;
this.onlyLUIds = onlyLUIds != null ? ImmutableSet.copyOf(onlyLUIds) : ImmutableSet.of();
this.createShipmentPolicy = createShipmentPolicy != null ? createShipmentPolicy : CreateShipmentPolicy.CREATE_COMPLETE_CLOSE;
if (!this.createShipmentPolicy.isCreateShipment()) | {
throw new AdempiereException("Invalid create shipment policy option: " + this.createShipmentPolicy);
}
}
public void addLine(@NonNull final PickingJobLine line)
{
scheduleIds.add(line.getScheduleId());
}
public ShipmentScheduleAndJobScheduleIdSet getScheduleIds()
{
return ShipmentScheduleAndJobScheduleIdSet.ofCollection(scheduleIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\shipment\PickingShipmentCandidate.java | 1 |
请完成以下Java代码 | public Builder setM_PricingSystem(final I_M_PricingSystem pricingSystem)
{
_pricingSystem = pricingSystem;
return this;
}
public Builder setM_PricingSystemOf(@NonNull final I_M_PriceList_Version plv)
{
final IPriceListDAO priceListsRepo = Services.get(IPriceListDAO.class);
final PriceListId priceListId = PriceListId.ofRepoId(plv.getM_PriceList_ID());
final I_M_PriceList priceList = priceListsRepo.getById(priceListId);
final PricingSystemId pricingSystemId = PricingSystemId.ofRepoIdOrNull(priceList.getM_PricingSystem_ID());
final I_M_PricingSystem pricingSystem = priceListsRepo.getPricingSystemById(pricingSystemId);
return setM_PricingSystem(pricingSystem);
}
private I_M_PricingSystem getM_PricingSystem()
{
Check.assumeNotNull(_pricingSystem, "_pricingSystem not null");
return _pricingSystem;
}
public Builder setM_Material_Tracking(final I_M_Material_Tracking materialTracking)
{
_materialTracking = materialTracking;
return this;
}
private int getM_Material_Tracking_ID()
{
Check.assumeNotNull(_materialTracking, "_materialTracking not null");
return _materialTracking.getM_Material_Tracking_ID();
}
public Builder setAllProductionOrders(final List<IQualityInspectionOrder> qualityInspectionOrders)
{
_allProductionOrders = qualityInspectionOrders;
return this;
}
private List<IQualityInspectionOrder> getProductionOrders()
{ | Check.assumeNotNull(_allProductionOrders, "_qualityInspectionOrders not null");
return _allProductionOrders;
}
public Builder setNotYetInvoicedProductionOrders(final List<IQualityInspectionOrder> qualityInspectionOrders)
{
_notYetInvoicedPPOrderIDs = new HashSet<>();
for (final IQualityInspectionOrder order : qualityInspectionOrders)
{
_notYetInvoicedPPOrderIDs.add(order.getPP_Order().getPP_Order_ID());
}
return this;
}
private Set<Integer> getNotYetInvoicedPPOrderIDs()
{
Check.assumeNotNull(_notYetInvoicedPPOrderIDs, "_notYetInvoicedProductionOrders not null");
return _notYetInvoicedPPOrderIDs;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingDocumentsPricingInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void delete(@NonNull final FailedTimeBookingId failedTimeBookingId)
{
final I_S_FailedTimeBooking record = InterfaceWrapperHelper.load(failedTimeBookingId, I_S_FailedTimeBooking.class);
InterfaceWrapperHelper.delete(record);
}
public Optional<FailedTimeBooking> getOptionalByExternalIdAndSystem(@NonNull final ExternalSystem externalSystem,
@NonNull final String externalId)
{
return queryBL.createQueryBuilder(I_S_FailedTimeBooking.class)
.addEqualsFilter(I_S_FailedTimeBooking.COLUMNNAME_ExternalSystem_ID, externalSystem.getId() )
.addEqualsFilter(I_S_FailedTimeBooking.COLUMNNAME_ExternalId, externalId)
.create()
.firstOnlyOptional(I_S_FailedTimeBooking.class)
.map(this::buildFailedTimeBooking);
}
public ImmutableList<FailedTimeBooking> listBySystem(@NonNull final ExternalSystem externalSystem)
{
return queryBL.createQueryBuilder(I_S_FailedTimeBooking.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_S_FailedTimeBooking.COLUMNNAME_ExternalSystem_ID, externalSystem.getId() )
.create()
.list()
.stream()
.map(this::buildFailedTimeBooking)
.collect(ImmutableList.toImmutableList()); | }
private FailedTimeBooking buildFailedTimeBooking(@NonNull final I_S_FailedTimeBooking record)
{
final ExternalSystem externalSystem = externalSystemRepository.getById(ExternalSystemId.ofRepoId(record.getExternalSystem_ID()));
return FailedTimeBooking.builder()
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.failedTimeBookingId(FailedTimeBookingId.ofRepoId(record.getS_FailedTimeBooking_ID()))
.externalId(record.getExternalId())
.externalSystem(externalSystem)
.jsonValue(record.getJSONValue())
.errorMsg(record.getImportErrorMsg())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\importer\failed\FailedTimeBookingRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Book getByIsbn(String isbn) {
simulateSlowService();
return new Book(isbn, "Some book", "vector");
}
/**
* 最好指定key,此时会根据key将cache中的内容更新为最新
* @param book
* @return
*/
@Override
@CachePut(cacheNames = "books", key = "#book.isbn.hashCode()") // 方法的返回值会被更新到缓存中
public Book update(Book book) {
logger.info("更新book");
return book;
}
/**
* beforeInvocation = true 意味着不管业务如何出错,缓存已清空
* beforeInvocation = false 等待方法处理完之后再清空缓存,缺点是如果逻辑出异常了,会导致缓存不会被清空
*/
@Override
@CacheEvict(cacheNames = "books", allEntries = true, beforeInvocation = true)
public void clear() {
logger.warn("清空books缓存数据");
throw new RuntimeException("测试 beforeInvocation = fasle"); | }
/**
* 模拟慢查询
*/
private void simulateSlowService() {
try {
long time = 3000L;
Thread.sleep(time);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
} | repos\spring-boot-quick-master\quick-cache\src\main\java\com\quick\cache\repo\SimpleBookRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DubboEndpointAnnotationAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@CompatibleConditionalOnEnabledEndpoint
public DubboMetadataEndpoint dubboEndpoint() {
return new DubboMetadataEndpoint();
}
@Bean
@ConditionalOnMissingBean
@CompatibleConditionalOnEnabledEndpoint
public DubboConfigsMetadataEndpoint dubboConfigsMetadataEndpoint() {
return new DubboConfigsMetadataEndpoint();
}
@Bean
@ConditionalOnMissingBean
@CompatibleConditionalOnEnabledEndpoint
public DubboPropertiesMetadataEndpoint dubboPropertiesEndpoint() {
return new DubboPropertiesMetadataEndpoint();
} | @Bean
@ConditionalOnMissingBean
@CompatibleConditionalOnEnabledEndpoint
public DubboReferencesMetadataEndpoint dubboReferencesMetadataEndpoint() {
return new DubboReferencesMetadataEndpoint();
}
@Bean
@ConditionalOnMissingBean
@CompatibleConditionalOnEnabledEndpoint
public DubboServicesMetadataEndpoint dubboServicesMetadataEndpoint() {
return new DubboServicesMetadataEndpoint();
}
@Bean
@ConditionalOnMissingBean
@CompatibleConditionalOnEnabledEndpoint
public DubboShutdownEndpoint dubboShutdownEndpoint() {
return new DubboShutdownEndpoint();
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\autoconfigure\DubboEndpointAnnotationAutoConfiguration.java | 2 |
请完成以下Java代码 | JSONDocumentChangedWebSocketEvent markActiveTabStaled()
{
activeTabStaled = Boolean.TRUE;
return this;
}
private HashMap<String, JSONIncludedTabInfo> getIncludedTabsInfo()
{
if (includedTabsInfoByTabId == null)
{
includedTabsInfoByTabId = new HashMap<>();
}
return includedTabsInfoByTabId;
}
private JSONIncludedTabInfo getIncludedTabInfo(final DetailId tabId)
{
return getIncludedTabsInfo().computeIfAbsent(tabId.toJson(), k -> JSONIncludedTabInfo.newInstance(tabId));
}
void addIncludedTabInfo(@NonNull final JSONIncludedTabInfo tabInfo)
{
getIncludedTabsInfo().compute(tabInfo.getTabId().toJson(), (tabId, existingTabInfo) -> {
if (existingTabInfo == null)
{
return tabInfo.copy();
}
else
{
existingTabInfo.mergeFrom(tabInfo);
return existingTabInfo;
}
});
}
@Override
@JsonIgnore
public WebsocketTopicName getWebsocketEndpoint()
{
return WebsocketTopicNames.buildDocumentTopicName(windowId, id);
}
public void staleTabs(@NonNull final Collection<DetailId> tabIds)
{
tabIds.stream().map(this::getIncludedTabInfo).forEach(JSONIncludedTabInfo::markAllRowsStaled);
} | public void staleIncludedRows(@NonNull final DetailId tabId, @NonNull final DocumentIdsSelection rowIds)
{
getIncludedTabInfo(tabId).staleRows(rowIds);
}
void mergeFrom(@NonNull final JSONDocumentChangedWebSocketEvent from)
{
if (!Objects.equals(windowId, from.windowId)
|| !Objects.equals(id, from.id))
{
throw new AdempiereException("Cannot merge events because they are not matching")
.setParameter("from", from)
.setParameter("to", this)
.appendParametersToMessage();
}
if (from.stale != null && from.stale)
{
stale = from.stale;
}
from.getIncludedTabsInfo().values().forEach(this::addIncludedTabInfo);
if (from.activeTabStaled != null && from.activeTabStaled)
{
activeTabStaled = from.activeTabStaled;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\JSONDocumentChangedWebSocketEvent.java | 1 |
请完成以下Java代码 | public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static ResponseData success() {
return new ResponseData(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage(), null);
}
public static <E> ResponseData<E> success(E object) {
return new ResponseData(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage(), object);
} | public static <E> ResponseData<E> success(Integer code, String message, E object) {
return new ResponseData(code, message, object);
}
public static ResponseData error() {
return new ResponseData(ResponseCode.FAILED.getCode(), ResponseCode.FAILED.getMessage(), null);
}
public static ResponseData error(ResponseCode code) {
return new ResponseData(code.getCode(), code.getMessage(), null);
}
public static ResponseData error(String message) {
return new ResponseData(ResponseCode.FAILED.getCode(), message, null);
}
public static ResponseData error(Integer code, String message) {
return new ResponseData(code, message, null);
}
public static <E> ResponseData<E> error(Integer code, String message, E object) {
return new ResponseData(code, message, object);
}
} | repos\spring-boot-quick-master\quick-flowable\src\main\java\com\quick\flowable\common\ResponseData.java | 1 |
请完成以下Java代码 | public IPOTreeSupport get(@NonNull final String tableName)
{
return get(TableName.ofString(tableName));
}
public IPOTreeSupport get(@NonNull final TableName tableName)
{
// NOTE: we need to create a new instance each time because IPOTreeSupport implementations are stateful
final Class<? extends IPOTreeSupport> cl = map.get(tableName);
final IPOTreeSupport result;
if (cl == null)
{
result = new DefaultPOTreeSupport();
}
else
{
try
{
result = cl.getConstructor().newInstance();
}
catch (final Exception e)
{
throw new AdempiereException(e);
}
}
result.setTableName(tableName.getAsString());
return result; | }
@Override
public void register(@NonNull final String tableName, @NonNull final Class<? extends IPOTreeSupport> clazz)
{
// do checks
try
{
clazz.getConstructor();
}
catch (NoSuchMethodException e)
{
throw new AdempiereException("Class " + clazz + " does not have a public constructor without parameters", e);
}
// register
map.put(TableName.ofString(tableName), clazz);
logger.info("Registered {} for {}", clazz, tableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\tree\impl\POTreeSupportFactory.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* AD_Language AD_Reference_ID=106
* Reference name: AD_Language
*/
public static final int AD_LANGUAGE_AD_Reference_ID=106;
@Override
public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setDescription_Customized (final @Nullable java.lang.String Description_Customized)
{
set_Value (COLUMNNAME_Description_Customized, Description_Customized);
}
@Override
public java.lang.String getDescription_Customized()
{
return get_ValueAsString(COLUMNNAME_Description_Customized);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public void setIsUseCustomization (final boolean IsUseCustomization)
{
set_Value (COLUMNNAME_IsUseCustomization, IsUseCustomization);
}
@Override
public boolean isUseCustomization()
{
return get_ValueAsBoolean(COLUMNNAME_IsUseCustomization);
}
@Override
public void setMobile_Application_ID (final int Mobile_Application_ID)
{
if (Mobile_Application_ID < 1) | set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID);
}
@Override
public int getMobile_Application_ID()
{
return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID);
}
@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 setName_Customized (final @Nullable java.lang.String Name_Customized)
{
set_Value (COLUMNNAME_Name_Customized, Name_Customized);
}
@Override
public java.lang.String getName_Customized()
{
return get_ValueAsString(COLUMNNAME_Name_Customized);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application_Trl.java | 1 |
请完成以下Java代码 | public long getMaxMemoryUsed() {
return maxMemoryUsed;
}
public SecureJavascriptConfigurator setMaxMemoryUsed(long maxMemoryUsed) {
this.maxMemoryUsed = maxMemoryUsed;
return this;
}
public int getScriptOptimizationLevel() {
return scriptOptimizationLevel;
}
public SecureJavascriptConfigurator setScriptOptimizationLevel(int scriptOptimizationLevel) {
this.scriptOptimizationLevel = scriptOptimizationLevel;
return this;
} | public SecureScriptContextFactory getSecureScriptContextFactory() {
return secureScriptContextFactory;
}
public static SecureScriptClassShutter getSecureScriptClassShutter() {
return secureScriptClassShutter;
}
public SecureJavascriptConfigurator setEnableAccessToBeans(boolean enableAccessToBeans) {
this.enableAccessToBeans = enableAccessToBeans;
return this;
}
public boolean isEnableAccessToBeans() {
return enableAccessToBeans;
}
} | repos\flowable-engine-main\modules\flowable-secure-javascript\src\main\java\org\flowable\scripting\secure\SecureJavascriptConfigurator.java | 1 |
请完成以下Java代码 | public int getAD_PrintColor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set 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_OrgType.java | 1 |
请完成以下Java代码 | public PageData<WidgetTypeId> findAllWidgetTypesIds(PageLink pageLink) {
return DaoUtil.pageToPageData(widgetTypeRepository.findAllIds(DaoUtil.toPageable(pageLink)).map(WidgetTypeId::new));
}
@Override
public List<WidgetTypeInfo> findByTenantAndImageLink(TenantId tenantId, String imageUrl, int limit) {
return DaoUtil.convertDataList(widgetTypeInfoRepository.findByTenantAndImageUrl(tenantId.getId(), imageUrl, limit));
}
@Override
public List<WidgetTypeInfo> findByImageLink(String imageUrl, int limit) {
return DaoUtil.convertDataList(widgetTypeInfoRepository.findByImageUrl(imageUrl, limit));
}
@Override
public PageData<WidgetTypeDetails> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<WidgetTypeFields> findNextBatch(UUID id, int batchSize) { | return widgetTypeRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public List<EntityInfo> findByTenantIdAndResource(TenantId tenantId, String reference, int limit) {
return widgetTypeInfoRepository.findWidgetTypeInfosByTenantIdAndResourceLink(tenantId.getId(), reference, PageRequest.of(0, limit));
}
@Override
public List<EntityInfo> findByResource(String reference, int limit) {
return widgetTypeInfoRepository.findWidgetTypeInfosByResourceLink(reference, PageRequest.of(0, limit));
}
@Override
public EntityType getEntityType() {
return EntityType.WIDGET_TYPE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\widget\JpaWidgetTypeDao.java | 1 |
请完成以下Java代码 | public class HistoricJobLogResourceImpl implements HistoricJobLogResource {
protected String id;
protected ProcessEngine engine;
public HistoricJobLogResourceImpl(String id, ProcessEngine engine) {
this.id = id;
this.engine = engine;
}
public HistoricJobLogDto getHistoricJobLog() {
HistoryService historyService = engine.getHistoryService();
HistoricJobLog historicJobLog = historyService
.createHistoricJobLogQuery()
.logId(id)
.singleResult();
if (historicJobLog == null) {
throw new InvalidRequestException(Status.NOT_FOUND, "Historic job log with id " + id + " does not exist");
} | return HistoricJobLogDto.fromHistoricJobLog(historicJobLog);
}
public String getStacktrace() {
try {
HistoryService historyService = engine.getHistoryService();
String stacktrace = historyService.getHistoricJobLogExceptionStacktrace(id);
return stacktrace;
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage());
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\history\impl\HistoricJobLogResourceImpl.java | 1 |
请完成以下Java代码 | /* package */IValidationContext getValidationContext()
{
final GridField gridField = m_mField;
// In case there is no GridField set (e.g. VLookup was created from a custom swing form)
if (gridField == null)
{
return IValidationContext.DISABLED;
}
final IValidationContext evalCtx = Services.get(IValidationRuleFactory.class).createValidationContext(gridField);
// In case grid field validation context could not be created, disable validation
// NOTE: in most of the cases when we reach this point is when we are in a custom form which used GridFields to create the lookups
// but those custom fields does not have a GridTab
// e.g. de.metas.paymentallocation.form.PaymentAllocationForm
if (evalCtx == null)
{
return IValidationContext.DISABLED;
}
return evalCtx;
}
@Override
public void addFocusListener(final FocusListener l)
{
getEditorComponent().addFocusListener(l);
}
@Override
public void removeFocusListener(FocusListener l)
{ | getEditorComponent().removeFocusListener(l);
}
public void setInfoWindowEnabled(final boolean enabled)
{
this.infoWindowEnabled = enabled;
if (m_button != null)
{
m_button.setVisible(enabled);
}
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
} // VLookup | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLookup.java | 1 |
请完成以下Java代码 | public class CompiledExecutableScript extends ExecutableScript {
private final static ScriptLogger LOG = ProcessEngineLogger.SCRIPT_LOGGER;
protected CompiledScript compiledScript;
protected CompiledExecutableScript(String language) {
this(language, null);
}
protected CompiledExecutableScript(String language, CompiledScript compiledScript) {
super(language);
this.compiledScript = compiledScript;
}
public CompiledScript getCompiledScript() {
return compiledScript;
}
public void setCompiledScript(CompiledScript compiledScript) {
this.compiledScript = compiledScript;
} | public Object evaluate(ScriptEngine scriptEngine, VariableScope variableScope, Bindings bindings) {
try {
LOG.debugEvaluatingCompiledScript(language);
return getCompiledScript().eval(bindings);
} catch (ScriptException e) {
if (e.getCause() instanceof BpmnError) {
throw (BpmnError) e.getCause();
}
String activityIdMessage = getActivityIdExceptionMessage(variableScope);
throw new ScriptEvaluationException("Unable to evaluate script" + activityIdMessage +": " + e.getMessage(), e);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\CompiledExecutableScript.java | 1 |
请完成以下Java代码 | public static void deliveryDateToPO(final I_GO_DeliveryOrder orderPO, final DeliveryDate deliveryDate)
{
final LocalDate date = deliveryDate != null ? deliveryDate.getDate() : null;
final LocalDateTime timeFrom = deliveryDate != null ? deliveryDate.getDateTimeFrom() : null;
final LocalDateTime timeTo = deliveryDate != null ? deliveryDate.getDateTimeTo() : null;
orderPO.setGO_DeliverToDate(TimeUtil.asTimestamp(date));
orderPO.setGO_DeliverToTimeFrom(TimeUtil.asTimestamp(timeFrom));
orderPO.setGO_DeliverToTimeTo(TimeUtil.asTimestamp(timeTo));
}
public static ContactPerson deliveryContactFromPO(final I_GO_DeliveryOrder orderPO)
{
final String phoneNo = orderPO.getGO_DeliverToPhoneNo();
if (Check.isEmpty(phoneNo, true))
{
return null;
}
return ContactPerson.builder()
.phone(PhoneNumber.fromString(phoneNo))
.build();
}
public static void deliveryContactToPO(final I_GO_DeliveryOrder orderPO, final ContactPerson deliveryContact)
{
orderPO.setGO_DeliverToPhoneNo(deliveryContact != null ? deliveryContact.getPhoneAsStringOrNull() : null);
}
public static DeliveryPosition deliveryPositionFromPO(final I_GO_DeliveryOrder orderPO, final Set<PackageId> mpackageIds)
{
return DeliveryPosition.builder()
.numberOfPackages(orderPO.getGO_NumberOfPackages())
.packageIds(mpackageIds)
.grossWeightKg(BigDecimal.valueOf(orderPO.getGO_GrossWeightKg()))
.content(orderPO.getGO_PackageContentDescription())
.build();
}
public static void deliveryPositionToPO(final I_GO_DeliveryOrder orderPO, final DeliveryPosition deliveryPosition)
{
orderPO.setGO_NumberOfPackages(deliveryPosition.getNumberOfPackages());
final int go_grossWeightKg = deliveryPosition.getGrossWeightKg() | .setScale(0, RoundingMode.UP)
.intValue();
orderPO.setGO_GrossWeightKg(go_grossWeightKg);
orderPO.setGO_PackageContentDescription(deliveryPosition.getContent());
}
// ------------
private static int createC_Location_ID(final Address address)
{
final I_C_Location locationPO = InterfaceWrapperHelper.newInstanceOutOfTrx(I_C_Location.class);
locationPO.setAddress1(address.getStreet1());
locationPO.setAddress2(address.getStreet2());
locationPO.setAddress3(address.getHouseNo());
locationPO.setPostal(address.getZipCode());
locationPO.setCity(address.getCity());
final String countryCode2 = address.getCountry().getAlpha2();
final I_C_Country country = Services.get(ICountryDAO.class).retrieveCountryByCountryCode(countryCode2);
locationPO.setC_Country(country);
InterfaceWrapperHelper.save(locationPO);
return locationPO.getC_Location_ID();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\GODeliveryOrderConverters.java | 1 |
请完成以下Java代码 | public String modelChange(PO po, int type) throws Exception
{
if (I_AD_Tab.Table_Name.equals(po.get_TableName()) && type == TYPE_AFTER_CHANGE
&& po.is_ValueChanged(I_AD_Tab.COLUMNNAME_AD_Table_ID))
{
I_AD_Tab tab = InterfaceWrapperHelper.create(po, I_AD_Tab.class);
updateTabFieldColumns(po.getCtx(), tab, po.get_TrxName());
}
if (I_AD_Ref_Table.Table_Name.equals(po.get_TableName())
&& (type == TYPE_BEFORE_NEW || type == TYPE_BEFORE_CHANGE))
{
I_AD_Ref_Table refTable = InterfaceWrapperHelper.create(po, I_AD_Ref_Table.class);
validate(refTable);
}
//
return null;
}
private void validate(I_AD_Ref_Table refTable)
{
String whereClause = refTable.getWhereClause();
if (!Check.isEmpty(whereClause, true) && whereClause.indexOf("@") >= 0)
{
log.warn("Using context variables in table reference where clause is not adviced");
}
}
private void updateTabFieldColumns(Properties ctx, I_AD_Tab tab, String trxName)
{
final String tableName = Services.get(IADTableDAO.class).retrieveTableName(tab.getAD_Table_ID());
final List<I_AD_Field> fields = new Query(ctx, I_AD_Field.Table_Name, I_AD_Field.COLUMNNAME_AD_Tab_ID + "=?", trxName)
.setParameters(tab.getAD_Tab_ID())
.setOrderBy(I_AD_Field.COLUMNNAME_SeqNo)
.list(I_AD_Field.class);
for (I_AD_Field field : fields)
{ | I_AD_Column columnOld = field.getAD_Column();
int columnId = MColumn.getColumn_ID(tableName, columnOld.getColumnName());
if (columnId > 0)
{
field.setAD_Column_ID(columnId);
InterfaceWrapperHelper.save(field);
log.info("Updated AD_Column_ID for field " + field.getName());
}
else
{
log.info("Deleting field " + field.getName());
InterfaceWrapperHelper.getPO(field).deleteEx(true); // TODO: use POWrapper.delete
}
}
}
@Override
public String docValidate(PO po, int timing)
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\model\validator\ApplicationDictionary.java | 1 |
请完成以下Java代码 | protected DocumentBuilder getDocumentBuilder() {
try {
DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
LOG.createdDocumentBuilder();
return docBuilder;
}
catch (ParserConfigurationException e) {
throw LOG.unableToCreateParser(e);
}
}
protected JAXBContext getContext(Class<?>... types) {
try {
return JAXBContext.newInstance(types);
}
catch (JAXBException e) {
throw LOG.unableToCreateContext(e);
}
}
protected Marshaller createMarshaller(Class<?>... types) {
try {
return getContext(types).createMarshaller();
}
catch (JAXBException e) {
throw LOG.unableToCreateMarshaller(e);
}
}
protected Unmarshaller createUnmarshaller(Class<?>... types) {
try {
return getContext(types).createUnmarshaller();
}
catch (JAXBException e) {
throw LOG.unableToCreateUnmarshaller(e);
}
}
public static TransformerFactory defaultTransformerFactory() {
return TransformerFactory.newInstance();
}
public static DocumentBuilderFactory defaultDocumentBuilderFactory() {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
LOG.documentBuilderFactoryConfiguration("namespaceAware", "true");
documentBuilderFactory.setValidating(false);
LOG.documentBuilderFactoryConfiguration("validating", "false"); | documentBuilderFactory.setIgnoringComments(true);
LOG.documentBuilderFactoryConfiguration("ignoringComments", "true");
documentBuilderFactory.setIgnoringElementContentWhitespace(false);
LOG.documentBuilderFactoryConfiguration("ignoringElementContentWhitespace", "false");
return documentBuilderFactory;
}
public static Class<?> loadClass(String classname, DataFormat dataFormat) {
// first try context classoader
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if(cl != null) {
try {
return cl.loadClass(classname);
}
catch(Exception e) {
// ignore
}
}
// else try the classloader which loaded the dataformat
cl = dataFormat.getClass().getClassLoader();
try {
return cl.loadClass(classname);
}
catch (ClassNotFoundException e) {
throw LOG.classNotFound(classname, e);
}
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\xml\DomXmlDataFormat.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public InsuranceContractSalesContracts careType(BigDecimal careType) {
this.careType = careType;
return this;
}
/**
* Art der Versorgung (0 = Unbekannt, 1 = Erstversorgung, 2 = Folgeversorgung)
* @return careType
**/
@Schema(example = "1", description = "Art der Versorgung (0 = Unbekannt, 1 = Erstversorgung, 2 = Folgeversorgung)")
public BigDecimal getCareType() {
return careType;
}
public void setCareType(BigDecimal careType) {
this.careType = careType;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractSalesContracts insuranceContractSalesContracts = (InsuranceContractSalesContracts) o;
return Objects.equals(this.name, insuranceContractSalesContracts.name) &&
Objects.equals(this.careType, insuranceContractSalesContracts.careType);
}
@Override | public int hashCode() {
return Objects.hash(name, careType);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InsuranceContractSalesContracts {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" careType: ").append(toIndentedString(careType)).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-article-api\src\main\java\io\swagger\client\model\InsuranceContractSalesContracts.java | 2 |
请完成以下Java代码 | static class ExternalTaskStateImpl implements ExternalTaskState {
public final int stateCode;
protected final String name;
public ExternalTaskStateImpl(int stateCode, String string) {
this.stateCode = stateCode;
this.name = string;
}
public int getStateCode() {
return stateCode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + stateCode;
return result;
} | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ExternalTaskStateImpl other = (ExternalTaskStateImpl) obj;
return stateCode == other.stateCode;
}
@Override
public String toString() {
return name;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\history\ExternalTaskState.java | 1 |
请完成以下Java代码 | protected void checkSignature(String appKey, String signature, String timestamp, OpenApiAuth openApiAuth) {
if(openApiAuth==null){
throw new JeecgBootException("不存在认证信息");
}
if(!appKey.equals(openApiAuth.getAk())){
throw new JeecgBootException("appkey错误");
}
if (!signature.equals(md5(appKey + openApiAuth.getSk() + timestamp))) {
throw new JeecgBootException("signature签名错误");
}
}
protected void checkPermission(OpenApi openApi, OpenApiAuth openApiAuth) {
List<OpenApiPermission> permissionList = openApiPermissionService.findByAuthId(openApiAuth.getId());
boolean hasPermission = false;
for (OpenApiPermission permission : permissionList) {
if (permission.getApiId().equals(openApi.getId())) {
hasPermission = true;
break;
}
}
if (!hasPermission) {
throw new JeecgBootException("该appKey未授权当前接口");
}
}
/**
* @return String 返回类型
* @Title: MD5
* @Description: 【MD5加密】
*/
protected static String md5(String sourceStr) {
String result = "";
try { | MessageDigest md = MessageDigest.getInstance("MD5");
md.update(sourceStr.getBytes("utf-8"));
byte[] hash = md.digest();
int i;
StringBuffer buf = new StringBuffer(32);
for (int offset = 0; offset < hash.length; offset++) {
i = hash[offset];
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
result = buf.toString();
} catch (Exception e) {
log.error("sign签名错误", e);
}
return result;
}
protected OpenApi findOpenApi(HttpServletRequest request) {
String uri = request.getRequestURI();
String path = uri.substring(uri.lastIndexOf("/") + 1);
return openApiService.findByPath(path);
}
public static void main(String[] args) {
long timestamp = System.currentTimeMillis();
System.out.println("timestamp:" + timestamp);
System.out.println("signature:" + md5("ak-eAU25mrMxhtaZsyS" + "rjxMqB6YyUXpSHAz4DCIz8vZ5aozQQiV" + timestamp));
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\filter\ApiAuthFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ContactType getContact() {
return contact;
}
/**
* Sets the value of the contact property.
*
* @param value
* allowed object is
* {@link ContactType }
*
*/
public void setContact(ContactType value) {
this.contact = value;
}
/**
* Address details of the party.
*
* @return
* possible object is
* {@link AddressType } | *
*/
public AddressType getAddress() {
return address;
}
/**
* Sets the value of the address property.
*
* @param value
* allowed object is
* {@link AddressType }
*
*/
public void setAddress(AddressType value) {
this.address = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\BusinessEntityType.java | 2 |
请完成以下Java代码 | public ConfigureConnectionsResult configureConnectionsIfArgsProvided(@Nullable final CommandLineOptions commandLineOptions)
{
if (commandLineOptions == null)
{
return new ConfigureConnectionsResult(false);
}
// CConnection
ConfigureConnectionsResult result;
if (Check.isNotBlank(commandLineOptions.getDbHost()) || commandLineOptions.getDbPort() != null)
{
final CConnectionAttributes connectionAttributes = CConnectionAttributes.builder()
.dbHost(commandLineOptions.getDbHost())
.dbPort(commandLineOptions.getDbPort())
.dbName(coalesce(commandLineOptions.getDbName(), "metasfresh"))
.dbUid(coalesce(commandLineOptions.getDbUser(), "metasfresh"))
.dbPwd(coalesce(commandLineOptions.getDbPassword(), "metasfresh"))
.build();
logger.info("!!!!!!!!!!!!!!!!\n"
+ "!! dbHost and/or dbPort were set from cmdline; -> will ignore DB-Settings from metasfresh.properties and connect to DB with {}\n"
+ "!!!!!!!!!!!!!!!!", connectionAttributes);
CConnection.createInstance(connectionAttributes);
result = new ConfigureConnectionsResult(true);
}
else
{
result = new ConfigureConnectionsResult(false);
} | // RabbitMQ
if (Check.isNotBlank(commandLineOptions.getRabbitHost()))
{
System.setProperty("spring.rabbitmq.host", commandLineOptions.getRabbitHost());
}
if (commandLineOptions.getRabbitPort() != null)
{
System.setProperty("spring.rabbitmq.port", Integer.toString(commandLineOptions.getRabbitPort()));
}
if (Check.isNotBlank(commandLineOptions.getRabbitUser()))
{
System.setProperty("spring.rabbitmq.username", commandLineOptions.getRabbitUser());
}
if (Check.isNotBlank(commandLineOptions.getRabbitPassword()))
{
System.setProperty("spring.rabbitmq.password", commandLineOptions.getRabbitPassword());
}
return result;
}
@Value
public static class ConfigureConnectionsResult
{
boolean cconnectionConfigured;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\de\metas\util\ConnectionUtil.java | 1 |
请完成以下Java代码 | private JsonDeliveryOrderParcel toJsonDeliveryOrderLine(@NonNull final DeliveryOrderParcel line)
{
return JsonDeliveryOrderParcel.builder()
.id(line.getId() != null ? String.valueOf(line.getId().getRepoId()) : null)
.content(line.getContent())
.grossWeightKg(line.getGrossWeightKg())
.packageDimensions(toJsonPackageDimensions(line.getPackageDimensions()))
.packageId(line.getPackageId().toString())
.contents(java.util.Collections.emptyList())
.build();
}
private JsonPackageDimensions toJsonPackageDimensions(final PackageDimensions dims)
{
if (dims == null) {return JsonPackageDimensions.builder().lengthInCM(0).widthInCM(0).heightInCM(0).build();}
return JsonPackageDimensions.builder()
.lengthInCM(dims.getLengthInCM())
.widthInCM(dims.getWidthInCM())
.heightInCM(dims.getHeightInCM())
.build();
}
@NonNull
private JsonMappingConfigList toJsonMappingConfigList(@NonNull final ShipperMappingConfigList configs)
{
if (configs == ShipperMappingConfigList.EMPTY)
{
return JsonMappingConfigList.EMPTY;
}
return JsonMappingConfigList.ofList(
StreamSupport.stream(configs.spliterator(), false)
.map(this::toJsonMappingConfig) | .collect(ImmutableList.toImmutableList()));
}
@NonNull
private JsonMappingConfig toJsonMappingConfig(@NonNull final ShipperMappingConfig config)
{
final CarrierProduct carrierProduct = config.getCarrierProductId() != null ? carrierProductRepository.getCachedShipperProductById(config.getCarrierProductId()) : null;
return JsonMappingConfig.builder()
.seqNo(config.getSeqNo().toInt())
.shipperProductExternalId(carrierProduct != null ? carrierProduct.getCode() : null)
.attributeType(config.getAttributeType().getCode())
.groupKey(config.getGroupKey())
.attributeKey(config.getAttributeKey())
.attributeValue(config.getAttributeValue().getCode())
.mappingRule(config.getMappingRule() != null ? config.getMappingRule().getCode() : null)
.mappingRuleValue(config.getMappingRuleValue())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\converters\v1\JsonShipperConverter.java | 1 |
请完成以下Java代码 | public int getDATEV_ExportFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DATEV_ExportFormat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Decimal Separator.
@param DecimalSeparator Decimal Separator */
@Override
public void setDecimalSeparator (java.lang.String DecimalSeparator)
{
set_Value (COLUMNNAME_DecimalSeparator, DecimalSeparator);
}
/** Get Decimal Separator.
@return Decimal Separator */
@Override
public java.lang.String getDecimalSeparator ()
{
return (java.lang.String)get_Value(COLUMNNAME_DecimalSeparator);
}
/** 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 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);
}
/** Set Number Grouping Separator.
@param NumberGroupingSeparator Number Grouping Separator */
@Override
public void setNumberGroupingSeparator (java.lang.String NumberGroupingSeparator)
{
set_Value (COLUMNNAME_NumberGroupingSeparator, NumberGroupingSeparator);
}
/** Get Number Grouping Separator.
@return Number Grouping Separator */
@Override
public java.lang.String getNumberGroupingSeparator ()
{
return (java.lang.String)get_Value(COLUMNNAME_NumberGroupingSeparator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportFormat.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PaymentReservationCaptureRepository
{
public void save(@NonNull final PaymentReservationCapture capture)
{
final I_C_Payment_Reservation_Capture captureRecord = capture.getId() != null
? load(capture.getId(), I_C_Payment_Reservation_Capture.class)
: newInstance(I_C_Payment_Reservation_Capture.class);
updateCaptureRecord(captureRecord, capture);
saveRecord(captureRecord);
capture.setId(extractCaptureId(captureRecord));
}
private static void updateCaptureRecord(
@NonNull final I_C_Payment_Reservation_Capture record,
@NonNull final PaymentReservationCapture from)
{
record.setC_Payment_Reservation_ID(from.getReservationId().getRepoId());
record.setStatus(from.getStatus().getCode());
record.setAD_Org_ID(from.getOrgId().getRepoId());
record.setC_Order_ID(from.getSalesOrderId().getRepoId());
record.setC_Invoice_ID(from.getSalesInvoiceId().getRepoId());
record.setC_Payment_ID(from.getPaymentId().getRepoId());
record.setAmount(from.getAmount().toBigDecimal());
record.setC_Currency_ID(from.getAmount().getCurrencyId().getRepoId());
} | private static PaymentReservationCaptureId extractCaptureId(final I_C_Payment_Reservation_Capture captureRecord)
{
return PaymentReservationCaptureId.ofRepoId(captureRecord.getC_Payment_Reservation_Capture_ID());
}
@SuppressWarnings("unused")
private static PaymentReservationCapture toPaymentReservationCapture(@NonNull final I_C_Payment_Reservation_Capture record)
{
return PaymentReservationCapture.builder()
.id(PaymentReservationCaptureId.ofRepoIdOrNull(record.getC_Payment_Reservation_Capture_ID()))
.reservationId(PaymentReservationId.ofRepoId(record.getC_Payment_Reservation_ID()))
.status(PaymentReservationCaptureStatus.ofCode(record.getStatus()))
//
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.salesOrderId(OrderId.ofRepoId(record.getC_Order_ID()))
.salesInvoiceId(InvoiceId.ofRepoId(record.getC_Invoice_ID()))
.paymentId(PaymentId.ofRepoId(record.getC_Payment_ID()))
//
.amount(Money.of(record.getAmount(), CurrencyId.ofRepoId(record.getC_Currency_ID())))
//
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationCaptureRepository.java | 2 |
请完成以下Java代码 | public class XxlJobLogReport {
private int id;
private Date triggerDay;
private int runningCount;
private int sucCount;
private int failCount;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getTriggerDay() {
return triggerDay;
}
public void setTriggerDay(Date triggerDay) {
this.triggerDay = triggerDay;
}
public int getRunningCount() {
return runningCount;
}
public void setRunningCount(int runningCount) {
this.runningCount = runningCount;
} | public int getSucCount() {
return sucCount;
}
public void setSucCount(int sucCount) {
this.sucCount = sucCount;
}
public int getFailCount() {
return failCount;
}
public void setFailCount(int failCount) {
this.failCount = failCount;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLogReport.java | 1 |
请完成以下Java代码 | class DebugLogbackConfigurator extends LogbackConfigurator {
DebugLogbackConfigurator(LoggerContext context) {
super(context);
}
@Override
<T extends Converter<?>> void conversionRule(String conversionWord, Class<T> converterClass,
Supplier<T> converterSupplier) {
info("Adding conversion rule of type '" + converterClass.getName() + "' for word '" + conversionWord + "'");
super.conversionRule(conversionWord, converterClass, converterSupplier);
}
@Override
void appender(String name, Appender<?> appender) {
info("Adding appender '" + appender + "' named '" + name + "'");
super.appender(name, appender);
}
@Override
void logger(String name, @Nullable Level level, boolean additive, @Nullable Appender<ILoggingEvent> appender) {
info("Configuring logger '" + name + "' with level '" + level + "'. Additive: " + additive); | if (appender != null) {
info("Adding appender '" + appender + "' to logger '" + name + "'");
}
super.logger(name, level, additive, appender);
}
@Override
void start(LifeCycle lifeCycle) {
info("Starting '" + lifeCycle + "'");
super.start(lifeCycle);
}
private void info(String message) {
getContext().getStatusManager().add(new InfoStatus(message, this));
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\logback\DebugLogbackConfigurator.java | 1 |
请完成以下Java代码 | private static class HUReportRequest
{
@NonNull Properties ctx;
@NonNull AdProcessId adProcessId;
int windowNo;
@NonNull PrintCopies copies;
AdProcessId adJasperProcessId;
@NonNull OptionalBoolean printPreview;
@Nullable String adLanguage;
boolean onErrorThrowException;
@NonNull ImmutableSet<HuId> huIdsToProcess;
@lombok.Builder
private HUReportRequest(
@NonNull final Properties ctx,
@NonNull final AdProcessId adProcessId,
final int windowNo,
@NonNull final PrintCopies copies,
@Nullable final AdProcessId adJasperProcessId,
@Nullable final Boolean printPreview,
@Nullable final String adLanguage,
final boolean onErrorThrowException,
@NonNull final ImmutableSet<HuId> huIdsToProcess) | {
Check.assume(copies.toInt() > 0, "copies > 0");
Check.assumeNotEmpty(huIdsToProcess, "huIdsToProcess is not empty");
this.ctx = ctx;
this.adProcessId = adProcessId;
this.windowNo = windowNo > 0 ? windowNo : Env.WINDOW_None;
this.copies = copies;
this.adJasperProcessId = adJasperProcessId;
this.printPreview = OptionalBoolean.ofNullableBoolean(printPreview);
this.adLanguage = adLanguage;
this.onErrorThrowException = onErrorThrowException;
this.huIdsToProcess = huIdsToProcess;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\HUReportExecutor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Book implements Serializable {
/**
* 编号
*/
@Id
@GeneratedValue
private Long id;
/**
* 书名
*/
private String name;
/**
* 作者
*/
private String writer;
/**
* 简介
*/
private String introduction;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) { | this.name = name;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
} | repos\springboot-learning-example-master\chapter-5-spring-boot-data-jpa\src\main\java\demo\springboot\domain\Book.java | 2 |
请完成以下Java代码 | public class HelloApplicationRunListener implements SpringApplicationRunListener {
public HelloApplicationRunListener(SpringApplication application, String[] args) {
}
@Override
public void starting() {
System.out.println("HelloApplicationRunListener starting......");
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
} | @Override
public void started(ConfigurableApplicationContext context) {
}
@Override
public void running(ConfigurableApplicationContext context) {
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
}
} | repos\SpringAll-master\45.Spring-Boot-SpringApplication\src\main\java\com\example\demo\listener\HelloApplicationRunListener.java | 1 |
请完成以下Java代码 | public static LockFailedException wrapIfNeeded(final Exception e)
{
if (e instanceof LockFailedException)
{
return (LockFailedException)e;
}
else
{
return new LockFailedException("Lock failed: " + e.getLocalizedMessage(), e);
}
}
public LockFailedException(final String message)
{
super(message);
}
public LockFailedException(final String message, final Throwable cause)
{
super(message, cause);
}
public LockFailedException setLockCommand(final ILockCommand lockCommand)
{
setParameter("Lock command", lockCommand);
return this;
} | @Override
public LockFailedException setSql(final String sql, final Object[] sqlParams)
{
super.setSql(sql, sqlParams);
return this;
}
public LockFailedException setRecordToLock(final TableRecordReference recordToLock)
{
super.setRecord(recordToLock);
return this;
}
public LockFailedException setExistingLocks(@NonNull final ImmutableList<ExistingLockInfo> existingLocks)
{
super.setExistingLocks(existingLocks);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\exceptions\LockFailedException.java | 1 |
请完成以下Java代码 | public JSONNotificationsList getNotifications(
@RequestParam(name = "limit", defaultValue = "-1") final int limit //
)
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
final UserNotificationsList notifications = userNotificationsService.getNotifications(adUserId, QueryLimit.ofInt(limit));
final JSONOptions jsonOpts = JSONOptions.of(userSession);
return JSONNotificationsList.of(notifications, jsonOpts);
}
@GetMapping("/unreadCount")
public int getNotificationsUnreadCount()
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
return userNotificationsService.getNotificationsUnreadCount(adUserId);
}
@PutMapping("/{notificationId}/read")
public void markAsRead(@PathVariable("notificationId") final String notificationId)
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
userNotificationsService.markNotificationAsRead(adUserId, notificationId);
}
@PutMapping("/all/read")
public void markAllAsRead()
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
userNotificationsService.markAllNotificationsAsRead(adUserId);
}
@DeleteMapping("/{notificationId}")
public void deleteById(@PathVariable("notificationId") final String notificationId)
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
userNotificationsService.deleteNotification(adUserId, notificationId);
} | @DeleteMapping
public void deleteByIds(@RequestParam(name = "ids") final String notificationIdsListStr)
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
final List<String> notificationIds = Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.splitToList(notificationIdsListStr);
if (notificationIds.isEmpty())
{
throw new AdempiereException("No IDs provided");
}
notificationIds.forEach(notificationId -> userNotificationsService.deleteNotification(adUserId, notificationId));
}
@DeleteMapping("/all")
public void deleteAll()
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
userNotificationsService.deleteAllNotification(adUserId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\NotificationRestController.java | 1 |
请完成以下Java代码 | public static String getLocalIpAddress() {
try {
return Inet4Address.getLocalHost()
.getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public static List<String> getAllLocalIpAddressUsingNetworkInterface() {
List<String> ipAddress = new ArrayList<>();
Enumeration<NetworkInterface> networkInterfaceEnumeration = null;
try {
networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
throw new RuntimeException(e);
}
for (; networkInterfaceEnumeration.hasMoreElements(); ) {
NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement(); | try {
if (!networkInterface.isUp() || networkInterface.isLoopback()) {
continue;
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
Enumeration<InetAddress> address = networkInterface.getInetAddresses();
for (; address.hasMoreElements(); ) {
InetAddress addr = address.nextElement();
ipAddress.add(addr.getHostAddress());
}
}
return ipAddress;
}
} | repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\iplookup\IPAddressLookup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DubboShutdownMetadata extends AbstractDubboMetadata {
public Map<String, Object> shutdown() throws Exception {
Map<String, Object> shutdownCountData = new LinkedHashMap<>();
// registries
int registriesCount = getRegistries().size();
// protocols
int protocolsCount = getProtocolConfigsBeanMap().size();
shutdownCountData.put("registries", registriesCount);
shutdownCountData.put("protocols", protocolsCount);
// Service Beans
Map<String, ServiceBean> serviceBeansMap = getServiceBeansMap();
if (!serviceBeansMap.isEmpty()) {
for (ServiceBean serviceBean : serviceBeansMap.values()) {
serviceBean.destroy();
} | }
shutdownCountData.put("services", serviceBeansMap.size());
// Reference Beans
ReferenceAnnotationBeanPostProcessor beanPostProcessor = getReferenceAnnotationBeanPostProcessor();
int referencesCount = beanPostProcessor.getReferenceBeans().size();
beanPostProcessor.destroy();
shutdownCountData.put("references", referencesCount);
// Set Result to complete
Map<String, Object> shutdownData = new TreeMap<>();
shutdownData.put("shutdown.count", shutdownCountData);
return shutdownData;
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\endpoint\metadata\DubboShutdownMetadata.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult<OmsOrderDetail> detail(@PathVariable Long id) {
OmsOrderDetail orderDetailResult = orderService.detail(id);
return CommonResult.success(orderDetailResult);
}
@ApiOperation("修改收货人信息")
@RequestMapping(value = "/update/receiverInfo", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateReceiverInfo(@RequestBody OmsReceiverInfoParam receiverInfoParam) {
int count = orderService.updateReceiverInfo(receiverInfoParam);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("修改订单费用信息")
@RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateReceiverInfo(@RequestBody OmsMoneyInfoParam moneyInfoParam) {
int count = orderService.updateMoneyInfo(moneyInfoParam);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed(); | }
@ApiOperation("备注订单")
@RequestMapping(value = "/update/note", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateNote(@RequestParam("id") Long id,
@RequestParam("note") String note,
@RequestParam("status") Integer status) {
int count = orderService.updateNote(id, note, status);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\OmsOrderController.java | 2 |
请完成以下Java代码 | public LookupValuesList getAttributeTypeahead(final String attributeName, final String query)
{
throw new UnsupportedOperationException();
// return asiDoc.getFieldLookupValuesForQuery(attributeName, query);
}
@Override
public LookupValuesList getAttributeDropdown(final String attributeName)
{
throw new UnsupportedOperationException();
// return asiDoc.getFieldLookupValues(attributeName);
}
@Override
public JSONViewRowAttributes toJson(final JSONOptions jsonOpts)
{
final JSONViewRowAttributes jsonDocument = new JSONViewRowAttributes(documentPath);
final List<JSONDocumentField> jsonFields = asiDoc.getFieldViews()
.stream()
.map(field -> toJSONDocumentField(field, jsonOpts)) | .collect(Collectors.toList());
jsonDocument.setFields(jsonFields);
return jsonDocument;
}
private JSONDocumentField toJSONDocumentField(final IDocumentFieldView field, final JSONOptions jsonOpts)
{
final String fieldName = field.getFieldName();
final Object jsonValue = field.getValueAsJsonObject(jsonOpts);
final DocumentFieldWidgetType widgetType = field.getWidgetType();
return JSONDocumentField.ofNameAndValue(fieldName, jsonValue)
.setDisplayed(true)
.setMandatory(false)
.setReadonly(true)
.setWidgetType(JSONLayoutWidgetType.fromNullable(widgetType));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ASIViewRowAttributes.java | 1 |
请完成以下Java代码 | public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if(obj == null) { | return false;
}
if (getClass() != obj.getClass()) {
return false;
}
BusinessKeyBook other = (BusinessKeyBook) obj;
return Objects.equals(isbn, other.getIsbn());
}
@Override
public int hashCode() {
return Objects.hash(isbn);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootLombokEqualsAndHashCode\src\main\java\com\app\BusinessKeyBook.java | 1 |
请完成以下Java代码 | public class FloatWrapperLookup extends Lookup {
private Float[] elements;
private final float pivot = 2;
@Override
@Setup
public void prepare() {
float common = 1;
elements = new Float[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark | @BenchmarkMode(Mode.AverageTime)
public int findPosition() {
int index = 0;
Float pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return FloatWrapperLookup.class.getSimpleName();
}
} | repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\primitive\FloatWrapperLookup.java | 1 |
请完成以下Java代码 | private void onEmptyElement() throws XMLStreamException {
state = SEEN_ELEMENT;
if (depth > 0) {
super.writeCharacters("\n");
}
doIndent();
}
/**
* Print indentation for the current level.
*
* @exception org.xml.sax.SAXException
* If there is an error writing the indentation characters, or if a filter further down the chain raises an exception.
*/
private void doIndent() throws XMLStreamException {
if (depth > 0) {
for (int i = 0; i < depth; i++) super.writeCharacters(indentStep);
}
}
public void writeStartDocument() throws XMLStreamException {
super.writeStartDocument();
super.writeCharacters("\n");
}
public void writeStartDocument(String version) throws XMLStreamException {
super.writeStartDocument(version);
super.writeCharacters("\n");
}
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
super.writeStartDocument(encoding, version);
super.writeCharacters("\n");
}
public void writeStartElement(String localName) throws XMLStreamException {
onStartElement();
super.writeStartElement(localName);
}
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
onStartElement();
super.writeStartElement(namespaceURI, localName);
}
public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
onStartElement();
super.writeStartElement(prefix, localName, namespaceURI);
} | public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
onEmptyElement();
super.writeEmptyElement(namespaceURI, localName);
}
public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
onEmptyElement();
super.writeEmptyElement(prefix, localName, namespaceURI);
}
public void writeEmptyElement(String localName) throws XMLStreamException {
onEmptyElement();
super.writeEmptyElement(localName);
}
public void writeEndElement() throws XMLStreamException {
onEndElement();
super.writeEndElement();
}
public void writeCharacters(String text) throws XMLStreamException {
state = SEEN_DATA;
super.writeCharacters(text);
}
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
state = SEEN_DATA;
super.writeCharacters(text, start, len);
}
public void writeCData(String data) throws XMLStreamException {
state = SEEN_DATA;
super.writeCData(data);
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\IndentingXMLStreamWriter.java | 1 |
请完成以下Java代码 | public String getAlias()
{
return m_alias;
} // getAlias
/**
* Column has Alias.
* (i.e. has a key)
* @return true if Alias
*/
public boolean hasAlias()
{
return !m_columnName.equals(m_alias);
} // hasAlias
/**
* Column value forces page break
* @return true if page break
*/
public boolean isPageBreak()
{
return m_pageBreak;
} // isPageBreak
/**
* String Representation | * @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("PrintDataColumn[");
sb.append("ID=").append(m_AD_Column_ID)
.append("-").append(m_columnName);
if (hasAlias())
sb.append("(").append(m_alias).append(")");
sb.append(",DisplayType=").append(m_displayType)
.append(",Size=").append(m_columnSize)
.append("]");
return sb.toString();
} // toString
public void setFormatPattern(String formatPattern) {
m_FormatPattern = formatPattern;
}
public String getFormatPattern() {
return m_FormatPattern;
}
} // PrintDataColumn | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataColumn.java | 1 |
请完成以下Java代码 | public void addField(String field) {
this.fields.add(field);
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getName() {
return name;
}
public Set<String> getFields() {
return new HashSet<>(fields);
}
public void setName(String name) {
this.name = name;
}
public void setFields(Set<String> fields) {
this.fields = fields;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public boolean isAll() {
return all;
}
public void setAll(boolean all) {
this.all = all;
}
/**
* 判断是否有相同字段
*
* @param fieldString
* @return
*/ | public boolean existSameField(String fieldString) {
String[] controlFields = fieldString.split(",");
for (String sqlField : fields) {
for (String controlField : controlFields) {
if (sqlField.equals(controlField)) {
// 非常明确的列直接比较
log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询");
return true;
} else {
// 使用表达式的列 只能判读字符串包含了
String aliasColumn = controlField;
if (StringUtils.isNotBlank(alias)) {
aliasColumn = alias + "." + controlField;
}
if (sqlField.indexOf(aliasColumn) != -1) {
log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询");
return true;
}
}
}
}
return false;
}
@Override
public String toString() {
return "QueryTable{" +
"name='" + name + '\'' +
", alias='" + alias + '\'' +
", fields=" + fields +
", all=" + all +
'}';
}
}
public String getError(){
// TODO
return "系统设置了安全规则,敏感表和敏感字段禁止查询,联系管理员授权!";
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\security\AbstractQueryBlackListHandler.java | 1 |
请完成以下Java代码 | public MigrationInstructionsBuilder mapEqualActivities() {
this.mapEqualActivities = true;
return this;
}
@Override
public MigrationPlanBuilder setVariables(Map<String, ?> variables) {
if (variables instanceof VariableMapImpl) {
this.variables = (VariableMapImpl) variables;
} else if (variables != null) {
this.variables = new VariableMapImpl(new HashMap<>(variables));
}
return this;
}
public MigrationInstructionBuilder mapActivities(String sourceActivityId, String targetActivityId) {
this.explicitMigrationInstructions.add(
new MigrationInstructionImpl(sourceActivityId, targetActivityId)
);
return this;
}
public MigrationInstructionBuilder updateEventTrigger() {
explicitMigrationInstructions
.get(explicitMigrationInstructions.size() - 1)
.setUpdateEventTrigger(true);
return this;
}
public MigrationInstructionsBuilder updateEventTriggers() {
this.updateEventTriggersForGeneratedInstructions = true;
return this;
}
public String getSourceProcessDefinitionId() {
return sourceProcessDefinitionId;
}
public String getTargetProcessDefinitionId() {
return targetProcessDefinitionId;
}
public boolean isMapEqualActivities() { | return mapEqualActivities;
}
public VariableMap getVariables() {
return variables;
}
public boolean isUpdateEventTriggersForGeneratedInstructions() {
return updateEventTriggersForGeneratedInstructions;
}
public List<MigrationInstructionImpl> getExplicitMigrationInstructions() {
return explicitMigrationInstructions;
}
public MigrationPlan build() {
return commandExecutor.execute(new CreateMigrationPlanCmd(this));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\MigrationPlanBuilderImpl.java | 1 |
请完成以下Java代码 | private void configureSsl(AbstractHttp11Protocol<?> protocol, @Nullable SslBundle sslBundle,
Map<String, SslBundle> serverNameSslBundles) {
protocol.setSSLEnabled(true);
if (sslBundle != null) {
addSslHostConfig(protocol, protocol.getDefaultSSLHostConfigName(), sslBundle);
}
serverNameSslBundles.forEach((serverName, bundle) -> addSslHostConfig(protocol, serverName, bundle));
}
private void addSslHostConfig(AbstractHttp11Protocol<?> protocol, String serverName, SslBundle sslBundle) {
SSLHostConfig sslHostConfig = new SSLHostConfig();
sslHostConfig.setHostName(serverName);
configureSslClientAuth(sslHostConfig);
applySslBundle(protocol, sslHostConfig, sslBundle);
protocol.addSslHostConfig(sslHostConfig, true);
}
private void applySslBundle(AbstractHttp11Protocol<?> protocol, SSLHostConfig sslHostConfig, SslBundle sslBundle) {
SslBundleKey key = sslBundle.getKey();
SslStoreBundle stores = sslBundle.getStores();
SslOptions options = sslBundle.getOptions();
sslHostConfig.setSslProtocol(sslBundle.getProtocol());
SSLHostConfigCertificate certificate = new SSLHostConfigCertificate(sslHostConfig, Type.UNDEFINED);
String keystorePassword = (stores.getKeyStorePassword() != null) ? stores.getKeyStorePassword() : "";
certificate.setCertificateKeystorePassword(keystorePassword);
if (key.getPassword() != null) {
certificate.setCertificateKeyPassword(key.getPassword());
}
if (key.getAlias() != null) {
certificate.setCertificateKeyAlias(key.getAlias());
}
sslHostConfig.addCertificate(certificate);
if (options.getCiphers() != null) {
String ciphers = StringUtils.arrayToCommaDelimitedString(options.getCiphers());
sslHostConfig.setCiphers(ciphers);
}
configureSslStores(sslHostConfig, certificate, stores);
configureEnabledProtocols(sslHostConfig, options);
}
private void configureEnabledProtocols(SSLHostConfig sslHostConfig, SslOptions options) {
if (options.getEnabledProtocols() != null) {
String enabledProtocols = StringUtils.arrayToDelimitedString(options.getEnabledProtocols(), "+");
sslHostConfig.setProtocols(enabledProtocols);
} | }
private void configureSslClientAuth(SSLHostConfig config) {
config.setCertificateVerification(ClientAuth.map(this.clientAuth, "none", "optional", "required"));
}
private void configureSslStores(SSLHostConfig sslHostConfig, SSLHostConfigCertificate certificate,
SslStoreBundle stores) {
try {
if (stores.getKeyStore() != null) {
certificate.setCertificateKeystore(stores.getKeyStore());
}
if (stores.getTrustStore() != null) {
sslHostConfig.setTrustStore(stores.getTrustStore());
}
}
catch (Exception ex) {
throw new IllegalStateException("Could not load store: " + ex.getMessage(), ex);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\SslConnectorCustomizer.java | 1 |
请完成以下Java代码 | public String getTypeName() {
return JSON;
}
public boolean isCachable() {
return true;
}
public Object getValue(ValueFields valueFields) {
Object loadedValue = null;
if (valueFields.getTextValue() != null && valueFields.getTextValue().length() > 0) {
try {
loadedValue = jsonTypeConverter.convertToValue(
objectMapper.readTree(valueFields.getTextValue()),
valueFields
);
} catch (Exception e) {
logger.error("Error reading json variable " + valueFields.getName(), e);
}
}
return loadedValue;
}
public void setValue(Object value, ValueFields valueFields) {
try {
valueFields.setTextValue(objectMapper.writeValueAsString(value));
if (value != null) {
valueFields.setTextValue2(value.getClass().getName());
}
} catch (JsonProcessingException e) { | logger.error("Error writing json variable " + valueFields.getName(), e);
}
}
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
if (
JsonNode.class.isAssignableFrom(value.getClass()) ||
(objectMapper.canSerialize(value.getClass()) && serializePOJOsInVariablesToJson)
) {
try {
return objectMapper.writeValueAsString(value).length() <= maxLength;
} catch (JsonProcessingException e) {
logger.error("Error writing json variable of type " + value.getClass(), e);
}
}
return false;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\JsonType.java | 1 |
请完成以下Java代码 | public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setRoot_AD_Table_ID (final int Root_AD_Table_ID)
{
if (Root_AD_Table_ID < 1)
set_Value (COLUMNNAME_Root_AD_Table_ID, null);
else
set_Value (COLUMNNAME_Root_AD_Table_ID, Root_AD_Table_ID);
}
@Override
public int getRoot_AD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Root_AD_Table_ID);
}
@Override
public void setRoot_Record_ID (final int Root_Record_ID)
{
if (Root_Record_ID < 1)
set_Value (COLUMNNAME_Root_Record_ID, null);
else
set_Value (COLUMNNAME_Root_Record_ID, Root_Record_ID);
}
@Override
public int getRoot_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_Root_Record_ID); | }
/**
* Severity AD_Reference_ID=541949
* Reference name: Severity
*/
public static final int SEVERITY_AD_Reference_ID=541949;
/** Notice = N */
public static final String SEVERITY_Notice = "N";
/** Error = E */
public static final String SEVERITY_Error = "E";
@Override
public void setSeverity (final java.lang.String Severity)
{
set_Value (COLUMNNAME_Severity, Severity);
}
@Override
public java.lang.String getSeverity()
{
return get_ValueAsString(COLUMNNAME_Severity);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Record_Warning.java | 1 |
请完成以下Java代码 | default Optional<String> getTableName()
{
return Optional.empty();
}
default Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
@Override
boolean equals(Object obj);
@Override
int hashCode();
LookupDataSourceFetcher getLookupDataSourceFetcher();
boolean isHighVolume();
LookupSource getLookupSourceType();
boolean hasParameters();
boolean isNumericKey();
Set<String> getDependsOnFieldNames();
default Set<String> getDependsOnTableNames()
{
return ImmutableSet.of();
}
default Class<?> getValueClass()
{
return isNumericKey() ? IntegerLookupValue.class : StringLookupValue.class;
} | default int getSearchStringMinLength()
{
return -1;
}
default Optional<Duration> getSearchStartDelay()
{
return Optional.empty();
}
default <T extends LookupDescriptor> T cast(final Class<T> ignoredLookupDescriptorClass)
{
@SuppressWarnings("unchecked")
final T thisCasted = (T)this;
return thisCasted;
}
default <T extends LookupDescriptor> T castOrNull(final Class<T> lookupDescriptorClass)
{
if (lookupDescriptorClass.isAssignableFrom(getClass()))
{
@SuppressWarnings("unchecked")
final T thisCasted = (T)this;
return thisCasted;
}
return null;
}
default TooltipType getTooltipType()
{
return TooltipType.DEFAULT;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\LookupDescriptor.java | 1 |
请完成以下Java代码 | public void onDeviceConnect(MqttPublishMessage mqttMsg) throws AdaptorException {
if (isJsonPayloadType()) {
onDeviceConnectJson(mqttMsg);
} else {
onDeviceConnectProto(mqttMsg);
}
}
public void onDeviceTelemetry(MqttPublishMessage mqttMsg) throws AdaptorException {
int msgId = getMsgId(mqttMsg);
ByteBuf payload = mqttMsg.payload();
if (isJsonPayloadType()) {
onDeviceTelemetryJson(msgId, payload);
} else {
onDeviceTelemetryProto(msgId, payload);
} | }
@Override
protected GatewayDeviceSessionContext newDeviceSessionCtx(GetOrCreateDeviceFromGatewayResponse msg) {
return new GatewayDeviceSessionContext(this, msg.getDeviceInfo(), msg.getDeviceProfile(), mqttQoSMap, transportService);
}
public void onGatewayUpdate(TransportProtos.SessionInfoProto sessionInfo, Device device, Optional<DeviceProfile> deviceProfileOpt) {
this.onDeviceUpdate(sessionInfo, device, deviceProfileOpt);
gatewayMetricsService.onDeviceUpdate(sessionInfo, gateway.getDeviceId());
}
public void onGatewayDelete(DeviceId deviceId) {
gatewayMetricsService.onDeviceDelete(deviceId);
}
} | repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\session\GatewaySessionHandler.java | 1 |
请完成以下Java代码 | public boolean isLiteralText() {
return node.isLiteralText();
}
/**
* @return <code>true</code> if this is a method invocation expression
*/
@Override
public boolean isParametersProvided() {
return node.isMethodInvocation();
}
/**
* Answer <code>true</code> if this is a deferred expression (starting with <code>#{</code>)
*/
public boolean isDeferred() {
return deferred;
}
/**
* Expressions are compared using the concept of a <em>structural id</em>:
* variable and function names are anonymized such that two expressions with
* same tree structure will also have the same structural id and vice versa.
* Two method expressions are equal if
* <ol>
* <li>their builders are equal</li>
* <li>their structural id's are equal</li>
* <li>their bindings are equal</li>
* <li>their expected types match</li>
* <li>their parameter types are equal</li>
* </ol>
*/
@Override
public boolean equals(Object obj) {
if (obj != null && obj.getClass() == getClass()) {
TreeMethodExpression other = (TreeMethodExpression) obj;
if (!builder.equals(other.builder)) {
return false; | }
if (type != other.type) {
return false;
}
if (!Arrays.equals(types, other.types)) {
return false;
}
return (getStructuralId().equals(other.getStructuralId()) && bindings.equals(other.bindings));
}
return false;
}
@Override
public int hashCode() {
return getStructuralId().hashCode();
}
@Override
public String toString() {
return "TreeMethodExpression(" + expr + ")";
}
/**
* Print the parse tree.
* @param writer
*/
public void dump(PrintWriter writer) {
NodePrinter.dump(writer, node);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
try {
node = builder.build(expr).getRoot();
} catch (ELException e) {
throw new IOException(e.getMessage());
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\TreeMethodExpression.java | 1 |
请完成以下Java代码 | public class UniqueIdGenerator {
private static final String ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static final SecureRandom random = new SecureRandom();
private int idLength = 8; // Default length
/**
* Overrides the default ID length for generated identifiers.
* @param idLength The desired length (must be positive).
*/
public void setIdLength(int idLength) {
if (idLength <= 0) {
throw new IllegalArgumentException("Length must be positive");
}
this.idLength = idLength;
}
/**
* Generates a unique alphanumeric ID using the SecureRandom character mapping approach.
* @param existingIds A set of IDs already in use to ensure uniqueness. | * @return A unique alphanumeric string.
*/
public String generateUniqueId(Set<String> existingIds) {
String newId;
do {
newId = generateRandomString(this.idLength);
} while (existingIds.contains(newId));
return newId;
}
private String generateRandomString(int length) {
return random.ints(length, 0, ALPHANUMERIC.length())
.mapToObj(ALPHANUMERIC::charAt)
.map(Object::toString)
.collect(Collectors.joining());
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-10\src\main\java\com\baeldung\algorithms\randomuniqueidentifier\UniqueIdGenerator.java | 1 |
请完成以下Java代码 | public class SubConversationImpl extends ConversationNodeImpl implements SubConversation {
protected static ChildElementCollection<ConversationNode> conversationNodeCollection;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(SubConversation.class, BPMN_ELEMENT_SUB_CONVERSATION)
.namespaceUri(BPMN20_NS)
.extendsType(ConversationNode.class)
.instanceProvider(new ModelTypeInstanceProvider<SubConversation>() {
public SubConversation newInstance(ModelTypeInstanceContext instanceContext) {
return new SubConversationImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence(); | conversationNodeCollection = sequenceBuilder.elementCollection(ConversationNode.class)
.build();
typeBuilder.build();
}
public SubConversationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Collection<ConversationNode> getConversationNodes() {
return conversationNodeCollection.get(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SubConversationImpl.java | 1 |
请完成以下Java代码 | public class FilterIterator<E> implements Iterator<E>, IteratorWrapper<E>
{
private final Iterator<E> iterator;
private final Predicate<E> predicate;
private E next;
private boolean nextSet = false;
public FilterIterator(final Iterator<E> iterator, final Predicate<E> predicate)
{
super();
if (iterator == null)
{
throw new IllegalArgumentException("iterator is null");
}
this.iterator = iterator;
this.predicate = predicate;
}
public FilterIterator(final BlindIterator<E> iterator, final Predicate<E> predicate)
{
this(new BlindIteratorWrapper<E>(iterator), predicate);
}
@Override
public boolean hasNext()
{
if (nextSet)
{
return true;
}
else
{
return setNextValid();
}
}
@Override
public E next()
{
if (!nextSet)
{
if (!setNextValid()) | {
throw new NoSuchElementException();
}
}
nextSet = false;
return next;
}
/**
* Set next valid element
*
* @return true if next valid element was found and set
*/
private final boolean setNextValid()
{
while (iterator.hasNext())
{
final E element = iterator.next();
if (predicate.test(element))
{
next = element;
nextSet = true;
return true;
}
}
return false;
}
/**
* @throws UnsupportedOperationException always
*/
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
@Override
public Iterator<E> getParentIterator()
{
return iterator;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\FilterIterator.java | 1 |
请完成以下Java代码 | public class JwtUserDto implements UserDetails {
@ApiModelProperty(value = "用户")
private final UserDto user;
@ApiModelProperty(value = "数据权限")
private final List<Long> dataScopes;
@ApiModelProperty(value = "角色权限")
private final List<AuthorityDto> authorities;
public Set<String> getRoles() {
return authorities.stream().map(AuthorityDto::getAuthority).collect(Collectors.toSet());
}
@Override
@JSONField(serialize = false)
public String getPassword() {
return user.getPassword();
}
@Override
@JSONField(serialize = false)
public String getUsername() {
return user.getUsername();
}
@JSONField(serialize = false)
@Override
public boolean isAccountNonExpired() {
return true; | }
@JSONField(serialize = false)
@Override
public boolean isAccountNonLocked() {
return true;
}
@JSONField(serialize = false)
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
@JSONField(serialize = false)
public boolean isEnabled() {
return user.getEnabled();
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\service\dto\JwtUserDto.java | 1 |
请完成以下Java代码 | public void forEach(BiConsumer<String, String> action) {
this.properties.forEach(action::accept);
}
@Override
public CharSequence getNormalForm(Iterable<? extends CharSequence> tokens) {
return PREFIX + Util.joinAsCamelCase(tokens);
}
@Override
public int getPriority() {
return -200;
}
@Override | public @Nullable String getProperty(String key) {
return this.properties.get(key);
}
@Override
public boolean containsProperty(String key) {
return this.properties.containsKey(key);
}
@Override
public Collection<String> getPropertyNames() {
return this.properties.keySet();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\SpringBootPropertySource.java | 1 |
请完成以下Java代码 | public Date getDueDate(final I_SEPA_Export_Line line)
{
// NOTE: for now, return SystemTime + 1
// return TimeUtil.addDays(line.getSEPA_Export().getPaymentDate(), 1);
// ts: unrelated: don'T add another day, because it turn our that it makes the creditors get their money one day after they expected it
final Timestamp paymentDate = line.getSEPA_Export().getPaymentDate();
if (paymentDate == null)
{
return SystemTime.asTimestamp();
}
return paymentDate;
}
@Override
public SEPACreditTransferXML exportCreditTransferXML(@NonNull final I_SEPA_Export sepaExport, @NonNull final SEPAExportContext exportContext)
{
final SEPAProtocol protocol = SEPAProtocol.ofCode(sepaExport.getSEPA_Protocol());
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final SEPAMarshaler marshaler = newSEPAMarshaler(protocol, exportContext);
try
{
marshaler.marshal(sepaExport, out);
}
catch (final RuntimeException e)
{
throw AdempiereException.wrapIfNeeded(e);
} | return SEPACreditTransferXML.builder()
.filename(FileUtil.stripIllegalCharacters(sepaExport.getDocumentNo()) + ".xml")
.contentType(MimeType.TYPE_XML)
.content(out.toByteArray())
.build();
}
private SEPAMarshaler newSEPAMarshaler(@NonNull final SEPAProtocol protocol, @NonNull final SEPAExportContext exportContext)
{
if (SEPAProtocol.CREDIT_TRANSFER_PAIN_001_001_03_CH_02.equals(protocol))
{
final BankRepository bankRepository = SpringContextHolder.instance.getBean(BankRepository.class);
return new SEPAVendorCreditTransferMarshaler_Pain_001_001_03_CH_02(bankRepository, exportContext, bankAccountService);
}
else if (SEPAProtocol.DIRECT_DEBIT_PAIN_008_003_02.equals(protocol))
{
return new SEPACustomerDirectDebitMarshaler_Pain_008_003_02(bankAccountService);
}
else
{
throw new AdempiereException("Unknown SEPA protocol: " + protocol);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\SEPADocumentBL.java | 1 |
请完成以下Java代码 | public String asValue()
{
Check.assume(Type.VALUE.equals(type),
"The type of this instance needs to be {}; this={}", Type.VALUE, this);
final Matcher valueMatcher = Type.VALUE.pattern.matcher(rawValue);
if (!valueMatcher.matches())
{
throw new AdempiereException("External identifier of Value parsing failed. External Identifier:" + rawValue);
}
return valueMatcher.group(1);
}
@NonNull
public String asGTIN()
{
Check.assume(Type.GTIN.equals(type),
"The type of this instance needs to be {}; this={}", Type.GTIN, this);
final Matcher gtinMatcher = Type.GTIN.pattern.matcher(rawValue);
if (!gtinMatcher.matches())
{
throw new AdempiereException("External identifier of Value parsing failed. External Identifier:" + rawValue);
}
return gtinMatcher.group(1);
} | @AllArgsConstructor
@Getter
public enum Type
{
METASFRESH_ID(Pattern.compile("^\\d+$")),
EXTERNAL_REFERENCE(Pattern.compile("^ext-([a-zA-Z0-9_]+)-(.+)$")),
GLN(Pattern.compile("^gln-(.+)")),
/**
* GLN with an optional additional label that can be used in case metasfresh has multiple BPartners which share the same GLN.
*/
GLN_WITH_LABEL(Pattern.compile("^glnl-([^_]+_.+)")),
GTIN(Pattern.compile("^gtin-(.+)")),
VALUE(Pattern.compile("^val-(.+)"));
private final Pattern pattern;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\ExternalIdentifier.java | 1 |
请完成以下Java代码 | protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
SequenceFlow sequenceFlow = new SequenceFlow();
BpmnXMLUtil.addXMLLocation(sequenceFlow, xtr);
sequenceFlow.setSourceRef(xtr.getAttributeValue(null, ATTRIBUTE_FLOW_SOURCE_REF));
sequenceFlow.setTargetRef(xtr.getAttributeValue(null, ATTRIBUTE_FLOW_TARGET_REF));
sequenceFlow.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME));
sequenceFlow.setSkipExpression(xtr.getAttributeValue(null, ATTRIBUTE_FLOW_SKIP_EXPRESSION));
parseChildElements(getXMLElementName(), sequenceFlow, model, xtr);
return sequenceFlow;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
SequenceFlow sequenceFlow = (SequenceFlow) element;
writeDefaultAttribute(ATTRIBUTE_FLOW_SOURCE_REF, sequenceFlow.getSourceRef(), xtw); | writeDefaultAttribute(ATTRIBUTE_FLOW_TARGET_REF, sequenceFlow.getTargetRef(), xtw);
if (StringUtils.isNotEmpty(sequenceFlow.getSkipExpression())) {
writeDefaultAttribute(ATTRIBUTE_FLOW_SKIP_EXPRESSION, sequenceFlow.getSkipExpression(), xtw);
}
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
SequenceFlow sequenceFlow = (SequenceFlow) element;
if (StringUtils.isNotEmpty(sequenceFlow.getConditionExpression())) {
xtw.writeStartElement(ELEMENT_FLOW_CONDITION);
xtw.writeAttribute(XSI_PREFIX, XSI_NAMESPACE, "type", "tFormalExpression");
xtw.writeCData(sequenceFlow.getConditionExpression());
xtw.writeEndElement();
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\SequenceFlowXMLConverter.java | 1 |
请完成以下Java代码 | public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
/**
* @return the label
*/
public String getLabel() {
return label;
}
/**
* @param label the label to set
*/
public void setLabel(String label) {
this.label = label;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) { | this.value = value;
}
public String getSlotTitle() {
return slotTitle;
}
public void setSlotTitle(String slotTitle) {
this.slotTitle = slotTitle;
}
public Integer getRuleFlag() {
return ruleFlag;
}
public void setRuleFlag(Integer ruleFlag) {
this.ruleFlag = ruleFlag;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\TreeModel.java | 1 |
请完成以下Java代码 | /* package */void collectEvent(final IDocumentFieldChangedEvent event)
{
final boolean init_isKey = false;
final boolean init_publicField = true;
final boolean init_advancedField = false;
final DocumentFieldWidgetType init_widgetType = event.getWidgetType();
fieldChangesOf(event.getFieldName(), init_isKey, init_publicField, init_advancedField, init_widgetType)
.mergeFrom(event);
}
/* package */ void collectFieldWarning(final IDocumentFieldView documentField, final DocumentFieldWarning fieldWarning)
{
fieldChangesOf(documentField).setFieldWarning(fieldWarning);
}
public static final class IncludedDetailInfo
{
private final DetailId detailId;
private boolean stale = false;
private LogicExpressionResult allowNew;
private LogicExpressionResult allowDelete;
private IncludedDetailInfo(final DetailId detailId)
{
this.detailId = detailId;
}
public DetailId getDetailId()
{
return detailId;
}
IncludedDetailInfo setStale()
{
stale = true;
return this;
}
public boolean isStale()
{
return stale;
}
public LogicExpressionResult getAllowNew()
{
return allowNew;
}
IncludedDetailInfo setAllowNew(final LogicExpressionResult allowNew)
{
this.allowNew = allowNew;
return this;
}
public LogicExpressionResult getAllowDelete()
{ | return allowDelete;
}
IncludedDetailInfo setAllowDelete(final LogicExpressionResult allowDelete)
{
this.allowDelete = allowDelete;
return this;
}
private void collectFrom(final IncludedDetailInfo from)
{
if (from.stale)
{
stale = from.stale;
}
if (from.allowNew != null)
{
allowNew = from.allowNew;
}
if (from.allowDelete != null)
{
allowDelete = from.allowDelete;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentChanges.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class OAuth2ClientConfigurations {
@Configuration(proxyBeanMethods = false)
@ConditionalOnOAuth2ClientRegistrationProperties
@EnableConfigurationProperties(OAuth2ClientProperties.class)
@ConditionalOnMissingBean(ClientRegistrationRepository.class)
static class ClientRegistrationRepositoryConfiguration {
@Bean
InMemoryClientRegistrationRepository clientRegistrationRepository(OAuth2ClientProperties properties) {
List<ClientRegistration> registrations = new ArrayList<>(
new OAuth2ClientPropertiesMapper(properties).asClientRegistrations().values());
return new InMemoryClientRegistrationRepository(registrations);
}
} | @Configuration(proxyBeanMethods = false)
@ConditionalOnBean(ClientRegistrationRepository.class)
static class OAuth2AuthorizedClientServiceConfiguration {
@Bean
@ConditionalOnMissingBean
OAuth2AuthorizedClientService authorizedClientService(
ClientRegistrationRepository clientRegistrationRepository) {
return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-client\src\main\java\org\springframework\boot\security\oauth2\client\autoconfigure\OAuth2ClientConfigurations.java | 2 |
请完成以下Java代码 | public void execute(@NonNull final Runnable command)
{
try
{
logger.debug("Going to acquire semaphore{}", semaphore.toString());
semaphore.acquire();
logger.debug("Done acquiring semaphore={}", semaphore.toString());
}
catch (final InterruptedException e)
{
logger.warn("execute - InterruptedException while acquiring semaphore=" + semaphore + " for command=" + command + ";-> return", e);
return;
}
// wrap 'command' into another runnable, so we can in the end release the semaphore.
final Runnable r = new Runnable()
{
public String toString()
{
return "runnable-wrapper-for[" + command + "]";
}
public void run()
{
try
{
logger.debug("execute - Going to invoke command.run() within delegate thread-pool");
command.run();
logger.debug("execute - Done invoking command.run() within delegate thread-pool");
} | catch (final Throwable t)
{
logger.error("execute - Caught throwable while running command=" + command + "; -> rethrow", t);
throw t;
}
finally
{
semaphore.release();
logger.debug("Released semaphore={}", semaphore);
}
}
};
try
{
delegate.execute(r); // don't expect RejectedExecutionException because delegate has a small queue that can hold runnables after semaphore-release and before they can actually start
}
catch (final RejectedExecutionException e)
{
semaphore.release();
logger.error("execute - Caught RejectedExecutionException while trying to submit task=" + r + " to delegate thread-pool=" + delegate + "; -> released semaphore=" + semaphore + " and rethrow", e);
throw e;
}
}
public boolean hasAvailablePermits()
{
return semaphore.availablePermits() > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\BlockingExecutorWrapper.java | 1 |
请完成以下Java代码 | public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public boolean isIncludeTaskLocalVariables() {
return includeTaskLocalVariables;
}
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
}
public boolean isInOrStatement() {
return inOrStatement;
}
public boolean isFinished() {
return finished;
}
public boolean isUnfinished() {
return unfinished;
}
public String getTaskName() {
return taskName;
}
public String getTaskNameLike() {
return taskNameLike;
}
public List<String> getTaskNameList() {
return taskNameList;
}
public List<String> getTaskNameListIgnoreCase() {
return taskNameListIgnoreCase;
}
public String getTaskDescription() {
return taskDescription;
}
public String getTaskDescriptionLike() {
return taskDescriptionLike;
}
public String getTaskDeleteReason() {
return taskDeleteReason;
}
public String getTaskDeleteReasonLike() {
return taskDeleteReasonLike;
}
public String getTaskAssignee() {
return taskAssignee;
}
public String getTaskAssigneeLike() {
return taskAssigneeLike;
}
public List<String> getTaskAssigneeIds() {
return taskAssigneeIds;
} | public String getTaskId() {
return taskId;
}
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
public String getTaskOwnerLike() {
return taskOwnerLike;
}
public String getTaskOwner() {
return taskOwner;
}
public String getTaskParentTaskId() {
return taskParentTaskId;
}
public Date getCreationDate() {
return creationDate;
}
public String getCandidateUser() {
return candidateUser;
}
public String getCandidateGroup() {
return candidateGroup;
}
public String getInvolvedUser() {
return involvedUser;
}
public String getProcessDefinitionKeyLikeIgnoreCase() {
return processDefinitionKeyLikeIgnoreCase;
}
public String getProcessInstanceBusinessKeyLikeIgnoreCase() {
return processInstanceBusinessKeyLikeIgnoreCase;
}
public String getTaskNameLikeIgnoreCase() {
return taskNameLikeIgnoreCase;
}
public String getTaskDescriptionLikeIgnoreCase() {
return taskDescriptionLikeIgnoreCase;
}
public String getTaskOwnerLikeIgnoreCase() {
return taskOwnerLikeIgnoreCase;
}
public String getTaskAssigneeLikeIgnoreCase() {
return taskAssigneeLikeIgnoreCase;
}
public String getLocale() {
return locale;
}
public List<HistoricTaskInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\HistoricTaskInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected final <T extends AbstractEntity> Map<String, T> mapByUuid(final List<T> list)
{
if (list.isEmpty())
{
return new HashMap<>();
}
final Map<String, T> map = new HashMap<>(list.size());
for (final T entry : list)
{
final String uuid = entry.getUuid();
final T entryOld = map.put(uuid, entry);
if (entryOld != null)
{
logger.warn("Duplicate UUID {} in {}.\n Discarding old entry: {}", uuid, list, entryOld);
// throw new IllegalArgumentException("Duplicate UUID " + uuid + " in " + list);
}
}
return map;
}
protected static final <T extends AbstractTranslationEntity<?>> Map<String, T> mapByLanguage(final List<T> list)
{
if (list.isEmpty())
{
return new HashMap<>();
}
final Map<String, T> map = new HashMap<>(list.size());
for (final T e : list)
{
map.put(e.getLanguage(), e);
}
return map;
}
/**
* Throws an {@link IllegalDeleteRequestException} if the given <code>syncModel</code> has <code>isDeleted</code>.
*/
protected void assertNotDeleteRequest(final IConfirmableDTO syncModel, final String reason)
{
if (syncModel.isDeleted())
{
throw new IllegalDeleteRequestException("Setting Deleted flag to " + syncModel + " is not allowed while: " + reason);
}
} | protected <T extends IConfirmableDTO> T assertNotDeleteRequest_WarnAndFix(@NonNull final T syncModel, final String reason)
{
if (syncModel.isDeleted())
{
logger.warn("Setting Deleted flag to " + syncModel + " is not allowed while: " + reason + ". Unsetting the flag and going forward.");
return (T)syncModel.withNotDeleted();
}
return syncModel;
}
private static class IllegalDeleteRequestException extends RuntimeException
{
private static final long serialVersionUID = 8217968386550762496L;
IllegalDeleteRequestException(final String message)
{
super(message);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\AbstractSyncImportService.java | 2 |
请完成以下Java代码 | public long sumThenReset() {
Cell[] as = cells; Cell a;
long sum = base;
base = 0L;
if (as != null) {
for (int i = 0; i < as.length; ++i) {
if ((a = as[i]) != null) {
sum += a.value;
a.value = 0L;
}
}
}
return sum;
}
/**
* Returns the String representation of the {@link #sum}.
* @return the String representation of the {@link #sum}
*/
public String toString() {
return Long.toString(sum());
}
/**
* Equivalent to {@link #sum}.
*
* @return the sum
*/
public long longValue() {
return sum();
}
/**
* Returns the {@link #sum} as an {@code int} after a narrowing
* primitive conversion.
*/
public int intValue() {
return (int)sum();
}
/**
* Returns the {@link #sum} as a {@code float}
* after a widening primitive conversion.
*/
public float floatValue() {
return (float)sum();
}
/**
* Returns the {@link #sum} as a {@code double} after a widening
* primitive conversion.
*/
public double doubleValue() {
return (double)sum();
}
/**
* Serialization proxy, used to avoid reference to the non-public
* Striped64 superclass in serialized forms.
* @serial include
*/
private static class SerializationProxy implements Serializable {
private static final long serialVersionUID = 7249069246863182397L;
/**
* The current value returned by sum().
* @serial | */
private final long value;
SerializationProxy(LongAdder a) {
value = a.sum();
}
/**
* Return a {@code LongAdder} object with initial state
* held by this proxy.
*
* @return a {@code LongAdder} object with initial state
* held by this proxy.
*/
private Object readResolve() {
LongAdder a = new LongAdder();
a.base = value;
return a;
}
}
/**
* Returns a
* <a href="../../../../serialized-form.html#java.util.concurrent.atomic.LongAdder.SerializationProxy">
* SerializationProxy</a>
* representing the state of this instance.
*
* @return a {@link SerializationProxy}
* representing the state of this instance
*/
private Object writeReplace() {
return new SerializationProxy(this);
}
/**
* @param s the stream
* @throws java.io.InvalidObjectException always
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.InvalidObjectException {
throw new java.io.InvalidObjectException("Proxy required");
}
} | repos\tutorials-master\jmh\src\main\java\com\baeldung\falsesharing\LongAdder.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final EventDescriptor eventDescriptor = EventDescriptor.ofClientAndOrg(Env.getClientAndOrgId());
queryBL.createQueryBuilder(I_MD_Candidate.class)
.addOnlyActiveRecordsFilter()
.filter(getProcessInfo().getQueryFilterOrElseFalse())
.create()
.iterateAndStream()
.filter(hasSupportedBusinessCase)
.filter(statusIsDocPlanned)
.map(r -> MaterialDispoGroupId.ofInt(r.getMD_Candidate_GroupId()))
.distinct()
.peek(groupId -> addLog("Calling {}.requestOrder() for groupId={}", RequestMaterialOrderService.class.getSimpleName(), groupId))
.forEach(groupId -> service.requestMaterialOrderForCandidates(groupId, eventDescriptor));
return MSG_OK;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{ | if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
final boolean atLeastOneProperCandidateSelected = context.streamSelectedModels(I_MD_Candidate.class)
.anyMatch(selectedRecord -> hasSupportedBusinessCase.test(selectedRecord)
&& statusIsDocPlanned.test(selectedRecord));
if (!atLeastOneProperCandidateSelected)
{
final ITranslatableString translatable = msgBL.getTranslatableMsgText(MSG_MISSING_PRODUCTION_OR_DISTRIBUTRION_RECORDS);
return ProcessPreconditionsResolution.reject(translatable);
}
return ProcessPreconditionsResolution.accept();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\process\MD_Candidate_Request_MaterialDocument.java | 1 |
请完成以下Java代码 | public CRPException setPP_Order(I_PP_Order order)
{
this.order = order;
resetMessageBuilt();
return this;
}
public CRPException setOrderActivity(PPOrderRoutingActivity orderActivity)
{
this.orderActivity = orderActivity;
resetMessageBuilt();
return this;
}
public CRPException setS_Resource(I_S_Resource resource)
{
this.resource = resource;
resetMessageBuilt();
return this;
}
@Override
protected ITranslatableString buildMessage()
{
String msg = super.getMessage();
StringBuffer sb = new StringBuffer(msg);
//
if (this.order != null)
{ | final String info;
if (order instanceof IDocument)
{
info = ((IDocument)order).getSummary();
}
else
{
info = "" + order.getDocumentNo() + "/" + order.getDatePromised();
}
sb.append(" @PP_Order_ID@:").append(info);
}
if (this.orderActivity != null)
{
sb.append(" @PP_Order_Node_ID@:").append(orderActivity);
}
if (this.resource != null)
{
sb.append(" @S_Resource_ID@:").append(resource.getValue()).append("_").append(resource.getName());
}
//
return TranslatableStrings.parse(sb.toString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\exceptions\CRPException.java | 1 |
请完成以下Java代码 | public class ProcessLoggerExporterMonitor implements IExporterMonitor
{
private static final Logger logger = LogManager.getLogger(ProcessLoggerExporterMonitor.class);
private final AdProcessId adProcessId;
private final Object params;
private final Class<?> paramsInterfaceClass;
private I_AD_PInstance pinstance;
private IClientUIInstance clientUIInstance;
/**
*
* @param ctx
* @param adProcessId which process shall be used when creating the {@link I_AD_PInstance} record
* @param params object which contains the export parameters
* @param paramsInterfaceClass interface class to be used when we are introspecting the export parameters
*/
public <T> ProcessLoggerExporterMonitor(
@NonNull final AdProcessId adProcessId,
@NonNull final T params,
@NonNull final Class<T> paramsInterfaceClass)
{
this.adProcessId = adProcessId;
this.params = params;
this.paramsInterfaceClass = paramsInterfaceClass;
}
@Override
public void exportStarted(IExporter exporter)
{
pinstance = createPInstance();
}
@Override
public void exportFinished(IExporter exporter)
{
final Throwable error = exporter.getError();
if (error != null)
{
// Log the error to console. This is useful if the exporter is running asynchronous and the threads executor service is not logging the exception
logger.error(error.getLocalizedMessage(), error);
if (clientUIInstance != null)
{
clientUIInstance.error(Env.WINDOW_MAIN, "Error", error.getLocalizedMessage());
}
}
if (pinstance != null)
{
pinstance.setResult(exporter.getExportedRowCount());
pinstance.setIsProcessing(false);
if (error != null)
{ | pinstance.setErrorMsg(error.getLocalizedMessage());
}
InterfaceWrapperHelper.save(pinstance);
}
}
private I_AD_PInstance createPInstance()
{
final I_AD_PInstance pinstance = Services.get(IADPInstanceDAO.class).createAD_PInstance(adProcessId);
pinstance.setIsProcessing(true);
InterfaceWrapperHelper.save(pinstance);
final BeanInfo beanInfo;
try
{
beanInfo = Introspector.getBeanInfo(paramsInterfaceClass);
}
catch (IntrospectionException e)
{
throw new AdempiereException(e.getLocalizedMessage(), e);
}
final List<ProcessInfoParameter> piParams = new ArrayList<>();
for (final PropertyDescriptor pd : beanInfo.getPropertyDescriptors())
{
final Object value;
try
{
value = pd.getReadMethod().invoke(params);
}
catch (Exception e)
{
logger.info(e.getLocalizedMessage(), e);
continue;
}
if (value == null)
{
continue;
}
piParams.add(ProcessInfoParameter.ofValueObject(pd.getName(), value));
}
Services.get(IADPInstanceDAO.class).saveParameterToDB(PInstanceId.ofRepoId(pinstance.getAD_PInstance_ID()), piParams);
return pinstance;
}
public void setClientUIInstance(IClientUIInstance clientUIInstance)
{
this.clientUIInstance = clientUIInstance;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\ProcessLoggerExporterMonitor.java | 1 |
请完成以下Java代码 | private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException {
SocketChannel client = (SocketChannel) key.channel();
int r = client.read(buffer);
if (r == -1 || new String(buffer.array()).trim()
.equals(POISON_PILL)) {
client.close();
System.out.println("Not accepting client messages anymore");
} else {
buffer.flip();
client.write(buffer);
buffer.clear();
}
}
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException { | SocketChannel client = serverSocket.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = EchoServer.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
} | repos\tutorials-master\core-java-modules\core-java-nio\src\main\java\com\baeldung\selector\EchoServer.java | 1 |
请完成以下Java代码 | 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 class JsonLegacyQueryOrderingPropertyConverter {
public static final String ORDER_BY_DELIMITER = ",";
public static JsonLegacyQueryOrderingPropertyConverter INSTANCE =
new JsonLegacyQueryOrderingPropertyConverter();
public List<QueryOrderingProperty> fromOrderByString(String orderByString) {
List<QueryOrderingProperty> properties = new ArrayList<QueryOrderingProperty>();
String[] orderByClauses = orderByString.split(ORDER_BY_DELIMITER);
for (String orderByClause : orderByClauses) {
orderByClause = orderByClause.trim();
String[] clauseParts = orderByClause.split(" ");
if (clauseParts.length == 0) {
continue;
} else if (clauseParts.length > 2) {
throw new ProcessEngineException("Invalid order by clause: " + orderByClause);
}
String function = null;
String propertyPart = clauseParts[0];
int functionArgumentBegin = propertyPart.indexOf("(");
if (functionArgumentBegin >= 0) {
function = propertyPart.substring(0, functionArgumentBegin);
int functionArgumentEnd = propertyPart.indexOf(")");
propertyPart = propertyPart.substring(functionArgumentBegin + 1, functionArgumentEnd);
} | String[] propertyParts = propertyPart.split("\\.");
String property = null;
if (propertyParts.length == 1) {
property = propertyParts[0];
} else if (propertyParts.length == 2) {
property = propertyParts[1];
} else {
throw new ProcessEngineException("Invalid order by property part: " + clauseParts[0]);
}
QueryProperty queryProperty = new QueryPropertyImpl(property, function);
Direction direction = null;
if (clauseParts.length == 2) {
String directionPart = clauseParts[1];
direction = Direction.findByName(directionPart);
}
QueryOrderingProperty orderingProperty = new QueryOrderingProperty(null, queryProperty);
orderingProperty.setDirection(direction);
properties.add(orderingProperty);
}
return properties;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\json\JsonLegacyQueryOrderingPropertyConverter.java | 1 |
请完成以下Java代码 | private void showErrorMessage(String message) {
HTMLDivElement errorDiv = (HTMLDivElement) DomGlobal.document.createElement("div");
errorDiv.textContent = message;
errorDiv.classList.add("errorMessage");
addTaskButton.parentNode.insertBefore(errorDiv, taskList);
DomGlobal.setTimeout((e) -> errorDiv.remove(), 5000);
}
/**
* Try to read the existing 'uuid' from the URL (e.g. ?uuid=12345).
* Return null if not present.
*/
private static String getUUIDFromURL() {
URLSearchParams params = new URLSearchParams(DomGlobal.window.location.search);
if (params.has("uuid")) {
return params.get("uuid");
}
return null;
}
/**
* Once we know the server-assigned uuid, we can rewrite the URL to include it.
*/ | private void rewriteURLwithUUID(String newUUID) {
String url = DomGlobal.window.location.href;
URLSearchParams params = new URLSearchParams(DomGlobal.window.location.search);
params.set("uuid", newUUID);
// If original had ?... we replace; otherwise append ?uuid=...
String baseUrl = url.contains("?") ? url.substring(0, url.indexOf("?")) : url;
String newUrl = baseUrl + "?" + params.toString();
DomGlobal.window.history.replaceState(null, "", newUrl);
}
@JsMethod(namespace = JsPackage.GLOBAL, name = "JSON.stringify")
private static native String jsonStringify(Object obj);
} | repos\tutorials-master\j2cl\src\main\java\com\baeldung\j2cl\taskmanager\MyJ2CLApp.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DummyEdqsService implements EdqsService {
@Override
public void onUpdate(TenantId tenantId, EntityId entityId, Object entity) {}
@Override
public void onUpdate(TenantId tenantId, ObjectType objectType, EdqsObject object) {}
@Override
public void onDelete(TenantId tenantId, EntityId entityId) {}
@Override
public void onDelete(TenantId tenantId, ObjectType objectType, EdqsObject object) {}
@Override | public void processSystemRequest(ToCoreEdqsRequest request) {}
@Override
public void processSystemMsg(ToCoreEdqsMsg request) {}
@Override
public boolean isApiEnabled() {
return getState().isApiEnabled();
}
@Override
public EdqsState getState() {
return new EdqsState();
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\query\DummyEdqsService.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.