instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class VolatileVarNotThreadSafe {
private static final Logger LOG = LoggerFactory.getLogger(VolatileVarNotThreadSafe.class);
private static volatile int count = 0;
private static final int MAX_LIMIT = 1000;
public static void increment() {
count++;
}
public static int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int index=0; index<MAX_LIMIT; index++) {
increment();
}
}
});
|
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int index=0; index<MAX_LIMIT; index++) {
increment();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
LOG.info("value of counter variable: "+count);
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-4\src\main\java\com\baeldung\volatilekeywordthreadsafety\VolatileVarNotThreadSafe.java
| 1
|
请完成以下Java代码
|
public class ZipCodeResource {
private ZipCodeRepo zipRepo;
public ZipCodeResource(ZipCodeRepo zipRepo) {
this.zipRepo = zipRepo;
}
@GET
@Path("/{zipcode}")
public Uni<ZipCode> findById(@PathParam("zipcode") String zipcode) {
return getById(zipcode);
}
@GET
@Path("/by_city")
public Multi<ZipCode> postZipCode(@QueryParam("city") String city) {
return zipRepo.findByCity(city);
}
@POST
public Uni<ZipCode> create(ZipCode zipCode) {
return getById(zipCode.getZip())
|
.onItem()
.ifNull()
.switchTo(createZipCode(zipCode))
.onFailure(PersistenceException.class)
.recoverWithUni(() -> getById(zipCode.getZip()));
}
private Uni<ZipCode> getById(String zipCode) {
return zipRepo.findById(zipCode);
}
private Uni<ZipCode> createZipCode(ZipCode zipCode) {
return Uni.createFrom().deferred(() -> zipRepo.save(zipCode));
}
}
|
repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\quarkus-project\src\main\java\com\baeldung\quarkus_project\ZipCodeResource.java
| 1
|
请完成以下Java代码
|
public String getReferenceNumber() {
return referenceNumber;
}
/**
* Sets the value of the referenceNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferenceNumber(String value) {
this.referenceNumber = value;
}
/**
* Gets the value of the codingLine1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCodingLine1() {
return codingLine1;
}
/**
* Sets the value of the codingLine1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodingLine1(String value) {
|
this.codingLine1 = value;
}
/**
* Gets the value of the codingLine2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCodingLine2() {
return codingLine2;
}
/**
* Sets the value of the codingLine2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodingLine2(String value) {
this.codingLine2 = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EsrRedType.java
| 1
|
请完成以下Java代码
|
public void createPackingMaterialMovementLines(final I_M_Movement movement)
{
final IHUMovementBL huMovementBL = Services.get(IHUMovementBL.class);
huMovementBL.createPackingMaterialMovementLines(movement);
}
@DocValidate(timings = ModelValidator.TIMING_BEFORE_REACTIVATE)
public void deletePackingMaterialMovementLines(final I_M_Movement movement)
{
final IMovementDAO movementDAO = Services.get(IMovementDAO.class);
for (final I_M_MovementLine movementLine : movementDAO.retrieveLines(movement, I_M_MovementLine.class))
{
if (!movementLine.isPackagingMaterial())
{
continue;
}
InterfaceWrapperHelper.delete(movementLine);
}
}
/**
* Fetch all HUs which are assigned to linked Receipt Line and assign them to given movement line.
*
* @return list of HUs which are now currently assigned given <code>movementLine</code>
*/
private void assignHUsFromReceiptLine(final I_M_MovementLine movementLine)
{
//
// Particular case: movement generated from Receipt Line (to move Qty to destination warehouse)
final I_M_InOutLine receiptLine = InterfaceWrapperHelper.create(movementLine.getM_InOutLine(), I_M_InOutLine.class);
if (receiptLine == null || receiptLine.getM_InOutLine_ID() <= 0)
{
return;
}
// Don't move HUs for InDispute receipt lines
if (receiptLine.isInDispute())
{
return;
}
//
|
// Fetch HUs which are currently assigned to Receipt Line
final List<I_M_HU> hus = Services.get(IHUAssignmentDAO.class).retrieveTopLevelHUsForModel(receiptLine);
if (hus.isEmpty())
{
return;
}
//
// Assign them to movement line
Services.get(IHUMovementBL.class).setAssignedHandlingUnits(movementLine, hus);
}
@DocValidate(timings = ModelValidator.TIMING_BEFORE_COMPLETE)
public void moveHandlingUnits(final I_M_Movement movement)
{
final boolean doReversal = false;
huMovementBL.moveHandlingUnits(movement, doReversal);
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_REVERSECORRECT, ModelValidator.TIMING_BEFORE_REVERSEACCRUAL, ModelValidator.TIMING_BEFORE_VOID, ModelValidator.TIMING_BEFORE_REACTIVATE })
public void unmoveHandlingUnits(final I_M_Movement movement)
{
final boolean doReversal = true;
huMovementBL.moveHandlingUnits(movement, doReversal);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_Movement.java
| 1
|
请完成以下Java代码
|
public void addMouseListener (MouseListener l)
{
m_textArea.addMouseListener(l);
}
/**
* Add Text Key Listener
* @param l
*/
@Override
public void addKeyListener (KeyListener l)
{
m_textArea.addKeyListener(l);
}
/**
* Add Text Input Method Listener
* @param l
*/
@Override
public void addInputMethodListener (InputMethodListener l)
{
m_textArea.addInputMethodListener(l);
}
/**
* Get text Input Method Requests
* @return requests
*/
@Override
public InputMethodRequests getInputMethodRequests()
{
return m_textArea.getInputMethodRequests();
}
/**
* Set Text Input Verifier
|
* @param l
*/
@Override
public void setInputVerifier (InputVerifier l)
{
m_textArea.setInputVerifier(l);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
} // CTextArea
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextArea.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Boolean getIncludeEnded() {
return includeEnded;
}
public void setIncludeEnded(Boolean includeEnded) {
this.includeEnded = includeEnded;
}
public Boolean getIncludeLocalVariables() {
return includeLocalVariables;
}
public void setIncludeLocalVariables(boolean includeLocalVariables) {
this.includeLocalVariables = includeLocalVariables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
|
this.tenantId = tenantId;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getCaseInstanceIds() {
return caseInstanceIds;
}
public void setCaseInstanceIds(Set<String> caseInstanceIds) {
this.caseInstanceIds = caseInstanceIds;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceQueryRequest.java
| 2
|
请完成以下Java代码
|
private Optional<Environment> asEnvironment(@Nullable Object target) {
Environment environment = target instanceof Environment ? (Environment) target
: target instanceof EnvironmentCapable ? ((EnvironmentCapable) target).getEnvironment()
: null;
return Optional.ofNullable(environment);
}
/**
* @inheritDoc
*/
@Override
public boolean canRead(EvaluationContext context, @Nullable Object target, String name) {
return asEnvironment(target)
.filter(environment -> environment.containsProperty(name))
.isPresent();
}
/**
* @inheritDoc
*/
@Override
public TypedValue read(EvaluationContext context, @Nullable Object target, String name) {
String value = asEnvironment(target)
.map(environment -> environment.getProperty(name))
.orElse(null);
|
return new TypedValue(value);
}
/**
* @inheritDoc
* @return {@literal false}.
*/
@Override
public boolean canWrite(EvaluationContext context, @Nullable Object target, String name) {
return false;
}
/**
* @inheritDoc
*/
@Override
public void write(EvaluationContext context, @Nullable Object target, String name, @Nullable Object newValue) { }
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\expression\SmartEnvironmentAccessor.java
| 1
|
请完成以下Java代码
|
public class DelegatingByTopicSerializer extends DelegatingByTopicSerialization<Serializer<?>>
implements Serializer<Object> {
/**
* Construct an instance that will be configured in {@link #configure(Map, boolean)}
* with producer properties {@link #VALUE_SERIALIZATION_TOPIC_CONFIG} and
* {@link #KEY_SERIALIZATION_TOPIC_CONFIG}.
*/
public DelegatingByTopicSerializer() {
}
/**
* Construct an instance with the supplied mapping of topic patterns to delegate
* serializers.
* @param delegates the map of delegates.
* @param defaultDelegate the default to use when no topic name match.
*/
public DelegatingByTopicSerializer(Map<Pattern, Serializer<?>> delegates, Serializer<?> defaultDelegate) {
super(delegates, defaultDelegate);
}
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
super.configure(configs, isKey);
}
@Override
protected Serializer<?> configureDelegate(Map<String, ?> configs, boolean isKey, Serializer<?> delegate) {
delegate.configure(configs, isKey);
return delegate;
}
@Override
protected boolean isInstance(Object instance) {
return instance instanceof Serializer;
|
}
@Override
public byte[] serialize(String topic, Object data) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"unchecked", "NullAway"}) // Dataflow analysis limitation
@Override
public byte[] serialize(String topic, Headers headers, Object data) {
if (data == null) {
return null;
}
return ((Serializer<Object>) findDelegate(topic)).serialize(topic, headers, data);
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DelegatingByTopicSerializer.java
| 1
|
请完成以下Java代码
|
protected @NonNull Environment getEnvironment() {
return this.environment;
}
/**
* Gets the {@link String key} (property) of this {@code Map.Entry}.
*
* @return the {@link String key} (property) of this {@code Map.Entry}.
*/
@Override
public @NonNull String getKey() {
return this.key;
}
/**
* Gets the {@link String value} mapped to the {@link #getKey() key} (property) in this {@code Map.Entry}
* ({@link Environment}).
*
* @return the {@link String value} mapped to the {@link #getKey() key} (property) in this {@code Map.Entry}
* ({@link Environment}).
|
* @see org.springframework.core.env.Environment#getProperty(String)
* @see #getEnvironment()
* @see #getKey()
*/
@Override
public @Nullable String getValue() {
return getEnvironment().getProperty(getKey());
}
/**
* @inheritDoc
* @throws UnsupportedOperationException
*/
@Override
public String setValue(String value) {
throw newUnsupportedOperationException("Setting the value of Environment property [%s] is not supported",
getKey());
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\EnvironmentMapAdapter.java
| 1
|
请完成以下Java代码
|
public class Book extends Item {
private String ISBN;
private Date published;
private BigDecimal pages;
private String binding;
public Book() {
}
public Book(String title, Author author) {
super(title, author);
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
public Date getPublished() {
return published;
}
public void setPublished(Date published) {
this.published = published;
}
public BigDecimal getPages() {
return pages;
}
|
public void setPages(BigDecimal pages) {
this.pages = pages;
}
@JsonProperty("binding")
public String coverBinding() {
return binding;
}
@JsonProperty("binding")
public void configureBinding(String binding) {
this.binding = binding;
}
}
|
repos\tutorials-master\video-tutorials\jackson-annotations-video\src\main\java\com\baeldung\jacksonannotation\general\jsonproperty\Book.java
| 1
|
请完成以下Java代码
|
public void setMarketingPlatformGatewayId (java.lang.String MarketingPlatformGatewayId)
{
set_Value (COLUMNNAME_MarketingPlatformGatewayId, MarketingPlatformGatewayId);
}
/** Get Marketing Platform GatewayId.
@return Marketing Platform GatewayId */
@Override
public java.lang.String getMarketingPlatformGatewayId ()
{
return (java.lang.String)get_Value(COLUMNNAME_MarketingPlatformGatewayId);
}
/** Set MKTG_Platform.
@param MKTG_Platform_ID MKTG_Platform */
@Override
public void setMKTG_Platform_ID (int MKTG_Platform_ID)
{
if (MKTG_Platform_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID));
}
/** Get MKTG_Platform.
@return MKTG_Platform */
@Override
|
public int getMKTG_Platform_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Platform.java
| 1
|
请完成以下Java代码
|
public void onError(Throwable t) {
logger.warn("error:{}", t.getMessage());
}
};
}
@Override
public StreamObserver<Stock> bidirectionalStreamingGetListsStockQuotes(final StreamObserver<StockQuote> responseObserver) {
return new StreamObserver<Stock>() {
@Override
public void onNext(Stock request) {
for (int i = 1; i <= 5; i++) {
StockQuote stockQuote = StockQuote.newBuilder()
.setPrice(fetchStockPriceBid(request))
.setOfferNumber(i)
.setDescription("Price for stock:" + request.getTickerSymbol())
.build();
responseObserver.onNext(stockQuote);
}
}
@Override
public void onCompleted() {
responseObserver.onCompleted();
}
|
@Override
public void onError(Throwable t) {
logger.warn("error:{}", t.getMessage());
}
};
}
}
private static double fetchStockPriceBid(Stock stock) {
return stock.getTickerSymbol()
.length()
+ ThreadLocalRandom.current()
.nextDouble(-0.1d, 0.1d);
}
}
|
repos\tutorials-master\grpc\src\main\java\com\baeldung\grpc\streaming\StockServer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setRepairServicePerformed_Product_ID (final int RepairServicePerformed_Product_ID)
{
if (RepairServicePerformed_Product_ID < 1)
set_Value (COLUMNNAME_RepairServicePerformed_Product_ID, null);
else
set_Value (COLUMNNAME_RepairServicePerformed_Product_ID, RepairServicePerformed_Product_ID);
}
@Override
public int getRepairServicePerformed_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_RepairServicePerformed_Product_ID);
}
@Override
public void setRepair_VHU_ID (final int Repair_VHU_ID)
{
if (Repair_VHU_ID < 1)
set_Value (COLUMNNAME_Repair_VHU_ID, null);
else
set_Value (COLUMNNAME_Repair_VHU_ID, Repair_VHU_ID);
}
@Override
public int getRepair_VHU_ID()
{
return get_ValueAsInt(COLUMNNAME_Repair_VHU_ID);
}
/**
* Status AD_Reference_ID=541245
* Reference name: C_Project_Repair_Task_Status
*/
public static final int STATUS_AD_Reference_ID=541245;
/** Not Started = NS */
public static final String STATUS_NotStarted = "NS";
/** In Progress = IP */
public static final String STATUS_InProgress = "IP";
/** Completed = CO */
|
public static final String STATUS_Completed = "CO";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
/**
* Type AD_Reference_ID=541243
* Reference name: C_Project_Repair_Task_Type
*/
public static final int TYPE_AD_Reference_ID=541243;
/** ServiceRepairOrder = W */
public static final String TYPE_ServiceRepairOrder = "W";
/** SpareParts = P */
public static final String TYPE_SpareParts = "P";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Task.java
| 2
|
请完成以下Java代码
|
public class CamundaConnectorImpl extends BpmnModelElementInstanceImpl implements CamundaConnector {
protected static ChildElement<CamundaConnectorId> camundaConnectorIdChild;
protected static ChildElement<CamundaInputOutput> camundaInputOutputChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaConnector.class, CAMUNDA_ELEMENT_CONNECTOR)
.namespaceUri(CAMUNDA_NS)
.instanceProvider(new ModelTypeInstanceProvider<CamundaConnector>() {
public CamundaConnector newInstance(ModelTypeInstanceContext instanceContext) {
return new CamundaConnectorImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
camundaConnectorIdChild = sequenceBuilder.element(CamundaConnectorId.class)
.required()
.build();
camundaInputOutputChild = sequenceBuilder.element(CamundaInputOutput.class)
.build();
typeBuilder.build();
}
public CamundaConnectorImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public CamundaConnectorId getCamundaConnectorId() {
return camundaConnectorIdChild.getChild(this);
|
}
public void setCamundaConnectorId(CamundaConnectorId camundaConnectorId) {
camundaConnectorIdChild.setChild(this, camundaConnectorId);
}
public CamundaInputOutput getCamundaInputOutput() {
return camundaInputOutputChild.getChild(this);
}
public void setCamundaInputOutput(CamundaInputOutput camundaInputOutput) {
camundaInputOutputChild.setChild(this, camundaInputOutput);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaConnectorImpl.java
| 1
|
请完成以下Java代码
|
public void afterEach(ExtensionContext context) {
BrokerRunningSupport brokerRunning = BROKER_RUNNING_HOLDER.get();
if (brokerRunning != null && brokerRunning.isPurgeAfterEach()) {
brokerRunning.purgeTestQueues();
}
}
@Override
public void afterAll(ExtensionContext context) {
BROKER_RUNNING_HOLDER.remove();
Store store = getStore(context);
BrokerRunningSupport brokerRunning = store.remove(BROKER_RUNNING_BEAN, BrokerRunningSupport.class);
if (brokerRunning != null) {
brokerRunning.removeTestQueues();
}
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
Class<?> type = parameterContext.getParameter().getType();
return type.equals(ConnectionFactory.class) || type.equals(BrokerRunningSupport.class);
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context)
throws ParameterResolutionException {
// in parent for method injection, Composite key causes a store miss
BrokerRunningSupport brokerRunning = getParentStore(context).get(BROKER_RUNNING_BEAN,
BrokerRunningSupport.class) == null
? getStore(context).get(BROKER_RUNNING_BEAN, BrokerRunningSupport.class)
: getParentStore(context).get(BROKER_RUNNING_BEAN, BrokerRunningSupport.class);
Assert.state(brokerRunning != null, "Could not find brokerRunning instance");
Class<?> type = parameterContext.getParameter().getType();
return type.equals(ConnectionFactory.class) ? brokerRunning.getConnectionFactory()
|
: brokerRunning;
}
private Store getStore(ExtensionContext context) {
return context.getStore(Namespace.create(getClass(), context));
}
private Store getParentStore(ExtensionContext context) {
ExtensionContext parent = context.getParent().get();
return parent.getStore(Namespace.create(getClass(), parent));
}
public static BrokerRunningSupport getBrokerRunning() {
return BROKER_RUNNING_HOLDER.get();
}
}
|
repos\spring-amqp-main\spring-rabbit-junit\src\main\java\org\springframework\amqp\rabbit\junit\RabbitAvailableCondition.java
| 1
|
请完成以下Java代码
|
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public String getDeploymentMode() {
return deploymentMode;
}
public void setDeploymentMode(String deploymentMode) {
this.deploymentMode = deploymentMode;
}
/**
* Gets the {@link AutoDeploymentStrategy} for the provided mode. This method may be overridden to implement custom deployment strategies if required, but implementors should take care not to return
* <code>null</code>.
*
|
* @param mode
* the mode to get the strategy for
* @return the deployment strategy to use for the mode. Never <code>null</code>
*/
protected AutoDeploymentStrategy getAutoDeploymentStrategy(final String mode) {
AutoDeploymentStrategy result = defaultAutoDeploymentStrategy;
for (final AutoDeploymentStrategy strategy : deploymentStrategies) {
if (strategy.handlesMode(mode)) {
result = strategy;
break;
}
}
return result;
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringProcessEngineConfiguration.java
| 1
|
请完成以下Java代码
|
public class RolePermissionsNotFoundException extends AdempiereException
{
private static final String MSG = "RolePermissionsNotFoundException";
/**
*
*/
private static final long serialVersionUID = -5635853326303323078L;
public RolePermissionsNotFoundException(final String additionalInfo)
{
this(buildMsg(additionalInfo), (Throwable)null);
}
public RolePermissionsNotFoundException(final String additionalInfo, Throwable cause)
{
super(buildMsg(additionalInfo), cause);
|
}
private static String buildMsg(String additionalInfo)
{
final StringBuilder sb = new StringBuilder()
.append("@").append(MSG).append("@");
if (!Check.isEmpty(additionalInfo, true))
{
sb.append(": ").append(additionalInfo);
}
return sb.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\RolePermissionsNotFoundException.java
| 1
|
请完成以下Java代码
|
private static ImmutableList<LocalToRemoteSyncResult> createErrorResults(
@NonNull final ImmutableListMultimap<String, ContactPerson> email2contactPersons,
@NonNull final InvalidEmail invalidEmailInfo)
{
final String errorMsg = invalidEmailInfo.getErrorMessage();
final String invalidAddress = invalidEmailInfo.getEmail();
return email2contactPersons
.get(invalidAddress)
.stream()
.map(p -> LocalToRemoteSyncResult.error(p, errorMsg))
.collect(ImmutableList.toImmutableList());
}
private static Optional<InvalidEmail> createInvalidEmailInfo(final String singleResult)
{
final Pattern regExpInvalidAddress = Pattern.compile(".*invalid address *'(.*)'.*");
final Pattern regExpDuplicateAddress = Pattern.compile(".*duplicate address *'(.*).*'");
final Optional<InvalidEmail> invalidEmailIfno = createInvalidEmailInfo(regExpInvalidAddress, singleResult);
if (invalidEmailIfno.isPresent())
{
return invalidEmailIfno;
}
return createInvalidEmailInfo(regExpDuplicateAddress, singleResult);
}
private static Optional<InvalidEmail> createInvalidEmailInfo(final Pattern regExpInvalidAddress, final String reponseString)
{
final Matcher invalidAddressMatcher = regExpInvalidAddress.matcher(reponseString);
if (invalidAddressMatcher.matches())
{
final String errorMsg = invalidAddressMatcher.group();
final String invalidAddress = invalidAddressMatcher.group(1);
return Optional.of(new InvalidEmail(invalidAddress, errorMsg));
}
return Optional.empty();
}
@Value
private static class InvalidEmail
{
String email;
String errorMessage;
}
private LocalToRemoteSyncResult createOrUpdateGroup(@NonNull final Campaign campaign)
{
if (Check.isEmpty(campaign.getRemoteId()))
{
final Group createdGroup = createGroup(campaign);
|
final Campaign campaignWithRemoteId = campaign
.toBuilder()
.remoteId(Integer.toString(createdGroup.getId()))
.build();
return LocalToRemoteSyncResult.inserted(campaignWithRemoteId);
}
updateGroup(campaign);
return LocalToRemoteSyncResult.updated(campaign);
}
@Override
public void sendEmailActivationForm(
@NonNull final String formId,
@NonNull final String email)
{
final String url = "/forms/" + formId + "/send/activate";
final SendEmailActivationFormRequest body = SendEmailActivationFormRequest.builder()
.email(email)
.doidata(SendEmailActivationFormRequest.DoubleOptInData.builder()
.user_ip("1.2.3.4")
.referer("metasfresh")
.user_agent("metasfresh")
.build())
.build();
getLowLevelClient().post(body, SINGLE_HETEROGENOUS_TYPE, url);
// returns the email as string in case of success
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java\de\metas\marketing\gateway\cleverreach\CleverReachClient.java
| 1
|
请完成以下Java代码
|
public Mono<UserViewWrapper> login(@RequestBody @Valid UserAuthenticationRequestWrapper request) {
return userFacade.login(request.getContent())
.map(UserViewWrapper::new);
}
@PostMapping("/users")
@ResponseStatus(HttpStatus.CREATED)
public Mono<UserViewWrapper> signup(@RequestBody @Valid UserRegistrationRequestWrapper request) {
return userFacade.signup(request.getContent())
.map(UserViewWrapper::new);
}
@GetMapping("/user")
public Mono<UserViewWrapper> currentUser() {
return userSessionProvider.getCurrentUserSessionOrEmpty()
.map(UserView::fromUserAndToken)
.map(UserViewWrapper::new);
}
@PutMapping("/user")
public Mono<UserViewWrapper> updateUser(@RequestBody @Valid UpdateUserRequestWrapper request) {
return userSessionProvider.getCurrentUserSessionOrEmpty()
.flatMap(it -> userFacade.updateUser(request.getContent(), it)).map(UserViewWrapper::new);
}
|
@GetMapping("/profiles/{username}")
public Mono<ProfileWrapper> getProfile(@PathVariable String username) {
return userSessionProvider.getCurrentUserOrEmpty()
.flatMap((currentUser -> userFacade.getProfile(username, currentUser)))
.switchIfEmpty(userFacade.getProfile(username))
.map(ProfileWrapper::new);
}
@PostMapping("/profiles/{username}/follow")
public Mono<ProfileWrapper> follow(@PathVariable String username) {
return userSessionProvider.getCurrentUserOrEmpty()
.flatMap(currentUser -> userFacade.follow(username, currentUser))
.map(ProfileWrapper::new);
}
@DeleteMapping("/profiles/{username}/follow")
public Mono<ProfileWrapper> unfollow(@PathVariable String username) {
return userSessionProvider.getCurrentUserOrEmpty()
.flatMap(currentUser -> userFacade.unfollow(username, currentUser))
.map(ProfileWrapper::new);
}
}
|
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\api\UserController.java
| 1
|
请完成以下Java代码
|
public Queue build() {
return new Queue(this.name, this.durable, this.exclusive, this.autoDelete, getArguments());
}
/**
* Overflow argument values.
*/
public enum Overflow {
/**
* Drop the oldest message.
*/
dropHead("drop-head"),
/**
* Reject the new message.
*/
rejectPublish("reject-publish");
private final String value;
Overflow(String value) {
this.value = value;
}
/**
* Return the value.
* @return the value.
*/
public String getValue() {
return this.value;
}
}
/**
* Locate the queue leader.
*
* @since 2.3.7
*
*/
public enum LeaderLocator {
/**
|
* Deploy on the node with the fewest queue leaders.
*/
minLeaders("min-masters"),
/**
* Deploy on the node we are connected to.
*/
clientLocal("client-local"),
/**
* Deploy on a random node.
*/
random("random");
private final String value;
LeaderLocator(String value) {
this.value = value;
}
/**
* Return the value.
* @return the value.
*/
public String getValue() {
return this.value;
}
}
}
|
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\QueueBuilder.java
| 1
|
请完成以下Java代码
|
public String cipher(String message, int offset) {
StringBuilder result = new StringBuilder();
for (char character : message.toCharArray()) {
if (character != ' ') {
int originalAlphabetPosition = character - LETTER_A;
int newAlphabetPosition = (originalAlphabetPosition + offset) % ALPHABET_SIZE;
char newCharacter = (char) (LETTER_A + newAlphabetPosition);
result.append(newCharacter);
} else {
result.append(character);
}
}
return result.toString();
}
public String decipher(String message, int offset) {
return cipher(message, ALPHABET_SIZE - (offset % ALPHABET_SIZE));
}
public int breakCipher(String message) {
return probableOffset(chiSquares(message));
}
private double[] chiSquares(String message) {
double[] expectedLettersFrequencies = expectedLettersFrequencies(message.length());
double[] chiSquares = new double[ALPHABET_SIZE];
for (int offset = 0; offset < chiSquares.length; offset++) {
String decipheredMessage = decipher(message, offset);
long[] lettersFrequencies = observedLettersFrequencies(decipheredMessage);
double chiSquare = new ChiSquareTest().chiSquare(expectedLettersFrequencies, lettersFrequencies);
chiSquares[offset] = chiSquare;
}
return chiSquares;
}
private long[] observedLettersFrequencies(String message) {
|
return IntStream.rangeClosed(LETTER_A, LETTER_Z)
.mapToLong(letter -> countLetter((char) letter, message))
.toArray();
}
private long countLetter(char letter, String message) {
return message.chars()
.filter(character -> character == letter)
.count();
}
private double[] expectedLettersFrequencies(int messageLength) {
return Arrays.stream(ENGLISH_LETTERS_PROBABILITIES)
.map(probability -> probability * messageLength)
.toArray();
}
private int probableOffset(double[] chiSquares) {
int probableOffset = 0;
for (int offset = 0; offset < chiSquares.length; offset++) {
log.debug(String.format("Chi-Square for offset %d: %.2f", offset, chiSquares[offset]));
if (chiSquares[offset] < chiSquares[probableOffset]) {
probableOffset = offset;
}
}
return probableOffset;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\caesarcipher\CaesarCipher.java
| 1
|
请完成以下Java代码
|
public Set<QueuePackageProcessorId> getPackageProcessorIds()
{
return packageProcessorIds;
}
/**
* @param packageProcessorIds the packageProcessorIds to set
*/
public void setPackageProcessorIds(@Nullable final Set<QueuePackageProcessorId> packageProcessorIds)
{
if (packageProcessorIds != null)
{
Check.assumeNotEmpty(packageProcessorIds, "packageProcessorIds cannot be empty!");
}
this.packageProcessorIds = packageProcessorIds;
}
/*
* (non-Javadoc)
*
* @see de.metas.async.api.IWorkPackageQuery#getPriorityFrom()
*/
@Override
public String getPriorityFrom()
{
return priorityFrom;
|
}
/**
* @param priorityFrom the priorityFrom to set
*/
public void setPriorityFrom(final String priorityFrom)
{
this.priorityFrom = priorityFrom;
}
@Override
public String toString()
{
return "WorkPackageQuery ["
+ "processed=" + processed
+ ", readyForProcessing=" + readyForProcessing
+ ", error=" + error
+ ", skippedTimeoutMillis=" + skippedTimeoutMillis
+ ", packageProcessorIds=" + packageProcessorIds
+ ", priorityFrom=" + priorityFrom
+ "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageQuery.java
| 1
|
请完成以下Java代码
|
public void setMessage(final String newMessage)
{
m_message = newMessage;
fMessage.setText(m_message);
fMessage.setCaretPosition(0);
} // setMessage
/**
* Get Message
*/
public String getMessage()
{
m_message = fMessage.getText();
return m_message;
} // getMessage
public void setAttributes(final BoilerPlateContext attributes)
{
this.attributes = attributes;
fMessage.setAttributes(attributes);
}
public BoilerPlateContext getAttributes()
{
return attributes;
}
/**
* Action Listener - Send email
*/
@Override
public void actionPerformed(final ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
{
try
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
confirmPanel.getOKButton().setEnabled(false);
//
if (m_isPrintOnOK)
{
m_isPrinted = fMessage.print();
}
}
finally
{
confirmPanel.getOKButton().setEnabled(true);
setCursor(Cursor.getDefaultCursor());
}
// m_isPrinted = true;
m_isPressedOK = true;
dispose();
}
else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
|
dispose();
}
} // actionPerformed
public void setPrintOnOK(final boolean value)
{
m_isPrintOnOK = value;
}
public boolean isPressedOK()
{
return m_isPressedOK;
}
public boolean isPrinted()
{
return m_isPrinted;
}
public File getPDF()
{
return fMessage.getPDF(getTitle());
}
public RichTextEditor getRichTextEditor()
{
return fMessage;
}
} // Letter
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\LetterDialog.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int delete(List<Long> ids) {
OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample();
example.createCriteria().andIdIn(ids).andStatusEqualTo(3);
return returnApplyMapper.deleteByExample(example);
}
@Override
public int updateStatus(Long id, OmsUpdateStatusParam statusParam) {
Integer status = statusParam.getStatus();
OmsOrderReturnApply returnApply = new OmsOrderReturnApply();
if(status.equals(1)){
//确认退货
returnApply.setId(id);
returnApply.setStatus(1);
returnApply.setReturnAmount(statusParam.getReturnAmount());
returnApply.setCompanyAddressId(statusParam.getCompanyAddressId());
returnApply.setHandleTime(new Date());
returnApply.setHandleMan(statusParam.getHandleMan());
returnApply.setHandleNote(statusParam.getHandleNote());
}else if(status.equals(2)){
//完成退货
returnApply.setId(id);
returnApply.setStatus(2);
returnApply.setReceiveTime(new Date());
|
returnApply.setReceiveMan(statusParam.getReceiveMan());
returnApply.setReceiveNote(statusParam.getReceiveNote());
}else if(status.equals(3)){
//拒绝退货
returnApply.setId(id);
returnApply.setStatus(3);
returnApply.setHandleTime(new Date());
returnApply.setHandleMan(statusParam.getHandleMan());
returnApply.setHandleNote(statusParam.getHandleNote());
}else{
return 0;
}
return returnApplyMapper.updateByPrimaryKeySelective(returnApply);
}
@Override
public OmsOrderReturnApplyResult getItem(Long id) {
return returnApplyDao.getDetail(id);
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\OmsOrderReturnApplyServiceImpl.java
| 2
|
请完成以下Java代码
|
public PO getPO(final Properties ctx, final String tableName, final String whereClause, final Object[] params, final String trxName)
{
final PO po = retrievePO(ctx, tableName, whereClause, params, trxName);
if (po != null)
{
final IModelCacheService modelCacheService = Services.get(IModelCacheService.class);
modelCacheService.addToCache(po);
}
return po;
}
private PO retrievePO(final Properties ctx, final String tableName, final String whereClause, final Object[] params, final String trxName)
{
if (whereClause == null || whereClause.length() == 0)
{
return null;
}
//
PO po = null;
final POInfo info = POInfo.getPOInfo(tableName);
if (info == null)
{
return null;
}
final StringBuilder sqlBuffer = info.buildSelect();
sqlBuffer.append(" WHERE ").append(whereClause);
final String sql = sqlBuffer.toString();
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
DB.setParameters(pstmt, params);
rs = pstmt.executeQuery();
if (rs.next())
{
po = getPO(ctx, tableName, rs, trxName);
}
}
catch (Exception e)
{
log.error(sql, e);
MetasfreshLastError.saveError(log, "Error", e);
}
finally
{
DB.close(rs, pstmt);
}
|
return po;
}
public <ModelType> ModelType retrieveModel(final Properties ctx, final String tableName, final Class<?> modelClass, final ResultSet rs, final String trxName)
{
final PO po = getPO(ctx, tableName, rs, trxName);
//
// Case: we have a modelClass specified
if (modelClass != null)
{
final Class<? extends PO> poClass = po.getClass();
if (poClass.isAssignableFrom(modelClass))
{
@SuppressWarnings("unchecked") final ModelType model = (ModelType)po;
return model;
}
else
{
@SuppressWarnings("unchecked") final ModelType model = (ModelType)InterfaceWrapperHelper.create(po, modelClass);
return model;
}
}
//
// Case: no "clazz" and no "modelClass"
else
{
if (log.isDebugEnabled())
{
final AdempiereException ex = new AdempiereException("Query does not have a modelClass defined and no 'clazz' was specified as parameter."
+ "We need to avoid this case, but for now we are trying to do a force casting"
+ "\nQuery: " + this
+ "\nPO: " + po);
log.debug(ex.getLocalizedMessage(), ex);
}
@SuppressWarnings("unchecked") final ModelType model = (ModelType)po;
return model;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\TableModelLoader.java
| 1
|
请完成以下Java代码
|
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
HttpServletRequest request = RequestHolder.getHttpServletRequest();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method signatureMethod = signature.getMethod();
Limit limit = signatureMethod.getAnnotation(Limit.class);
LimitType limitType = limit.limitType();
String key = limit.key();
if (StringUtils.isEmpty(key)) {
if (limitType == LimitType.IP) {
key = StringUtils.getIp(request);
} else {
key = signatureMethod.getName();
}
}
ImmutableList<Object> keys = ImmutableList.of(StringUtils.join(limit.prefix(), "_", key, "_", request.getRequestURI().replace("/","_")));
String luaScript = buildLuaScript();
RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
Long count = redisTemplate.execute(redisScript, keys, limit.count(), limit.period());
if (ObjUtil.isNotNull(count) && count.intValue() <= limit.count()) {
logger.info("第{}次访问key为 {},描述为 [{}] 的接口", count, keys, limit.name());
return joinPoint.proceed();
} else {
throw new BadRequestException("访问次数受限制");
}
}
|
/**
* 限流脚本
*/
private String buildLuaScript() {
return "local c" +
"\nc = redis.call('get',KEYS[1])" +
"\nif c and tonumber(c) > tonumber(ARGV[1]) then" +
"\nreturn c;" +
"\nend" +
"\nc = redis.call('incr',KEYS[1])" +
"\nif tonumber(c) == 1 then" +
"\nredis.call('expire',KEYS[1],ARGV[2])" +
"\nend" +
"\nreturn c;";
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\aspect\LimitAspect.java
| 1
|
请完成以下Java代码
|
public class HandleHistoryCleanupTimerJobCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
@Override
public Object execute(CommandContext commandContext) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
CmmnManagementService managementService = cmmnEngineConfiguration.getCmmnManagementService();
List<Job> cleanupJobs = managementService.createTimerJobQuery().handlerType(CmmnHistoryCleanupJobHandler.TYPE).list();
if (cleanupJobs.isEmpty()) {
scheduleTimerJob(cmmnEngineConfiguration);
} else if (cleanupJobs.size() == 1) {
TimerJobEntity timerJob = (TimerJobEntity) cleanupJobs.get(0);
if (!Objects.equals(cmmnEngineConfiguration.getHistoryCleaningTimeCycleConfig(), timerJob.getRepeat())) {
managementService.deleteTimerJob(timerJob.getId());
scheduleTimerJob(cmmnEngineConfiguration);
}
} else {
TimerJobEntity timerJob = (TimerJobEntity) cleanupJobs.get(0);
if (!Objects.equals(cmmnEngineConfiguration.getHistoryCleaningTimeCycleConfig(), timerJob.getRepeat())) {
// If the cleaning time cycle config has changed we need to create a new timer job
managementService.deleteTimerJob(timerJob.getId());
scheduleTimerJob(cmmnEngineConfiguration);
|
}
for (int i = 1; i < cleanupJobs.size(); i++) {
managementService.deleteTimerJob(cleanupJobs.get(i).getId());
}
}
return null;
}
protected void scheduleTimerJob(CmmnEngineConfiguration cmmnEngineConfiguration) {
TimerJobService timerJobService = cmmnEngineConfiguration.getJobServiceConfiguration().getTimerJobService();
TimerJobEntity timerJob = timerJobService.createTimerJob();
timerJob.setJobType(JobEntity.JOB_TYPE_TIMER);
timerJob.setRevision(1);
timerJob.setJobHandlerType(CmmnHistoryCleanupJobHandler.TYPE);
timerJob.setScopeType(ScopeTypes.CMMN);
BusinessCalendar businessCalendar = cmmnEngineConfiguration.getBusinessCalendarManager().getBusinessCalendar(CycleBusinessCalendar.NAME);
timerJob.setDuedate(businessCalendar.resolveDuedate(cmmnEngineConfiguration.getHistoryCleaningTimeCycleConfig()));
timerJob.setRepeat(cmmnEngineConfiguration.getHistoryCleaningTimeCycleConfig());
timerJobService.scheduleTimerJob(timerJob);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\HandleHistoryCleanupTimerJobCmd.java
| 1
|
请完成以下Java代码
|
public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID)
{
if (S_ResourceAssignment_ID < 1)
set_Value (COLUMNNAME_S_ResourceAssignment_ID, null);
else
set_Value (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID));
}
/** Get Resource Assignment.
@return Resource Assignment
*/
public int getS_ResourceAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_S_TimeExpense getS_TimeExpense() throws RuntimeException
{
return (I_S_TimeExpense)MTable.get(getCtx(), I_S_TimeExpense.Table_Name)
.getPO(getS_TimeExpense_ID(), get_TrxName()); }
/** Set Expense Report.
@param S_TimeExpense_ID
Time and Expense Report
*/
public void setS_TimeExpense_ID (int S_TimeExpense_ID)
{
if (S_TimeExpense_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeExpense_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeExpense_ID, Integer.valueOf(S_TimeExpense_ID));
}
/** Get Expense Report.
@return Time and Expense Report
*/
public int getS_TimeExpense_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeExpense_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Expense Line.
@param S_TimeExpenseLine_ID
|
Time and Expense Report Line
*/
public void setS_TimeExpenseLine_ID (int S_TimeExpenseLine_ID)
{
if (S_TimeExpenseLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeExpenseLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeExpenseLine_ID, Integer.valueOf(S_TimeExpenseLine_ID));
}
/** Get Expense Line.
@return Time and Expense Report Line
*/
public int getS_TimeExpenseLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeExpenseLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_S_TimeType getS_TimeType() throws RuntimeException
{
return (I_S_TimeType)MTable.get(getCtx(), I_S_TimeType.Table_Name)
.getPO(getS_TimeType_ID(), get_TrxName()); }
/** Set Time Type.
@param S_TimeType_ID
Type of time recorded
*/
public void setS_TimeType_ID (int S_TimeType_ID)
{
if (S_TimeType_ID < 1)
set_Value (COLUMNNAME_S_TimeType_ID, null);
else
set_Value (COLUMNNAME_S_TimeType_ID, Integer.valueOf(S_TimeType_ID));
}
/** Get Time Type.
@return Type of time recorded
*/
public int getS_TimeType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_TimeExpenseLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final class MetricsAspectsAutoConfiguration {
@Bean
@ConditionalOnMissingBean
CountedAspect countedAspect(MeterRegistry registry,
ObjectProvider<CountedMeterTagAnnotationHandler> countedMeterTagAnnotationHandler) {
CountedAspect countedAspect = new CountedAspect(registry);
countedMeterTagAnnotationHandler.ifAvailable(countedAspect::setMeterTagAnnotationHandler);
return countedAspect;
}
@Bean
@ConditionalOnMissingBean
TimedAspect timedAspect(MeterRegistry registry,
ObjectProvider<MeterTagAnnotationHandler> meterTagAnnotationHandler) {
TimedAspect timedAspect = new TimedAspect(registry);
meterTagAnnotationHandler.ifAvailable(timedAspect::setMeterTagAnnotationHandler);
return timedAspect;
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(ValueExpressionResolver.class)
static class TagAnnotationHandlersConfiguration {
@Bean
@ConditionalOnMissingBean
|
CountedMeterTagAnnotationHandler countedMeterTagAnnotationHandler(BeanFactory beanFactory,
ValueExpressionResolver valueExpressionResolver) {
return new CountedMeterTagAnnotationHandler(beanFactory::getBean, (ignored) -> valueExpressionResolver);
}
@Bean
@ConditionalOnMissingBean
MeterTagAnnotationHandler meterTagAnnotationHandler(BeanFactory beanFactory,
ValueExpressionResolver valueExpressionResolver) {
return new MeterTagAnnotationHandler(beanFactory::getBean, (ignored) -> valueExpressionResolver);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\MetricsAspectsAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public Integer getPublishCount() {
return publishCount;
}
public void setPublishCount(Integer publishCount) {
this.publishCount = publishCount;
}
public Integer getUseCount() {
return useCount;
}
public void setUseCount(Integer useCount) {
this.useCount = useCount;
}
public Integer getReceiveCount() {
return receiveCount;
}
public void setReceiveCount(Integer receiveCount) {
this.receiveCount = receiveCount;
}
public Date getEnableTime() {
return enableTime;
}
public void setEnableTime(Date enableTime) {
this.enableTime = enableTime;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
|
}
public Integer getMemberLevel() {
return memberLevel;
}
public void setMemberLevel(Integer memberLevel) {
this.memberLevel = memberLevel;
}
@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(", type=").append(type);
sb.append(", name=").append(name);
sb.append(", platform=").append(platform);
sb.append(", count=").append(count);
sb.append(", amount=").append(amount);
sb.append(", perLimit=").append(perLimit);
sb.append(", minPoint=").append(minPoint);
sb.append(", startTime=").append(startTime);
sb.append(", endTime=").append(endTime);
sb.append(", useType=").append(useType);
sb.append(", note=").append(note);
sb.append(", publishCount=").append(publishCount);
sb.append(", useCount=").append(useCount);
sb.append(", receiveCount=").append(receiveCount);
sb.append(", enableTime=").append(enableTime);
sb.append(", code=").append(code);
sb.append(", memberLevel=").append(memberLevel);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCoupon.java
| 1
|
请完成以下Java代码
|
public void setOnMouseOver (String script)
{
addAttribute ("onmouseover", script);
}
/**
* The onmousemove event occurs when the pointing device is moved while it
* is over an element. This attribute may be used with most elements.
*
* @param script script
*/
public void setOnMouseMove (String script)
{
addAttribute ("onmousemove", script);
}
/**
* The onmouseout event occurs when the pointing device is moved away from
* an element. This attribute may be used with most elements.
*
* @param script script
*/
public void setOnMouseOut (String script)
{
addAttribute ("onmouseout", script);
}
/**
* The onkeypress event occurs when a key is pressed and released over an
* element. This attribute may be used with most elements.
*
* @param script script
*/
public void setOnKeyPress (String script)
{
addAttribute ("onkeypress", script);
}
/**
|
* The onkeydown event occurs when a key is pressed down over an element.
* This attribute may be used with most elements.
*
* @param script script
*/
public void setOnKeyDown (String script)
{
addAttribute ("onkeydown", script);
}
/**
* The onkeyup event occurs when a key is released over an element. This
* attribute may be used with most elements.
*
* @param script script
*/
public void setOnKeyUp (String script)
{
addAttribute ("onkeyup", script);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\acronym.java
| 1
|
请完成以下Java代码
|
public void setFieldMinWidth(final int fieldMinWidth)
{
this.fieldMinWidth = fieldMinWidth;
}
public void setFieldMaxWidth(final int fieldMaxWidth)
{
this.fieldMaxWidth = fieldMaxWidth;
}
public void updateMinWidthFrom(final CLabel label)
{
final int labelWidth = label.getPreferredSize().width;
labelMinWidth = labelWidth > labelMinWidth ? labelWidth : labelMinWidth;
|
logger.trace("LabelMinWidth={} ({})", new Object[] { labelMinWidth, label });
}
public void updateMinWidthFrom(final VEditor editor)
{
final JComponent editorComp = swingEditorFactory.getEditorComponent(editor);
final int editorCompWidth = editorComp.getPreferredSize().width;
if (editorCompWidth > fieldMinWidth)
{
fieldMinWidth = editorCompWidth;
}
logger.trace("FieldMinWidth={} ({})", new Object[] { fieldMinWidth, editorComp });
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelLayoutCallback.java
| 1
|
请完成以下Java代码
|
private void setAdditionalContactFields(
@NonNull final JsonCustomerBuilder customerBuilder,
@NonNull final BPartnerLocation bPartnerLocation)
{
customerBuilder
.contactEmail(bPartnerLocation.getEmail())
.contactName(bPartnerLocation.getBpartnerName())
.contactPhone(bPartnerLocation.getPhone());
logger.debug("Exporting effective contactEmail={}, contactName={}, contactPhone={} from the bPartnerLocationId={}",
bPartnerLocation.getEmail(),
bPartnerLocation.getBpartnerName(),
bPartnerLocation.getPhone(),
bPartnerLocation.getId());
}
private void setAdditionalContactFieldsForOxidOrder(
@NonNull final ShipmentSchedule shipmentSchedule,
@NonNull final BPartnerComposite composite,
@NonNull final JsonCustomerBuilder customerBuilder,
|
@Nullable final BPartnerContactId contactId)
{
if (contactId == null)
{
return;
}
final BPartnerContact contact = composite.extractContact(contactId)
.orElseThrow(() -> new ShipmentCandidateExportException("Unable to get the contact info from bPartnerComposite!")
.appendParametersToMessage()
.setParameter("composite.C_BPartner_ID", composite.getBpartner().getId())
.setParameter("AD_User_ID", contactId));
customerBuilder
.contactEmail(oxidAdaptor.getContactEmail(shipmentSchedule, composite))
.contactName(contact.getName())
.contactPhone(contact.getPhone());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\shipping\ShipmentCandidateAPIService.java
| 1
|
请完成以下Java代码
|
protected boolean beforeSave (boolean newRecord)
{
if (getAD_Org_ID() != 0)
setAD_Org_ID(0);
return true;
} // beforeSave
/**
* After Save.
* Insert
* - create tree
* @param newRecord insert
* @param success save success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
return success;
if (newRecord)
|
insert_Tree(MTree_Base.TREETYPE_SalesRegion);
// Value/Name change
if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name")))
MAccount.updateValueDescription(getCtx(), "C_SalesRegion_ID=" + getC_SalesRegion_ID(), get_TrxName());
return true;
} // afterSave
/**
* After Delete
* @param success
* @return deleted
*/
protected boolean afterDelete (boolean success)
{
if (success)
delete_Tree(MTree_Base.TREETYPE_SalesRegion);
return success;
} // afterDelete
} // MSalesRegion
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSalesRegion.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractSessionEvent extends ApplicationEvent {
private final String sessionId;
private final Session session;
AbstractSessionEvent(Object source, Session session) {
super(source);
this.session = session;
this.sessionId = session.getId();
}
/**
* Gets the {@link Session} that was destroyed. For some {@link SessionRepository}
* implementations it may not be possible to get the original session in which case
|
* this may be null.
* @param <S> the type of Session
* @return the expired {@link Session} or null if the data store does not support
* obtaining it
*/
@SuppressWarnings("unchecked")
public <S extends Session> S getSession() {
return (S) this.session;
}
public String getSessionId() {
return this.sessionId;
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\events\AbstractSessionEvent.java
| 1
|
请完成以下Java代码
|
default Context createContext(long dueTimestamp, String listenerId, TopicPartition topicPartition,
@Nullable Consumer<?, ?> messageConsumer) {
return new Context(dueTimestamp, topicPartition, listenerId, messageConsumer);
}
/**
* Provides the state that will be used for backing off.
* @since 2.7
*/
class Context {
/**
* The time after which the message should be processed,
* in milliseconds since epoch.
*/
private final long dueTimestamp;
/**
* The id for the listener that should be paused.
*/
private final String listenerId;
/**
* The topic that contains the partition to be paused.
*/
private final TopicPartition topicPartition;
/**
* The consumer of the message, if present.
*/
private final @Nullable Consumer<?, ?> consumerForTimingAdjustment;
Context(long dueTimestamp, TopicPartition topicPartition, String listenerId,
@Nullable Consumer<?, ?> consumerForTimingAdjustment) {
this.dueTimestamp = dueTimestamp;
|
this.listenerId = listenerId;
this.topicPartition = topicPartition;
this.consumerForTimingAdjustment = consumerForTimingAdjustment;
}
public long getDueTimestamp() {
return this.dueTimestamp;
}
public String getListenerId() {
return this.listenerId;
}
public TopicPartition getTopicPartition() {
return this.topicPartition;
}
public @Nullable Consumer<?, ?> getConsumerForTimingAdjustment() {
return this.consumerForTimingAdjustment;
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\KafkaConsumerBackoffManager.java
| 1
|
请完成以下Java代码
|
private Step step() throws Exception {
return stepBuilderFactory.get("step")
.<TestData, TestData>chunk(2)
.reader(simpleReader)
.writer(xmlFileItemWriter())
.build();
}
private StaxEventItemWriter<TestData> xmlFileItemWriter() throws IOException {
StaxEventItemWriter<TestData> writer = new StaxEventItemWriter<>();
// 通过XStreamMarshaller将TestData转换为xml
XStreamMarshaller marshaller = new XStreamMarshaller();
Map<String,Class<TestData>> map = new HashMap<>(1);
map.put("test", TestData.class);
|
marshaller.setAliases(map); // 设置xml标签
writer.setRootTagName("tests"); // 设置根标签
writer.setMarshaller(marshaller);
FileSystemResource file = new FileSystemResource("/Users/mrbird/Desktop/file.xml");
Path path = Paths.get(file.getPath());
if (!Files.exists(path)) {
Files.createFile(path);
}
writer.setResource(file); // 设置目标文件路径
return writer;
}
}
|
repos\SpringAll-master\69.spring-batch-itemwriter\src\main\java\cc\mrbird\batch\job\XmlFileItemWriterDemo.java
| 1
|
请完成以下Java代码
|
public String modelChange(final PO po, int type)
{
assert po instanceof MInvoiceLine : po;
if (type == TYPE_BEFORE_CHANGE || type == TYPE_BEFORE_NEW)
{
final IInvoiceLineBL invoiceLineBL = Services.get(IInvoiceLineBL.class);
final I_C_InvoiceLine il = InterfaceWrapperHelper.create(po, I_C_InvoiceLine.class);
if (!il.isProcessed())
{
logger.debug("Reevaluating tax for " + il);
invoiceLineBL.setTaxBasedOnShipment(il, po.get_TrxName());
logger.debug("Setting TaxAmtInfo for " + il);
invoiceLineBL.setTaxAmtInfo(po.getCtx(), il, po.get_TrxName());
}
// Introduced by US1184, because having the same price on Order and Invoice is enforced by German Law
if (invoiceLineBL.isPriceLocked(il))
{
assertOrderInvoicePricesMatch(il);
}
}
else if (type == TYPE_BEFORE_DELETE)
{
final I_C_InvoiceLine il = InterfaceWrapperHelper.create(po, I_C_InvoiceLine.class);
beforeDelete(il);
|
}
return null;
}
void beforeDelete(final org.compiere.model.I_C_InvoiceLine invoiceLine)
{
final IInvoiceDAO invoiceDAO = Services.get(IInvoiceDAO.class);
final InvoiceAndLineId invoiceAndLineId = InvoiceAndLineId.ofRepoId(invoiceLine.getC_Invoice_ID(), invoiceLine.getC_InvoiceLine_ID());
for (final I_C_InvoiceLine refInvoiceLine : invoiceDAO.retrieveReferringLines(invoiceAndLineId))
{
refInvoiceLine.setRef_InvoiceLine_ID(0);
invoiceDAO.save(refInvoiceLine);
}
}
public static void assertOrderInvoicePricesMatch(final I_C_InvoiceLine invoiceLine)
{
final I_C_OrderLine oline = invoiceLine.getC_OrderLine();
if (invoiceLine.getPriceActual().compareTo(oline.getPriceActual()) != 0)
{
throw new OrderInvoicePricesNotMatchException(I_C_InvoiceLine.COLUMNNAME_PriceActual, oline.getPriceActual(), invoiceLine.getPriceActual());
}
if (invoiceLine.getPriceList().compareTo(oline.getPriceList()) != 0)
{
throw new OrderInvoicePricesNotMatchException(I_C_InvoiceLine.COLUMNNAME_PriceList, oline.getPriceList(), invoiceLine.getPriceList());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\InvoiceLine.java
| 1
|
请完成以下Spring Boot application配置
|
spring.application.name=spring-boot-persistence
server.port=8082
#spring boot mongodb
spring.data.mongodb.host=localhost
spring.data.mongodb.port=0
spring.data.mongodb.database=springboot-mongo
spring.thymeleaf.cache=false
spring.servlet.multipart.max-file-size=256MB
spring.servlet.multipart.max-request-size
|
=256MB
spring.servlet.multipart.enabled=true
spring.data.mongodb.uri=mongodb://localhost
de.flapdoodle.mongodb.embedded.version=8.0.5
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private void performNameRequest(final NameRequest nameRequest, IWebSession webSession) {
try {
CompletableFuture<NameAnalysisEntity> nameAnalysis = this.nameAnalysisService.searchForName(nameRequest);
NameAnalysisEntity nameAnalysisEntity = nameAnalysis.get(30, TimeUnit.SECONDS);
sessionRegisterRequest(nameRequest, webSession);
sessionRegisterAnalysis(nameAnalysisEntity, webSession);
sessionClearAnalysisError(webSession);
} catch (Exception e) {
e.printStackTrace();
sessionSetAnalysisError(nameRequest, webSession);
}
}
private void sessionClearAnalysisError(IWebSession webSession) {
webSession.removeAttribute("analysisError");
}
private void sessionSetAnalysisError(NameRequest nameRequest, IWebSession webSession) {
webSession.setAttributeValue("analysisError", nameRequest);
}
private void clearAnalysis(IWebSession webSession) {
webSession.removeAttribute("lastAnalysis");
}
private void sessionRegisterAnalysis(NameAnalysisEntity analysis, IWebSession webSession) {
webSession.setAttributeValue("lastAnalysis", analysis);
}
private void sessionRegisterRequest(NameRequest nameRequest, IWebSession webSession) {
webSession.setAttributeValue("lastRequest", nameRequest);
|
SessionNameRequest sessionNameRequest = sessionNameRequestFactory.getInstance(nameRequest);
List<SessionNameRequest> requests = getRequestsFromSession(webSession);
requests.add(0, sessionNameRequest);
}
private List<SessionNameRequest> getRequestsFromSession(IWebSession session) {
Object requests = session.getAttributeValue("requests");
if (requests == null || !(requests instanceof List)) {
List<SessionNameRequest> sessionNameRequests = new ArrayList<>();
session.setAttributeValue("requests", sessionNameRequests);
requests = sessionNameRequests;
}
return (List<SessionNameRequest>) requests;
}
private IWebSession getIWebSession(HttpServletRequest request, HttpServletResponse response) {
IServletWebExchange exchange = webApp.buildExchange(request, response);
return exchange == null ? null : exchange.getSession();
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\web\controllers\NameAnalysisController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class CreatePriceListSchemaRequest
{
@NonNull
PricingConditionsId discountSchemaId;
int seqNo;
@Nullable
ProductId productId;
@Nullable
ProductCategoryId productCategoryId;
@Nullable
BPartnerId bPartnerId;
@Nullable
TaxCategoryId taxCategoryId;
@Nullable
TaxCategoryId taxCategoryTargetId;
@NonNull
LocalDate conversionDate;
@NonNull
CurrencyConversionTypeId conversionTypeId;
@NonNull
BigDecimal limit_AddAmt;
@NonNull
String limit_Base;
@NonNull
BigDecimal limit_Discount;
@NonNull
BigDecimal limit_MaxAmt;
@NonNull
BigDecimal limit_MinAmt;
@NonNull
|
String limit_Rounding;
@NonNull
BigDecimal list_AddAmt;
@NonNull
String list_Base;
@NonNull
BigDecimal list_Discount;
@NonNull
BigDecimal list_MaxAmt;
@NonNull
BigDecimal list_MinAmt;
@NonNull
String list_Rounding;
@NonNull
BigDecimal std_AddAmt;
@NonNull
String std_Base;
@NonNull
BigDecimal std_Discount;
@NonNull
BigDecimal std_MaxAmt;
@NonNull
BigDecimal std_MinAmt;
@NonNull
String std_Rounding;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\service\CreatePriceListSchemaRequest.java
| 2
|
请完成以下Java代码
|
private DocTypeId getDocTypeId()
{
Integer docTypeId = (Integer)m_mTab.getValue("C_DocType_ID");
if (docTypeId == null || docTypeId.intValue() <= 0)
{
docTypeId = (Integer)m_mTab.getValue("C_DocTypeTarget_ID");
}
return docTypeId != null ? DocTypeId.ofRepoIdOrNull(docTypeId) : null;
}
/**
* Check Status Change
*
* @param TableName table name
* @param Record_ID record
* @param DocStatus current doc status
* @return true if status not changed
*/
private boolean checkStatus(final String TableName, final int Record_ID, final String DocStatus)
{
final String sql = "SELECT 2 FROM " + TableName
+ " WHERE " + TableName + "_ID=" + Record_ID
+ " AND DocStatus='" + DocStatus + "'";
final int result = DB.getSQLValue(null, sql);
return result == 2;
} // checkStatusChange
/**
* Number of options available (to decide to display it)
*
* @return item count
*/
public int getNumberOfOptions()
{
return actionCombo.getItemCount();
} // getNumberOfOptions
/**
* Should the process be started?
*
* @return OK pressed
*/
public boolean isStartProcess()
{
return m_OKpressed;
} // isStartProcess
/**
* Fill map with DocAction Ref_List(135) values
*/
private Map<String, IDocActionItem> getDocActionItemsIndexedByValue()
{
if (docActionItemsByValue == null)
{
docActionItemsByValue = Services.get(IDocumentBL.class).retrieveDocActionItemsIndexedByValue();
}
return docActionItemsByValue;
}
/**
* ActionListener
*
* @param e event
*/
@Override
public void actionPerformed(final ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
{
if (save())
|
{
dispose();
m_OKpressed = true;
}
}
else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
}
//
// ActionCombo: display the description for the selection
else if (e.getSource() == actionCombo)
{
final IDocActionItem selectedDocAction = actionCombo.getSelectedItem();
// Display description
if (selectedDocAction != null)
{
message.setText(selectedDocAction.getDescription());
}
}
} // actionPerformed
/**
* Save to Database
*
* @return true if saved to Tab
*/
private boolean save()
{
final IDocActionItem selectedDocAction = actionCombo.getSelectedItem();
if (selectedDocAction == null)
{
return false;
}
// Save Selection
log.info("DocAction={}", selectedDocAction);
m_mTab.setValue("DocAction", selectedDocAction.getValue());
return true;
} // save
} // VDocAction
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VDocAction.java
| 1
|
请完成以下Spring Boot application配置
|
server.port=8081
spring.application.name=config
spring.cloud.config.server.git.uri=file:///${user.home}/application-config
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@l
|
ocalhost:8082/eureka/
security.user.name=configUser
security.user.password=configPassword
security.user.role=SYSTEM
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\config\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
webSocketMap.put(userId, this);
} else {
webSocketMap.put(userId, this);
addOnlineCount();
}
log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
try {
sendMessage("连接成功!");
} catch (IOException e) {
log.error("用户:" + userId + ",网络异常!!!!!!");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
subOnlineCount();
}
log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("用户消息:" + userId + ",报文:" + message);
if (!StringUtils.isEmpty(message)) {
try {
JSONObject jsonObject = JSON.parseObject(message);
jsonObject.put("fromUserId", this.userId);
String toUserId = jsonObject.getString("toUserId");
if (!StringUtils.isEmpty(toUserId) && webSocketMap.containsKey(toUserId)) {
webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
} else {
log.error("请求的 userId:" + toUserId + "不在该服务器上");
}
} catch (Exception e) {
e.printStackTrace();
|
}
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static synchronized AtomicInteger getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount.getAndIncrement();
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount.getAndDecrement();
}
}
|
repos\springboot-demo-master\websocket\src\main\java\com\et\websocket\channel\WebSocketServer.java
| 1
|
请完成以下Java代码
|
public @Nullable <D> D toEntity(Class<D> entityType) {
return toEntity(ResolvableType.forType(entityType));
}
@Override
public @Nullable <D> D toEntity(ParameterizedTypeReference<D> entityType) {
return toEntity(ResolvableType.forType(entityType));
}
@Override
public <D> List<D> toEntityList(Class<D> elementType) {
List<D> list = toEntity(ResolvableType.forClassWithGenerics(List.class, elementType));
return (list != null) ? list : Collections.emptyList();
}
@Override
public <D> List<D> toEntityList(ParameterizedTypeReference<D> elementType) {
List<D> list = toEntity(ResolvableType.forClassWithGenerics(List.class, ResolvableType.forType(elementType)));
return (list != null) ? list : Collections.emptyList();
}
@SuppressWarnings("unchecked")
private @Nullable <T> T toEntity(ResolvableType targetType) {
if (getValue() == null) {
if (this.response.isValid() && getErrors().isEmpty()) {
return null;
}
|
throw new FieldAccessException(this.response.getRequest(), this.response, this);
}
DataBufferFactory bufferFactory = DefaultDataBufferFactory.sharedInstance;
MimeType mimeType = MimeTypeUtils.APPLICATION_JSON;
Map<String, Object> hints = Collections.emptyMap();
try {
DataBuffer buffer = ((Encoder<T>) this.response.getEncoder()).encodeValue(
(T) getValue(), bufferFactory, ResolvableType.forInstance(getValue()), mimeType, hints);
return ((Decoder<T>) this.response.getDecoder()).decode(buffer, targetType, mimeType, hints);
}
catch (Throwable ex) {
throw new GraphQlClientException("Cannot read field '" + this.field.getPath() + "'", ex, this.response.getRequest());
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultClientResponseField.java
| 1
|
请完成以下Java代码
|
public void setPA_ReportLineSet_ID (int PA_ReportLineSet_ID)
{
if (PA_ReportLineSet_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, Integer.valueOf(PA_ReportLineSet_ID));
}
/** Get Report Line Set.
@return Report Line Set */
public int getPA_ReportLineSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLineSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
|
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportLineSet.java
| 1
|
请完成以下Java代码
|
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Case.class, CMMN_ELEMENT_CASE)
.extendsType(CmmnElement.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<Case>() {
public Case newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
camundaHistoryTimeToLive = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_HISTORY_TIME_TO_LIVE)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
caseFileModelChild = sequenceBuilder.element(CaseFileModel.class)
.build();
casePlanModelChild = sequenceBuilder.element(CasePlanModel.class)
.build();
caseRolesCollection = sequenceBuilder.elementCollection(CaseRole.class)
.build();
|
caseRolesChild = sequenceBuilder.element(CaseRoles.class)
.build();
inputCollection = sequenceBuilder.elementCollection(InputCaseParameter.class)
.build();
outputCollection = sequenceBuilder.elementCollection(OutputCaseParameter.class)
.build();
typeBuilder.build();
}
@Override
public String getCamundaHistoryTimeToLiveString() {
return camundaHistoryTimeToLive.getValue(this);
}
@Override
public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) {
camundaHistoryTimeToLive.setValue(this, historyTimeToLive);
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseImpl.java
| 1
|
请完成以下Java代码
|
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Date getBookingDate() {
return bookingDate;
}
public void setBookingDate(Date bookingDate) {
this.bookingDate = bookingDate;
}
|
public int getAmout() {
return amout;
}
public void setAmout(int amout) {
this.amout = amout;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
|
repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\domain\model\Order.java
| 1
|
请完成以下Java代码
|
public static void validateXML(final File xmlFile, final File schemaFile) throws SAXException, IOException
{
System.out.println("Validating:");
System.out.println("Schema: " + schemaFile);
System.out.println("Test XML File: " + xmlFile);
final SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
final Schema schema = factory.newSchema(schemaFile);
final Validator validator = schema.newValidator();
final Source source = new StreamSource(xmlFile);
validator.validate(source);
System.out.println("File " + xmlFile + " is valid");
}
/**
*
* @param line
* @param defaultDisplayType
* @return
*/
private int getDisplayType(final I_EXP_FormatLine line, final int defaultDisplayType)
{
if (line.getAD_Reference_Override_ID() > 0)
{
|
return line.getAD_Reference_Override_ID();
}
final I_AD_Column column = line.getAD_Column();
if (column == null || column.getAD_Column_ID() <= 0)
{
return defaultDisplayType;
}
final int displayType = column.getAD_Reference_ID();
if (displayType <= 0)
{
return defaultDisplayType;
}
return displayType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\esb\util\CanonicalXSDGenerator.java
| 1
|
请完成以下Java代码
|
private static JsonActualImport toJson(@Nullable final ActualImportRecordsResult result)
{
if (result == null)
{
return null;
}
return JsonActualImport.builder()
.importTableName(result.getImportTableName())
.targetTableName(result.getTargetTableName())
.countImportRecordsConsidered(result.getCountImportRecordsConsidered().orElse(0))
.countInsertsIntoTargetTable(result.getCountInsertsIntoTargetTable().orElse(0))
.countUpdatesIntoTargetTable(result.getCountUpdatesIntoTargetTable().orElse(0))
.errors(result.getErrors()
.stream()
.map(error -> toJsonErrorItem(error))
.collect(ImmutableList.toImmutableList()))
.build();
}
private static JsonActualImportAsync toJson(@Nullable final AsyncImportRecordsResponse result)
{
if (result == null)
{
return null;
}
return JsonActualImportAsync.builder()
.workpackageId(result.getWorkpackageId())
.build();
}
private static JsonErrorItem toJsonErrorItem(final InsertIntoImportTableResult.Error error)
{
return JsonErrorItem.builder()
.message(error.getMessage())
.parameter(ERROR_PARAM_WHERE, "source-file")
|
.parameter("importLineNo", String.valueOf(error.getLineNo()))
.parameter("importLineContent", error.getLineContent())
.build();
}
private static JsonErrorItem toJsonErrorItem(final ActualImportRecordsResult.Error error)
{
return JsonErrorItem.builder()
.message(error.getMessage())
.adIssueId(JsonMetasfreshId.of(error.getAdIssueId().getRepoId()))
.throwable(error.getException())
.stackTrace(error.getException() != null
? Trace.toOneLineStackTraceString(error.getException())
: null)
.parameter(ERROR_PARAM_WHERE, "actual-import")
.parameter("affectedRecordsCount", String.valueOf(error.getAffectedImportRecordsCount()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\data_import\DataImportRestController.java
| 1
|
请完成以下Java代码
|
public List<String> getUnigramTempls_()
{
return unigramTempls_;
}
public void setUnigramTempls_(List<String> unigramTempls_)
{
this.unigramTempls_ = unigramTempls_;
}
public List<String> getBigramTempls_()
{
return bigramTempls_;
}
public void setBigramTempls_(List<String> bigramTempls_)
{
this.bigramTempls_ = bigramTempls_;
}
public List<String> getY_()
{
return y_;
}
public void setY_(List<String> y_)
{
this.y_ = y_;
}
|
public List<List<Path>> getPathList_()
{
return pathList_;
}
public void setPathList_(List<List<Path>> pathList_)
{
this.pathList_ = pathList_;
}
public List<List<Node>> getNodeList_()
{
return nodeList_;
}
public void setNodeList_(List<List<Node>> nodeList_)
{
this.nodeList_ = nodeList_;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\FeatureIndex.java
| 1
|
请完成以下Java代码
|
public final class ObjectValueExpression extends jakarta.el.ValueExpression {
private static final long serialVersionUID = 1L;
private final TypeConverter converter;
private final Object object;
private final Class<?> type;
/**
* Wrap an object into a value expression.
* @param converter type converter
* @param object the object to wrap
* @param type the expected type this object will be coerced in {@link #getValue(ELContext)}.
*/
public ObjectValueExpression(TypeConverter converter, Object object, Class<?> type) {
super();
this.converter = converter;
this.object = object;
this.type = type;
if (type == null) {
throw new NullPointerException(LocalMessages.get("error.value.notype"));
}
}
/**
* Two object value expressions are equal if and only if their wrapped objects are equal.
*/
@Override
public boolean equals(Object obj) {
if (obj != null && obj.getClass() == getClass()) {
ObjectValueExpression other = (ObjectValueExpression)obj;
if (type != other.type) {
return false;
}
return object == other.object || object != null && object.equals(other.object);
}
return false;
}
@Override
public int hashCode() {
return object == null ? 0 : object.hashCode();
}
/**
* Answer the wrapped object, coerced to the expected type.
*/
@Override
public Object getValue(ELContext context) {
return converter.convert(object, type);
|
}
/**
* Answer <code>null</code>.
*/
@Override
public String getExpressionString() {
return null;
}
/**
* Answer <code>false</code>.
*/
@Override
public boolean isLiteralText() {
return false;
}
/**
* Answer <code>null</code>.
*/
@Override
public Class<?> getType(ELContext context) {
return null;
}
/**
* Answer <code>true</code>.
*/
@Override
public boolean isReadOnly(ELContext context) {
return true;
}
/**
* Throw an exception.
*/
@Override
public void setValue(ELContext context, Object value) {
throw new ELException(LocalMessages.get("error.value.set.rvalue", "<object value expression>"));
}
@Override
public String toString() {
return "ValueExpression(" + object + ")";
}
@Override
public Class<?> getExpectedType() {
return type;
}
}
|
repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\ObjectValueExpression.java
| 1
|
请完成以下Java代码
|
private @Nullable Method getMainMethod(StackTraceElement element) {
try {
Class<?> elementClass = Class.forName(element.getClassName());
Method method = getMainMethod(elementClass);
if (Modifier.isStatic(method.getModifiers())) {
return method;
}
}
catch (Exception ex) {
// Ignore
}
return null;
}
private static Method getMainMethod(Class<?> clazz) throws Exception {
try {
return clazz.getDeclaredMethod("main", String[].class);
}
catch (NoSuchMethodException ex) {
return clazz.getDeclaredMethod("main");
|
}
}
/**
* Returns the actual main method.
* @return the main method
*/
Method getMethod() {
return this.method;
}
/**
* Return the name of the declaring class.
* @return the declaring class name
*/
String getDeclaringClassName() {
return this.method.getDeclaringClass().getName();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\MainMethod.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<RfqQty> getQuantities()
{
return quantities;
}
public ImmutableSet<LocalDate> generateAllDaysSet()
{
final ArrayList<LocalDate> dates = DateUtils.getDaysList(getDateStart(), getDateEnd());
dates.addAll(quantities
.stream()
.map(RfqQty::getDatePromised)
.collect(ImmutableSet.toImmutableSet()));
dates.sort(LocalDate::compareTo);
return ImmutableSet.copyOf(dates);
}
public void setPricePromisedUserEntered(@NonNull final BigDecimal pricePromisedUserEntered)
{
this.pricePromisedUserEntered = pricePromisedUserEntered;
}
public BigDecimal getQtyPromisedUserEntered()
{
return quantities.stream()
.map(RfqQty::getQtyPromisedUserEntered)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
public void setQtyPromised(@NonNull final LocalDate date, @NonNull final BigDecimal qtyPromised)
{
final RfqQty rfqQty = getOrCreateQty(date);
rfqQty.setQtyPromisedUserEntered(qtyPromised);
updateConfirmedByUser();
}
private RfqQty getOrCreateQty(@NonNull final LocalDate date)
{
final RfqQty existingRfqQty = getRfqQtyByDate(date);
if (existingRfqQty != null)
{
return existingRfqQty;
}
else
{
final RfqQty rfqQty = RfqQty.builder()
.rfq(this)
.datePromised(date)
.build();
addRfqQty(rfqQty);
return rfqQty;
}
}
private void addRfqQty(final RfqQty rfqQty)
{
rfqQty.setRfq(this);
quantities.add(rfqQty);
}
@Nullable
public RfqQty getRfqQtyByDate(@NonNull final LocalDate date)
{
for (final RfqQty rfqQty : quantities)
{
if (date.equals(rfqQty.getDatePromised()))
{
return rfqQty;
}
}
|
return null;
}
private void updateConfirmedByUser()
{
this.confirmedByUser = computeConfirmedByUser();
}
private boolean computeConfirmedByUser()
{
if (pricePromised.compareTo(pricePromisedUserEntered) != 0)
{
return false;
}
for (final RfqQty rfqQty : quantities)
{
if (!rfqQty.isConfirmedByUser())
{
return false;
}
}
return true;
}
public void closeIt()
{
this.closed = true;
}
public void confirmByUser()
{
this.pricePromised = getPricePromisedUserEntered();
quantities.forEach(RfqQty::confirmByUser);
updateConfirmedByUser();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Rfq.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class TaxCategoryId implements RepoIdAware
{
public static TaxCategoryId NOT_FOUND = new TaxCategoryId(100);
@JsonCreator
public static TaxCategoryId ofRepoId(final int repoId)
{
if (repoId == NOT_FOUND.getRepoId())
{
return NOT_FOUND;
}
else
{
return new TaxCategoryId(repoId);
}
}
public static TaxCategoryId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static TaxCategoryId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<TaxCategoryId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(final TaxCategoryId id)
{
|
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(final TaxCategoryId o1, final TaxCategoryId o2)
{
return Objects.equals(o1, o2);
}
int repoId;
private TaxCategoryId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_TaxCategory_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\tax\api\TaxCategoryId.java
| 2
|
请完成以下Java代码
|
public java.math.BigDecimal getTransfertTime ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TransfertTime);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Working Time.
@param WorkingTime
Workflow Simulation Execution Time
*/
@Override
public void setWorkingTime (java.math.BigDecimal WorkingTime)
{
set_Value (COLUMNNAME_WorkingTime, WorkingTime);
}
/** Get Working Time.
@return Workflow Simulation Execution Time
*/
@Override
public java.math.BigDecimal getWorkingTime ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WorkingTime);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Yield %.
@param Yield
The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent
*/
@Override
public void setYield (int Yield)
{
set_Value (COLUMNNAME_Yield, Integer.valueOf(Yield));
}
/** Get Yield %.
@return The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent
*/
@Override
public int getYield ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_Yield);
if (ii == null)
return 0;
return ii.intValue();
}
@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\de\metas\product\model\X_M_Product_PlanningSchema.java
| 1
|
请完成以下Java代码
|
public BigDecimal getQtyFree()
{
final Capacity capacityAvailable = itemStorage.getAvailableCapacity(getProductId(), getC_UOM(), date);
if (capacityAvailable.isInfiniteCapacity())
{
return Quantity.QTY_INFINITE;
}
return capacityAvailable.toBigDecimal();
}
@Override
public Quantity getQty()
{
return itemStorage.getQuantity(getProductId(), getC_UOM());
}
@Override
public final Quantity getQty(final I_C_UOM uom)
{
final ProductId productId = getProductId();
final Quantity qty = getQty();
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
final UOMConversionContext conversionCtx= UOMConversionContext.of(productId);
return uomConversionBL.convertQuantityTo(qty, conversionCtx, uom);
}
@Override
public BigDecimal getQtyCapacity()
{
final Capacity capacityTotal = getTotalCapacity();
return capacityTotal.toBigDecimal();
}
@Override
public IAllocationRequest addQty(final IAllocationRequest request)
{
return itemStorage.requestQtyToAllocate(request);
}
@Override
public IAllocationRequest removeQty(final IAllocationRequest request)
|
{
return itemStorage.requestQtyToDeallocate(request);
}
@Override
public void markStaled()
{
// nothing, so far, itemStorage is always database coupled, no in memory values
}
@Override
public boolean isEmpty()
{
return itemStorage.isEmpty(getProductId());
}
@Override
public boolean isAllowNegativeStorage()
{
return itemStorage.isAllowNegativeStorage();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUItemProductStorage.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder ("X_M_PropertiesConfig[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Properties Configuration.
@param M_PropertiesConfig_ID Properties Configuration */
@Override
public void setM_PropertiesConfig_ID (int M_PropertiesConfig_ID)
{
if (M_PropertiesConfig_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PropertiesConfig_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PropertiesConfig_ID, Integer.valueOf(M_PropertiesConfig_ID));
}
/** Get Properties Configuration.
@return Properties Configuration */
@Override
public int getM_PropertiesConfig_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PropertiesConfig_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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 Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PropertiesConfig.java
| 1
|
请完成以下Java代码
|
public TbQueueProducer<TbProtoQueueMsg<ToRuleEngineMsg>> createRuleEngineMsgProducer() {
return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(transportApiSettings.getRequestsTopic()));
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCoreMsg>> createTbCoreMsgProducer() {
return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getTopic()));
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCoreNotificationMsg>> createTbCoreNotificationsMsgProducer() {
return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getTopic()));
}
@Override
|
public TbQueueConsumer<TbProtoQueueMsg<ToTransportMsg>> createTransportNotificationsConsumer() {
return new InMemoryTbQueueConsumer<>(storage, topicService.buildTopicName(transportNotificationSettings.getNotificationsTopic() + "." + serviceInfoProvider.getServiceId()));
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToUsageStatsServiceMsg>> createToUsageStatsServiceMsgProducer() {
return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getUsageStatsTopic()));
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToHousekeeperServiceMsg>> createHousekeeperMsgProducer() {
return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getHousekeeperTopic()));
}
}
|
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\InMemoryTbTransportQueueFactory.java
| 1
|
请完成以下Java代码
|
public class Personne {
private String nom;
private String surnom;
private int age;
public Personne() {
}
public Personne(String nom, String surnom, int age) {
super();
this.nom = nom;
this.surnom = surnom;
this.age = age;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getSurnom() {
|
return surnom;
}
public void setSurnom(String surnom) {
this.surnom = surnom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
repos\tutorials-master\libraries-data\src\main\java\com\baeldung\dozer\Personne.java
| 1
|
请完成以下Java代码
|
public class PrintJobInstructionsConfirm implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -9040749090880603823L;
private String printJobInstructionsID;
private String errorMsg;
private PrintJobInstructionsStatusEnum status;
public String getPrintJobInstructionsID()
{
return printJobInstructionsID;
}
public void setPrintJobInstructionsID(String printJobInstructionsID)
{
this.printJobInstructionsID = printJobInstructionsID;
}
public String getErrorMsg()
{
return errorMsg;
}
public void setErrorMsg(String errorMsg)
{
this.errorMsg = errorMsg;
}
public PrintJobInstructionsStatusEnum getStatus()
{
return status;
}
public void setStatus(PrintJobInstructionsStatusEnum status)
{
this.status = status;
}
@Override
public String toString()
{
return "PrintJobInstructionsConfirm [printJobInstructionsID=" + printJobInstructionsID + ", errorMsg=" + errorMsg + ", status=" + status + "]";
}
|
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((errorMsg == null) ? 0 : errorMsg.hashCode());
result = prime * result + ((printJobInstructionsID == null) ? 0 : printJobInstructionsID.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrintJobInstructionsConfirm other = (PrintJobInstructionsConfirm)obj;
if (errorMsg == null)
{
if (other.errorMsg != null)
return false;
}
else if (!errorMsg.equals(other.errorMsg))
return false;
if (printJobInstructionsID == null)
{
if (other.printJobInstructionsID != null)
return false;
}
else if (!printJobInstructionsID.equals(other.printJobInstructionsID))
return false;
if (status != other.status)
return false;
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintJobInstructionsConfirm.java
| 1
|
请完成以下Java代码
|
public void onReportingPeriodEnd() {
log.debug("Going to end reporting period.");
for (Map.Entry<Key, ActivityStateWrapper> entry : states.entrySet()) {
Key key = entry.getKey();
ActivityStateWrapper stateWrapper = entry.getValue();
try {
reportLastEvent(key, stateWrapper);
} catch (Exception e) {
log.error("Failed to report last activity event on reporting period end for key: [{}]. State: [{}].", key, stateWrapper, e);
}
}
}
private void reportLastEvent(Key key, ActivityStateWrapper stateWrapper) {
var currentState = stateWrapper.getState();
long lastRecordedTime = currentState.getLastRecordedTime();
long lastReportedTime = stateWrapper.getLastReportedTime();
var metadata = currentState.getMetadata();
boolean hasExpired;
boolean shouldReport;
var updatedState = updateState(key, currentState);
if (updatedState != null) {
stateWrapper.setState(updatedState);
lastRecordedTime = updatedState.getLastRecordedTime();
metadata = updatedState.getMetadata();
hasExpired = hasExpired(lastRecordedTime);
shouldReport = stateWrapper.getStrategy().onReportingPeriodEnd();
} else {
states.remove(key);
hasExpired = false;
shouldReport = true;
}
if (hasExpired) {
states.remove(key);
onStateExpiry(key, metadata);
shouldReport = true;
}
if (shouldReport && lastReportedTime < lastRecordedTime) {
long timeToReport = lastRecordedTime;
|
log.debug("Going to report last activity event for key: [{}]. Event time: [{}].", key, timeToReport);
reportActivity(key, metadata, timeToReport, new ActivityReportCallback<>() {
@Override
public void onSuccess(Key key, long reportedTime) {
updateLastReportedTime(key, reportedTime);
}
@Override
public void onFailure(Key key, Throwable t) {
log.debug("Failed to report last activity event for key: [{}]. Event time: [{}].", key, timeToReport, t);
}
});
}
}
@Override
public long getLastRecordedTime(Key key) {
ActivityStateWrapper stateWrapper = states.get(key);
return stateWrapper == null ? 0L : stateWrapper.getState().getLastRecordedTime();
}
private void updateLastReportedTime(Key key, long newLastReportedTime) {
states.computeIfPresent(key, (__, stateWrapper) -> {
stateWrapper.setLastReportedTime(Math.max(stateWrapper.getLastReportedTime(), newLastReportedTime));
return stateWrapper;
});
}
}
|
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\activity\AbstractActivityManager.java
| 1
|
请完成以下Java代码
|
private Mono<Boolean> findLeakedPassword(String encodedPassword) {
String prefix = encodedPassword.substring(0, PREFIX_LENGTH).toUpperCase(Locale.ROOT);
String suffix = encodedPassword.substring(PREFIX_LENGTH).toUpperCase(Locale.ROOT);
return getLeakedPasswordsForPrefix(prefix).any((leakedPw) -> leakedPw.startsWith(suffix));
}
private Flux<String> getLeakedPasswordsForPrefix(String prefix) {
return this.webClient.get().uri(prefix).retrieve().bodyToMono(String.class).flatMapMany((body) -> {
if (StringUtils.hasText(body)) {
return Flux.fromStream(body.lines());
}
return Flux.empty();
})
.doOnError((ex) -> this.logger.error("Request for leaked passwords failed", ex))
.onErrorResume(WebClientResponseException.class, (ex) -> Flux.empty());
}
/**
* Sets the {@link WebClient} to use when making requests to Have I Been Pwned REST
* API. By default, a {@link WebClient} with a base URL of {@link #API_URL} is used.
* @param webClient the {@link WebClient} to use
*/
public void setWebClient(WebClient webClient) {
Assert.notNull(webClient, "webClient cannot be null");
|
this.webClient = webClient;
}
private Mono<byte[]> getHash(@Nullable String rawPassword) {
return Mono.justOrEmpty(rawPassword)
.map((password) -> this.sha1Digest.digest(password.getBytes(StandardCharsets.UTF_8)))
.subscribeOn(Schedulers.boundedElastic())
.publishOn(Schedulers.parallel());
}
private static MessageDigest getSha1Digest() {
try {
return MessageDigest.getInstance("SHA-1");
}
catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex.getMessage());
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\password\HaveIBeenPwnedRestApiReactivePasswordChecker.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/login*", "/signin/**", "/signup/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout();
return http.build();
}
@Bean
// @Primary
public ProviderSignInController providerSignInController() {
|
ConnectionFactoryLocator connectionFactoryLocator = connectionFactoryLocator();
UsersConnectionRepository usersConnectionRepository = getUsersConnectionRepository(connectionFactoryLocator);
((InMemoryUsersConnectionRepository) usersConnectionRepository).setConnectionSignUp(facebookConnectionSignup);
return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new FacebookSignInAdapter());
}
private ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new FacebookConnectionFactory(appId, appSecret));
return registry;
}
private UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
return new InMemoryUsersConnectionRepository(connectionFactoryLocator);
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-social-login\src\main\java\com\baeldung\config\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public int getK_Topic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Topic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Rating.
@param Rating
Classification or Importance
*/
public void setRating (int Rating)
{
set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating));
}
/** Get Rating.
@return Classification or Importance
*/
public int getRating ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Rating);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
|
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Entry.java
| 1
|
请完成以下Java代码
|
public class OAuth2AuthorizationCodeGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
private final OAuth2AuthorizationExchange authorizationExchange;
/**
* Constructs an {@code OAuth2AuthorizationCodeGrantRequest} using the provided
* parameters.
* @param clientRegistration the client registration
* @param authorizationExchange the authorization exchange
*/
public OAuth2AuthorizationCodeGrantRequest(ClientRegistration clientRegistration,
OAuth2AuthorizationExchange authorizationExchange) {
super(AuthorizationGrantType.AUTHORIZATION_CODE, clientRegistration);
Assert.notNull(authorizationExchange, "authorizationExchange cannot be null");
this.authorizationExchange = authorizationExchange;
}
/**
* Returns the {@link OAuth2AuthorizationExchange authorization exchange}.
* @return the {@link OAuth2AuthorizationExchange}
*/
public OAuth2AuthorizationExchange getAuthorizationExchange() {
return this.authorizationExchange;
}
/**
* Populate default parameters for the Authorization Code Grant.
* @param grantRequest the authorization grant request
* @return a {@link MultiValueMap} of the parameters used in the OAuth 2.0 Access
* Token Request body
|
*/
static MultiValueMap<String, String> defaultParameters(OAuth2AuthorizationCodeGrantRequest grantRequest) {
OAuth2AuthorizationExchange authorizationExchange = grantRequest.getAuthorizationExchange();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames.CODE, authorizationExchange.getAuthorizationResponse().getCode());
String redirectUri = authorizationExchange.getAuthorizationRequest().getRedirectUri();
if (redirectUri != null) {
parameters.set(OAuth2ParameterNames.REDIRECT_URI, redirectUri);
}
String codeVerifier = authorizationExchange.getAuthorizationRequest()
.getAttribute(PkceParameterNames.CODE_VERIFIER);
if (codeVerifier != null) {
parameters.set(PkceParameterNames.CODE_VERIFIER, codeVerifier);
}
return parameters;
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\endpoint\OAuth2AuthorizationCodeGrantRequest.java
| 1
|
请完成以下Java代码
|
public class CopyFromOrder extends JavaProcess
{
/** The Order */
private int p_C_Order_ID = 0;
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("C_Order_ID"))
p_C_Order_ID = ((BigDecimal)para[i].getParameter()).intValue();
else
log.error("Unknown Parameter: " + name);
}
} // prepare
/**
* Perform process.
* @return Message (clear text)
* @throws Exception if not successful
|
*/
protected String doIt() throws Exception
{
int To_C_Order_ID = getRecord_ID();
log.info("From C_Order_ID=" + p_C_Order_ID + " to " + To_C_Order_ID);
if (To_C_Order_ID == 0)
throw new IllegalArgumentException("Target C_Order_ID == 0");
if (p_C_Order_ID == 0)
throw new IllegalArgumentException("Source C_Order_ID == 0");
MOrder from = new MOrder (getCtx(), p_C_Order_ID, get_TrxName());
MOrder to = new MOrder (getCtx(), To_C_Order_ID, get_TrxName());
//
int no = to.copyLinesFrom (from, false, false); // no Attributes
//
return "@Copied@=" + no;
} // doIt
} // CopyFromOrder
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\CopyFromOrder.java
| 1
|
请完成以下Java代码
|
public static Component searchComponent(Container parent, Class<?> clazz, boolean remove) {
Container con = parent;
Component retVal = null;
Component c = null;
for(int i = 0; i < con.getComponentCount(); i++) {
c = con.getComponent(i);
//Found the given class and breaks the loop
if(clazz.isInstance(c)) {
if(remove) {
con.remove(c);
}
return c;
}
//Recursively calling this method to search in deep
if(c instanceof Container) {
c = searchComponent((Container)c , clazz, remove);
if(clazz.isInstance(c)) {
if(remove) {
con.remove(retVal);
}
return c;
}
}
}
return null;
}
public static void addOpaque(JComponent c, final boolean opaque) {
ContainerAdapter ca = new ContainerAdapter() {
@Override
public void componentAdded(ContainerEvent e) {
setOpaque(e.getChild());
}
private void setOpaque(Component c) {
//ignores all selectable items, like buttons
if(c instanceof ItemSelectable) {
return;
}
// sets transparent
else if(c instanceof JComponent) {
((JComponent)c).setOpaque(opaque);
}
// recursively calls this method for all container components
else if(c instanceof Container) {
for(int i = 0; i > ((Container)c).getComponentCount(); i++) {
setOpaque(((Container)c).getComponent(i));
}
}
|
}
};
c.addContainerListener(ca);
}
public static KeyStroke getKeyStrokeFor(String name, List<KeyStroke> usedStrokes) {
return (name == null) ? null : getKeyStrokeFor(name.charAt(0), usedStrokes);
}
public static KeyStroke getKeyStrokeFor(char c, List<KeyStroke> usedStrokes) {
int m = Event.CTRL_MASK;
KeyStroke o = null;
for(Iterator<?> i = usedStrokes.iterator(); i.hasNext();) {
o = (KeyStroke)i.next();
if(c == o.getKeyChar()) {
if(c == o.getKeyChar()) {
if(o.getModifiers() != Event.SHIFT_MASK+Event.CTRL_MASK) {
m = Event.SHIFT_MASK+Event.CTRL_MASK;
}
else if(o.getModifiers() != Event.SHIFT_MASK+Event.ALT_MASK) {
m = Event.SHIFT_MASK+Event.ALT_MASK;
}
else {
m = -1;
}
}
}
}
KeyStroke s = null;
if(m != -1) {
s = KeyStroke.getKeyStroke(c, m);
usedStrokes.add(s);
}
return s;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\tools\swing\SwingTool.java
| 1
|
请完成以下Java代码
|
private TsKvEntry convertResultToTsKvEntry(Row row) {
String key = row.getString(ModelConstants.KEY_COLUMN);
long ts = row.getLong(ModelConstants.TS_COLUMN);
return new BasicTsKvEntry(ts, toKvEntry(row, key));
}
protected TsKvEntry convertResultToTsKvEntry(String key, Row row) {
if (row != null) {
return getBasicTsKvEntry(key, row);
} else {
return new BasicTsKvEntry(System.currentTimeMillis(), new StringDataEntry(key, null));
}
}
protected Optional<TsKvEntry> convertResultToTsKvEntryOpt(String key, Row row) {
if (row != null) {
return Optional.of(getBasicTsKvEntry(key, row));
} else {
return Optional.empty();
|
}
}
private BasicTsKvEntry getBasicTsKvEntry(String key, Row row) {
Optional<String> foundKeyOpt = getKey(row);
long ts = row.getLong(ModelConstants.TS_COLUMN);
return new BasicTsKvEntry(ts, toKvEntry(row, foundKeyOpt.orElse(key)));
}
private Optional<String> getKey(Row row){
try{
return Optional.ofNullable(row.getString(ModelConstants.KEY_COLUMN));
} catch (IllegalArgumentException e){
return Optional.empty();
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\AbstractCassandraBaseTimeseriesDao.java
| 1
|
请完成以下Java代码
|
public boolean isAnyComponentIssue(@Nullable final PPOrderBOMLineId orderBOMLineId)
{
return isComponentIssue()
|| isMaterialMethodChangeVariance(orderBOMLineId);
}
public boolean isActivityControl()
{
return this == ActivityControl;
}
public boolean isVariance()
{
return this == MethodChangeVariance
|| this == UsageVariance
|| this == RateVariance
|| this == MixVariance;
}
public boolean isCoOrByProductReceipt()
{
return this == MixVariance;
}
public boolean isUsageVariance()
{
return this == UsageVariance;
}
public boolean isMaterialUsageVariance(@Nullable final PPOrderBOMLineId orderBOMLineId)
{
return this == UsageVariance && orderBOMLineId != null;
}
public boolean isResourceUsageVariance(@Nullable final PPOrderRoutingActivityId activityId)
|
{
return this == UsageVariance && activityId != null;
}
public boolean isRateVariance()
{
return this == RateVariance;
}
public boolean isMethodChangeVariance()
{
return this == MethodChangeVariance;
}
public boolean isMaterialMethodChangeVariance(@Nullable final PPOrderBOMLineId orderBOMLineId)
{
return this == MethodChangeVariance && orderBOMLineId != null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\CostCollectorType.java
| 1
|
请完成以下Java代码
|
private void setupInfoColumnControllerBindings()
{
for (int i = 0; i < p_layout.length; i++)
{
final int columnIndexModel = i;
final Info_Column infoColumn = p_layout[columnIndexModel];
final IInfoColumnController columnController = infoColumn.getColumnController();
final List<Info_Column> dependentColumns = infoColumn.getDependentColumns();
if (columnController == null
&& (dependentColumns == null || dependentColumns.isEmpty()))
{
// if there is no controller on this column and there are no dependent columns
// then there is no point for adding a binder
continue;
}
final TableModel tableModel = getTableModel();
final InfoColumnControllerBinder binder = new InfoColumnControllerBinder(this, infoColumn, columnIndexModel);
tableModel.addTableModelListener(binder);
}
}
@Override
public void setValue(final Info_Column infoColumn, final int rowIndexModel, final Object value)
|
{
final int colIndexModel = getColumnIndex(infoColumn);
if (colIndexModel < 0)
{
return;
}
p_table.setValueAt(value, rowIndexModel, colIndexModel);
}
@Override
public void setValueByColumnName(final String columnName, final int rowIndexModel, final Object value)
{
final int colIndexModel = getColumnIndex(columnName);
if (colIndexModel < 0)
{
return;
}
p_table.setValueAt(value, rowIndexModel, colIndexModel);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\InfoSimple.java
| 1
|
请完成以下Java代码
|
public class X_C_Async_Batch_Type extends org.compiere.model.PO implements I_C_Async_Batch_Type, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 851172719L;
/** Standard Constructor */
public X_C_Async_Batch_Type (final Properties ctx, final int C_Async_Batch_Type_ID, @Nullable final String trxName)
{
super (ctx, C_Async_Batch_Type_ID, trxName);
}
/** Load Constructor */
public X_C_Async_Batch_Type (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_BoilerPlate_ID (final int AD_BoilerPlate_ID)
{
if (AD_BoilerPlate_ID < 1)
set_Value (COLUMNNAME_AD_BoilerPlate_ID, null);
else
set_Value (COLUMNNAME_AD_BoilerPlate_ID, AD_BoilerPlate_ID);
}
@Override
public int getAD_BoilerPlate_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BoilerPlate_ID);
}
@Override
public void setC_Async_Batch_Type_ID (final int C_Async_Batch_Type_ID)
{
if (C_Async_Batch_Type_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Async_Batch_Type_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Async_Batch_Type_ID, C_Async_Batch_Type_ID);
}
@Override
public int getC_Async_Batch_Type_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Async_Batch_Type_ID);
}
@Override
public void setInternalName (final String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
@Override
public String getInternalName()
|
{
return get_ValueAsString(COLUMNNAME_InternalName);
}
@Override
public void setKeepAliveTimeHours (final @Nullable String KeepAliveTimeHours)
{
set_Value (COLUMNNAME_KeepAliveTimeHours, KeepAliveTimeHours);
}
@Override
public String getKeepAliveTimeHours()
{
return get_ValueAsString(COLUMNNAME_KeepAliveTimeHours);
}
/**
* NotificationType AD_Reference_ID=540643
* Reference name: _NotificationType
*/
public static final int NOTIFICATIONTYPE_AD_Reference_ID=540643;
/** Async Batch Processed = ABP */
public static final String NOTIFICATIONTYPE_AsyncBatchProcessed = "ABP";
/** Workpackage Processed = WPP */
public static final String NOTIFICATIONTYPE_WorkpackageProcessed = "WPP";
@Override
public void setNotificationType (final @Nullable String NotificationType)
{
set_Value (COLUMNNAME_NotificationType, NotificationType);
}
@Override
public String getNotificationType()
{
return get_ValueAsString(COLUMNNAME_NotificationType);
}
@Override
public void setSkipTimeoutMillis (final int SkipTimeoutMillis)
{
set_Value (COLUMNNAME_SkipTimeoutMillis, SkipTimeoutMillis);
}
@Override
public int getSkipTimeoutMillis()
{
return get_ValueAsInt(COLUMNNAME_SkipTimeoutMillis);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch_Type.java
| 1
|
请完成以下Java代码
|
public BpmnDiagram newInstance(ModelTypeInstanceContext instanceContext) {
return new BpmnDiagramImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
bpmnPlaneChild = sequenceBuilder.element(BpmnPlane.class)
.required()
.build();
bpmnLabelStyleCollection = sequenceBuilder.elementCollection(BpmnLabelStyle.class)
.build();
typeBuilder.build();
}
public BpmnDiagramImpl(ModelTypeInstanceContext instanceContext) {
|
super(instanceContext);
}
public BpmnPlane getBpmnPlane() {
return bpmnPlaneChild.getChild(this);
}
public void setBpmnPlane(BpmnPlane bpmnPlane) {
bpmnPlaneChild.setChild(this, bpmnPlane);
}
public Collection<BpmnLabelStyle> getBpmnLabelStyles() {
return bpmnLabelStyleCollection.get(this);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\bpmndi\BpmnDiagramImpl.java
| 1
|
请完成以下Java代码
|
public AggregationKey buildAggregationKey(I_C_Invoice_Candidate model)
{
final List<Object> keyValues = getValues(model);
final ArrayKey key = Util.mkKey(keyValues.toArray());
final AggregationId aggregationId = null;
return new AggregationKey(key, aggregationId);
}
private List<Object> getValues(@NonNull final I_C_Invoice_Candidate ic)
{
final List<Object> values = new ArrayList<>();
final I_C_DocType invoiceDocType = Optional.ofNullable(DocTypeId.ofRepoIdOrNull(ic.getC_DocTypeInvoice_ID()))
.map(docTypeBL::getById)
.orElse(null);
final DocTypeId docTypeIdToBeUsed = Optional.ofNullable(invoiceDocType)
.filter(docType -> docType.getC_DocType_Invoicing_Pool_ID() <= 0)
.map(I_C_DocType::getC_DocType_ID)
.map(DocTypeId::ofRepoId)
.orElse(null);
values.add(docTypeIdToBeUsed);
values.add(ic.getAD_Org_ID());
final BPartnerLocationAndCaptureId billLocation = invoiceCandBL.getBillLocationId(ic, false);
values.add(billLocation.getBpartnerRepoId());
values.add(billLocation.getBPartnerLocationRepoId());
final int currencyId = ic.getC_Currency_ID();
values.add(currencyId <= 0 ? 0 : currencyId);
// Dates
// 08511 workaround - we don't add dates in header aggregation key
values.add(null); // ic.getDateInvoiced());
values.add(null); // ic.getDateAcct()); // task 08437
// IsSOTrx
values.add(ic.isSOTrx());
// Pricing System
|
final int pricingSystemId = IPriceListDAO.M_PricingSystem_ID_None; // 08511 workaround
values.add(pricingSystemId);
values.add(invoiceCandBL.isTaxIncluded(ic)); // task 08451
final Boolean compact = true;
values.add(compact ? toHashcode(ic.getDescriptionHeader()) : ic.getDescriptionHeader());
values.add(compact ? toHashcode(ic.getDescriptionBottom()) : ic.getDescriptionBottom());
final DocTypeInvoicingPoolId docTypeInvoicingPoolId = Optional.ofNullable(invoiceDocType)
.filter(docType -> docType.getC_DocType_Invoicing_Pool_ID() > 0)
.map(I_C_DocType::getC_DocType_Invoicing_Pool_ID)
.map(DocTypeInvoicingPoolId::ofRepoId)
.orElse(null);
values.add(docTypeInvoicingPoolId);
return values;
}
private static int toHashcode(final String s)
{
if (Check.isEmpty(s, true))
{
return 0;
}
return s.hashCode();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\agg\key\impl\ICHeaderAggregationKeyBuilder_OLD.java
| 1
|
请完成以下Java代码
|
public ListenableFuture<Integer> getCartId() {
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return new Random().nextInt(Integer.MAX_VALUE);
});
}
public ListenableFuture<String> getCustomerName() {
String[] names = new String[] { "Mark", "Jane", "June" };
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return names[new Random().nextInt(names.length)];
});
}
public ListenableFuture<List<String>> getCartItems() {
String[] items = new String[] { "Apple", "Orange", "Mango", "Pineapple" };
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
int noOfItems = new Random().nextInt(items.length);
if (noOfItems == 0) ++noOfItems;
return Arrays.stream(items, 0, noOfItems).collect(Collectors.toList());
});
}
|
public ListenableFuture<String> generateUsername(String firstName) {
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return firstName.replaceAll("[^a-zA-Z]+","")
.concat("@service.com");
});
}
public ListenableFuture<String> generatePassword(String username) {
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
if (username.contains("@")) {
String[] parts = username.split("@");
return parts[0] + "123@" + parts[1];
} else {
return username + "123";
}
});
}
}
|
repos\tutorials-master\guava-modules\guava-concurrency\src\main\java\com\baeldung\guava\future\ListenableFutureService.java
| 1
|
请完成以下Java代码
|
public List<Comment> findCommentsByProcessInstanceId(String processInstanceId) {
checkHistoryEnabled();
return commentDataManager.findCommentsByProcessInstanceId(processInstanceId);
}
@Override
public List<Comment> findCommentsByProcessInstanceId(String processInstanceId, String type) {
checkHistoryEnabled();
return commentDataManager.findCommentsByProcessInstanceId(processInstanceId, type);
}
@Override
public Comment findComment(String commentId) {
return commentDataManager.findComment(commentId);
}
@Override
public Event findEvent(String commentId) {
return commentDataManager.findEvent(commentId);
}
@Override
public void delete(CommentEntity commentEntity) {
checkHistoryEnabled();
delete(commentEntity, false);
Comment comment = (Comment) commentEntity;
if (getEventDispatcher().isEnabled()) {
// Forced to fetch the process-instance to associate the right
// process definition
String processDefinitionId = null;
String processInstanceId = comment.getProcessInstanceId();
if (comment.getProcessInstanceId() != null) {
ExecutionEntity process = getExecutionEntityManager().findById(comment.getProcessInstanceId());
if (process != null) {
|
processDefinitionId = process.getProcessDefinitionId();
}
}
getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(
ActivitiEventType.ENTITY_DELETED,
commentEntity,
processInstanceId,
processInstanceId,
processDefinitionId
)
);
}
}
protected void checkHistoryEnabled() {
if (!getHistoryManager().isHistoryEnabled()) {
throw new ActivitiException("In order to use comments, history should be enabled");
}
}
public CommentDataManager getCommentDataManager() {
return commentDataManager;
}
public void setCommentDataManager(CommentDataManager commentDataManager) {
this.commentDataManager = commentDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\CommentEntityManagerImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public long setAdd(String key, Object... values) {
return setOperations.add(key, values);
}
public long setAdd(String key, long milliseconds, Object... values) {
Long count = setOperations.add(key, values);
if (milliseconds > 0) {
expire(key, milliseconds);
}
return count;
}
public long setSize(String key) {
return setOperations.size(key);
}
public long setRemove(String key, Object... values) {
return setOperations.remove(key, values);
}
//===============================list=================================
public List<Object> lGet(String key, long start, long end) {
return listOperations.range(key, start, end);
}
public long listSize(String key) {
return listOperations.size(key);
}
public Object listIndex(String key, long index) {
return listOperations.index(key, index);
}
public void listRightPush(String key, Object value) {
listOperations.rightPush(key, value);
}
|
public boolean listRightPush(String key, Object value, long milliseconds) {
listOperations.rightPush(key, value);
if (milliseconds > 0) {
return expire(key, milliseconds);
}
return false;
}
public long listRightPushAll(String key, List<Object> value) {
return listOperations.rightPushAll(key, value);
}
public boolean listRightPushAll(String key, List<Object> value, long milliseconds) {
listOperations.rightPushAll(key, value);
if (milliseconds > 0) {
return expire(key, milliseconds);
}
return false;
}
public void listSet(String key, long index, Object value) {
listOperations.set(key, index, value);
}
public long listRemove(String key, long count, Object value) {
return listOperations.remove(key, count, value);
}
//===============================zset=================================
public boolean zsAdd(String key, Object value, double score) {
return zSetOperations.add(key, value, score);
}
}
|
repos\spring-boot-best-practice-master\spring-boot-redis\src\main\java\cn\javastack\springboot\redis\service\RedisOptService.java
| 2
|
请完成以下Java代码
|
protected BigDecimalStringExpression createGeneralExpression(final ExpressionContext context, final String expressionStr, final List<Object> expressionChunks)
{
return new GeneralExpression(context, this, expressionStr, expressionChunks);
}
});
}
private static final class BigDecimalValueConverter implements ValueConverter<BigDecimal, BigDecimalStringExpression>
{
@Override
public BigDecimal convertFrom(final Object valueObj, final ExpressionContext options)
{
if (valueObj == null)
{
return null;
}
else if (valueObj instanceof BigDecimal)
{
return (BigDecimal)valueObj;
}
else if (valueObj instanceof Integer)
{
return BigDecimal.valueOf((Integer)valueObj);
}
else
{
String valueStr = valueObj.toString();
if (valueStr == null)
{
return null; // shall not happen
}
valueStr = valueStr.trim();
return new BigDecimal(valueStr);
}
}
}
private static final class NullExpression extends NullExpressionTemplate<BigDecimal, BigDecimalStringExpression>implements BigDecimalStringExpression
{
public NullExpression(final Compiler<BigDecimal, BigDecimalStringExpression> compiler)
{
super(compiler);
}
}
private static final class ConstantExpression extends ConstantExpressionTemplate<BigDecimal, BigDecimalStringExpression>implements BigDecimalStringExpression
{
|
public ConstantExpression(final Compiler<BigDecimal, BigDecimalStringExpression> compiler, final String expressionStr, final BigDecimal constantValue)
{
super(ExpressionContext.EMPTY, compiler, expressionStr, constantValue);
}
}
private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<BigDecimal, BigDecimalStringExpression>implements BigDecimalStringExpression
{
public SingleParameterExpression(final ExpressionContext context, final Compiler<BigDecimal, BigDecimalStringExpression> compiler, final String expressionStr, final CtxName parameter)
{
super(context, compiler, expressionStr, parameter);
}
@Override
protected Object extractParameterValue(final Evaluatee ctx)
{
return parameter.getValueAsBigDecimal(ctx);
}
}
private static final class GeneralExpression extends GeneralExpressionTemplate<BigDecimal, BigDecimalStringExpression>implements BigDecimalStringExpression
{
public GeneralExpression(final ExpressionContext context, final Compiler<BigDecimal, BigDecimalStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks)
{
super(context, compiler, expressionStr, expressionChunks);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\BigDecimalStringExpressionSupport.java
| 1
|
请完成以下Java代码
|
public XMLGregorianCalendar getCreDtTm() {
return creDtTm;
}
/**
* Sets the value of the creDtTm property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setCreDtTm(XMLGregorianCalendar value) {
this.creDtTm = value;
}
/**
* Gets the value of the nbOfTxs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNbOfTxs() {
return nbOfTxs;
}
/**
* Sets the value of the nbOfTxs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNbOfTxs(String value) {
this.nbOfTxs = value;
}
/**
* Gets the value of the ctrlSum property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getCtrlSum() {
return ctrlSum;
}
/**
* Sets the value of the ctrlSum property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
|
*/
public void setCtrlSum(BigDecimal value) {
this.ctrlSum = value;
}
/**
* Gets the value of the initgPty property.
*
* @return
* possible object is
* {@link PartyIdentification32CHNameAndId }
*
*/
public PartyIdentification32CHNameAndId getInitgPty() {
return initgPty;
}
/**
* Sets the value of the initgPty property.
*
* @param value
* allowed object is
* {@link PartyIdentification32CHNameAndId }
*
*/
public void setInitgPty(PartyIdentification32CHNameAndId value) {
this.initgPty = value;
}
/**
* Gets the value of the fwdgAgt property.
*
* @return
* possible object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public BranchAndFinancialInstitutionIdentification4 getFwdgAgt() {
return fwdgAgt;
}
/**
* Sets the value of the fwdgAgt property.
*
* @param value
* allowed object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public void setFwdgAgt(BranchAndFinancialInstitutionIdentification4 value) {
this.fwdgAgt = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\GroupHeader32CH.java
| 1
|
请完成以下Java代码
|
private void updateShipmentFromResponse(@NonNull final ShipmentSchedule shipmentSchedule, @NonNull final JsonDeliveryAdvisorResponse response)
{
if (response.isError())
{
shipmentSchedule.setCarrierAdviseErrorMessage(response.getErrorMessage());
updateAdviseStatusAndSave(shipmentSchedule, CarrierAdviseStatus.Failed);
}
else
{
final JsonShipperProduct shipperProduct = response.getShipperProduct();
if (shipperProduct != null)
{
shipmentSchedule.setCarrierProductId(extractCarrierProductId(Objects.requireNonNull(shipmentSchedule.getShipperId()), shipperProduct));
}
final ShipperId shipperId = Check.assumeNotNull(shipmentSchedule.getShipperId(), "Shipment Schedule ShipperId should be set at this point");
final JsonGoodsType goodsType = Check.assumeNotNull(response.getGoodsType(), "response goods type should be set at not error case");
shipmentSchedule.setCarrierGoodsTypeId(extractCarrierGoodsTypeId(shipperId, goodsType));
shipmentSchedule.setCarrierServices(extractCarrierServiceIds(shipmentSchedule.getShipperId(), response.getShipperProductServices()));
updateAdviseStatusAndSave(shipmentSchedule, CarrierAdviseStatus.Completed);
}
}
private @NonNull Set<CarrierServiceId> extractCarrierServiceIds(@NonNull final ShipperId shipperId, final @NonNull Set<JsonCarrierService> shipperProductServices)
{
return shipperProductServices.stream()
.map(service -> carrierServiceRepository.getOrCreateService(shipperId, service.getId(), service.getName()))
.map(CarrierService::getId)
.collect(Collectors.toSet());
}
|
@NonNull
private CarrierGoodsTypeId extractCarrierGoodsTypeId(@NonNull final ShipperId shipperId, final @NonNull JsonGoodsType jsonGoodsType)
{
final CarrierGoodsType goodsType = goodsTypeRepository.getOrCreateGoodsType(shipperId, jsonGoodsType.getId(), jsonGoodsType.getName());
return goodsType.getId();
}
@NonNull
private CarrierProductId extractCarrierProductId(@NonNull final ShipperId shipperId, @NonNull final JsonShipperProduct shipperProduct)
{
final String name = shipperProduct.getName() != null ? shipperProduct.getName() : shipperProduct.getCode();
final CarrierProduct carrierProduct = carrierProductRepository.getOrCreateCarrierProduct(shipperId, shipperProduct.getCode(), name);
return carrierProduct.getId();
}
private void updateAdviseStatusAndSave(@NonNull final ShipmentSchedule shipmentSchedule, @NonNull final CarrierAdviseStatus status)
{
shipmentSchedule.setCarrierAdvisingStatus(status);
shipmentScheduleService.save(shipmentSchedule);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\CarrierAdviseCommand.java
| 1
|
请完成以下Java代码
|
public static String encode16(String password) {
return encode32(password).substring(8, 24);
}
/**
* 16位大写MD5签名值
* @param password
* @return
*/
public static String encode16ToUpperCase(String password) {
return encode32ToUpperCase(password).substring(8,24);
}
public static String encode(String password , String enc) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] byteArray = md5.digest(password.getBytes(enc));
String passwordMD5 = byteArrayToHexString(byteArray);
return passwordMD5;
} catch (Exception e) {
LOG.error(e.toString());
}
return password;
}
private static String byteArrayToHexString(byte[] byteArray) {
StringBuffer sb = new StringBuffer();
for (byte b : byteArray) {
sb.append(byteToHexChar(b));
}
return sb.toString();
}
|
private static Object byteToHexChar(byte b) {
int n = b;
if (n < 0) {
n = 256 + n;
}
int d1 = n / 16;
int d2 = n % 16;
return hex[d1] + hex[d2];
}
public static void main(String [] args ){
String ss = "test";
System.out.println(MD5Util.encode32(ss));
System.out.println(MD5Util.encode32ToUpperCase(ss));
System.out.println(MD5Util.encode16(ss));
System.out.println(MD5Util.encode16ToUpperCase(ss));
}
}
|
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\MD5Util.java
| 1
|
请完成以下Java代码
|
public boolean isInserted() {
return isInserted;
}
@Override
public void setInserted(boolean isInserted) {
this.isInserted = isInserted;
}
@Override
public boolean isUpdated() {
return isUpdated;
}
@Override
public void setUpdated(boolean isUpdated) {
this.isUpdated = isUpdated;
}
|
@Override
public boolean isDeleted() {
return isDeleted;
}
@Override
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
@Override
public Object getOriginalPersistentState() {
return originalPersistentState;
}
@Override
public void setOriginalPersistentState(Object persistentState) {
this.originalPersistentState = persistentState;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\AbstractEntityNoRevision.java
| 1
|
请完成以下Java代码
|
public String completeIt(final DocumentTableFields docFields)
{
final I_SAP_GLJournal glJournalRecord = extractRecord(docFields);
assertPeriodOpen(glJournalRecord);
glJournalService.updateWhileSaving(
glJournalRecord,
glJournal -> {
glJournal.assertHasLines();
glJournal.updateLineAcctAmounts(glJournalService.getCurrencyConverter());
glJournal.assertTotalsBalanced();
glJournal.setProcessed(true);
}
);
glJournalRecord.setDocAction(IDocument.ACTION_None);
return IDocument.STATUS_Completed;
}
private static void assertPeriodOpen(final I_SAP_GLJournal glJournalRecord)
{
MPeriod.testPeriodOpen(Env.getCtx(), glJournalRecord.getDateAcct(), glJournalRecord.getC_DocType_ID(), glJournalRecord.getAD_Org_ID());
}
|
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_SAP_GLJournal glJournalRecord = extractRecord(docFields);
assertPeriodOpen(glJournalRecord);
glJournalService.updateWhileSaving(
glJournalRecord,
glJournal -> glJournal.setProcessed(false)
);
factAcctDAO.deleteForDocumentModel(glJournalRecord);
glJournalRecord.setPosted(false);
glJournalRecord.setProcessed(false);
glJournalRecord.setDocAction(X_GL_Journal.DOCACTION_Complete);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\document\SAPGLJournalDocumentHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean refresh(final I_AD_Table_MView mview, final PO sourcePO, final RefreshMode refreshMode, final String trxName)
{
final boolean[] ok = new boolean[] { false };
Services.get(ITrxManager.class).run(trxName, new TrxRunnable2()
{
@Override
public void run(String trxName)
{
refreshEx(mview, sourcePO, refreshMode, trxName);
ok[0] = true;
}
@Override
public boolean doCatch(Throwable e)
{
// log the error, return true to rollback the transaction but don't throw it forward
log.error(e.getLocalizedMessage() + ", mview=" + mview + ", sourcePO=" + sourcePO + ", trxName=" + trxName, e);
ok[0] = false;
return true;
}
@Override
public void doFinally()
{
}
});
return ok[0];
}
@Override
|
public boolean isSourceChanged(MViewMetadata mdata, PO sourcePO, int changeType)
{
final String sourceTableName = sourcePO.get_TableName();
final Set<String> sourceColumns = mdata.getSourceColumns(sourceTableName);
if (sourceColumns == null || sourceColumns.isEmpty())
return false;
if (changeType == ModelValidator.TYPE_AFTER_NEW || changeType == ModelValidator.TYPE_AFTER_DELETE)
{
return true;
}
for (String sourceColumn : sourceColumns)
{
if (sourcePO.is_ValueChanged(sourceColumn))
{
return true;
}
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\TableMViewBL.java
| 2
|
请完成以下Java代码
|
private void addForParentTable(final ParentChildInfo info)
{
final String parentTableName = info.getParentTableName();
factoriesByTableName.put(parentTableName, DirectModelCacheInvalidateRequestFactory.instance);
// NOTE: always invalidate parent table name, even if info.isParentNeedsRemoteCacheInvalidation() is false
tableNamesToEnableRemoveCacheInvalidation.add(parentTableName);
}
private void addForChildTable(final ParentChildInfo info)
{
final String childTableName = info.getChildTableName();
if (childTableName == null || isBlank(childTableName))
{
return;
}
try
{
final ParentChildModelCacheInvalidateRequestFactory factory = info.toGenericModelCacheInvalidateRequestFactoryOrNull();
if (factory != null)
|
{
factoriesByTableName.put(childTableName, factory);
}
}
catch (final Exception ex)
{
logger.warn("Failed to create model cache invalidate for {}: {}", childTableName, info, ex);
}
if (info.isChildNeedsRemoteCacheInvalidation())
{
tableNamesToEnableRemoveCacheInvalidation.add(childTableName);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\WindowBasedModelCacheInvalidateRequestFactoryGroup.java
| 1
|
请完成以下Java代码
|
public int getEXP_FormatLine_ID()
{
return get_ValueAsInt(COLUMNNAME_EXP_FormatLine_ID);
}
/**
* FilterOperator AD_Reference_ID=541875
* Reference name: FilterOperator_for_EXP_FormatLine
*/
public static final int FILTEROPERATOR_AD_Reference_ID=541875;
/** Equals = E */
public static final String FILTEROPERATOR_Equals = "E";
/** Like = L */
public static final String FILTEROPERATOR_Like = "L";
@Override
public void setFilterOperator (final java.lang.String FilterOperator)
{
set_Value (COLUMNNAME_FilterOperator, FilterOperator);
}
@Override
public java.lang.String getFilterOperator()
{
return get_ValueAsString(COLUMNNAME_FilterOperator);
}
@Override
public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsMandatory (final boolean IsMandatory)
{
set_Value (COLUMNNAME_IsMandatory, IsMandatory);
}
@Override
public boolean isMandatory()
{
return get_ValueAsBoolean(COLUMNNAME_IsMandatory);
}
@Override
public void setIsPartUniqueIndex (final boolean IsPartUniqueIndex)
{
set_Value (COLUMNNAME_IsPartUniqueIndex, IsPartUniqueIndex);
}
@Override
public boolean isPartUniqueIndex()
{
return get_ValueAsBoolean(COLUMNNAME_IsPartUniqueIndex);
}
@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 setPosition (final int Position)
{
set_Value (COLUMNNAME_Position, Position);
}
@Override
public int getPosition()
{
return get_ValueAsInt(COLUMNNAME_Position);
}
/**
* Type AD_Reference_ID=53241
* Reference name: EXP_Line_Type
*/
public static final int TYPE_AD_Reference_ID=53241;
/** XML Element = E */
public static final String TYPE_XMLElement = "E";
/** XML Attribute = A */
public static final String TYPE_XMLAttribute = "A";
/** Embedded EXP Format = M */
public static final String TYPE_EmbeddedEXPFormat = "M";
/** Referenced EXP Format = R */
public static final String TYPE_ReferencedEXPFormat = "R";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_FormatLine.java
| 1
|
请完成以下Java代码
|
default List<URL> getAuthorizationServers() {
List<String> authorizationServers = getClaimAsStringList(
OAuth2ProtectedResourceMetadataClaimNames.AUTHORIZATION_SERVERS);
List<URL> urls = new ArrayList<>();
authorizationServers.forEach((authorizationServer) -> {
try {
urls.add(new URI(authorizationServer).toURL());
}
catch (Exception ex) {
throw new IllegalArgumentException("Failed to convert authorization_server to URL", ex);
}
});
return urls;
}
/**
* Returns a list of {@code scope} values supported, that are used in authorization
* requests to request access to this protected resource {@code (scopes_supported)}.
* @return a list of {@code scope} values supported, that are used in authorization
* requests to request access to this protected resource
*/
default List<String> getScopes() {
return getClaimAsStringList(OAuth2ProtectedResourceMetadataClaimNames.SCOPES_SUPPORTED);
}
/**
* Returns a list of the supported methods for sending an OAuth 2.0 bearer token to
* the protected resource. Defined values are "header", "body" and "query".
* {@code (bearer_methods_supported)}.
* @return a list of the supported methods for sending an OAuth 2.0 bearer token to
* the protected resource
*/
default List<String> getBearerMethodsSupported() {
|
return getClaimAsStringList(OAuth2ProtectedResourceMetadataClaimNames.BEARER_METHODS_SUPPORTED);
}
/**
* Returns the name of the protected resource intended for display to the end user
* {@code (resource_name)}.
* @return the name of the protected resource intended for display to the end user
*/
default String getResourceName() {
return getClaimAsString(OAuth2ProtectedResourceMetadataClaimNames.RESOURCE_NAME);
}
/**
* Returns {@code true} to indicate protected resource support for mutual-TLS client
* certificate-bound access tokens
* {@code (tls_client_certificate_bound_access_tokens)}.
* @return {@code true} to indicate protected resource support for mutual-TLS client
* certificate-bound access tokens
*/
default boolean isTlsClientCertificateBoundAccessTokens() {
return Boolean.TRUE.equals(getClaimAsBoolean(
OAuth2ProtectedResourceMetadataClaimNames.TLS_CLIENT_CERTIFICATE_BOUND_ACCESS_TOKENS));
}
}
|
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\OAuth2ProtectedResourceMetadataClaimAccessor.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("AD_Role_ID"))
{
p_role_id = para[i].getParameterAsInt();
}
else
{
log.error("Unknown Parameter: " + name);
}
}
}
private MRoleMenu addUpdateRole(Properties ctx, int roleId, int menuId, boolean active, String trxName)
{
String whereClause = "AD_Role_ID=" + roleId + " AND U_WebMenu_ID=" + menuId;
int roleMenuIds[] = MRoleMenu.getAllIDs(MRoleMenu.Table_Name, whereClause, trxName);
MRoleMenu roleMenu;
if ( roleMenuIds.length == 1)
{
roleMenu = new MRoleMenu(ctx, roleMenuIds[0],trxName);
}
else if ( roleMenuIds.length == 0)
{
roleMenu = new MRoleMenu(ctx, 0,trxName);
}
else
{
throw new IllegalStateException("More than one role menu defined.");
}
roleMenu.setAD_Role_ID(roleId);
roleMenu.setU_WebMenu_ID(menuId);
roleMenu.setIsActive(active);
if (!roleMenu.save())
{
throw new IllegalStateException("Could not create/update role menu, RoleMenuId: " + roleMenu.get_ID());
}
return roleMenu;
}
|
@Override
protected String doIt() throws Exception
{
if (p_role_id == 0)
{
throw new Exception("No Role defined or cannot assign menus to System Administrator");
}
String sqlStmt = "SELECT U_WebMenu_ID, IsActive FROM U_WebMenu";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sqlStmt, get_TrxName());
rs = pstmt.executeQuery();
while (rs.next())
{
int menuId = rs.getInt(1);
boolean active = "Y".equals(rs.getString(2));
addUpdateRole(getCtx(), p_role_id, menuId, active, get_TrxName());
}
}
finally
{
DB.close(rs, pstmt);
}
return "Role updated successfully";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\UpdateRoleMenu.java
| 1
|
请完成以下Java代码
|
public String getGivenName() {
return this.givenName;
}
public String getSn() {
return this.sn;
}
public String[] getCn() {
return this.cn.toArray(new String[0]);
}
public String getDescription() {
return this.description;
}
public String getTelephoneNumber() {
return this.telephoneNumber;
}
protected void populateContext(DirContextAdapter adapter) {
adapter.setAttributeValue("givenName", this.givenName);
adapter.setAttributeValue("sn", this.sn);
adapter.setAttributeValues("cn", getCn());
adapter.setAttributeValue("description", getDescription());
adapter.setAttributeValue("telephoneNumber", getTelephoneNumber());
if (getPassword() != null) {
adapter.setAttributeValue("userPassword", getPassword());
}
adapter.setAttributeValues("objectclass", new String[] { "top", "person" });
}
public static class Essence extends LdapUserDetailsImpl.Essence {
public Essence() {
}
public Essence(DirContextOperations ctx) {
super(ctx);
setCn(ctx.getStringAttributes("cn"));
setGivenName(ctx.getStringAttribute("givenName"));
setSn(ctx.getStringAttribute("sn"));
setDescription(ctx.getStringAttribute("description"));
setTelephoneNumber(ctx.getStringAttribute("telephoneNumber"));
Object password = ctx.getObjectAttribute("userPassword");
if (password != null) {
setPassword(LdapUtils.convertPasswordToString(password));
}
}
public Essence(Person copyMe) {
|
super(copyMe);
setGivenName(copyMe.givenName);
setSn(copyMe.sn);
setDescription(copyMe.getDescription());
setTelephoneNumber(copyMe.getTelephoneNumber());
((Person) this.instance).cn = new ArrayList<>(copyMe.cn);
}
@Override
protected LdapUserDetailsImpl createTarget() {
return new Person();
}
public void setGivenName(String givenName) {
((Person) this.instance).givenName = givenName;
}
public void setSn(String sn) {
((Person) this.instance).sn = sn;
}
public void setCn(String[] cn) {
((Person) this.instance).cn = Arrays.asList(cn);
}
public void addCn(String value) {
((Person) this.instance).cn.add(value);
}
public void setTelephoneNumber(String tel) {
((Person) this.instance).telephoneNumber = tel;
}
public void setDescription(String desc) {
((Person) this.instance).description = desc;
}
@Override
public LdapUserDetails createUserDetails() {
Person p = (Person) super.createUserDetails();
Assert.notNull(p.cn, "person.sn cannot be null");
Assert.notEmpty(p.cn, "person.cn cannot be empty");
// TODO: Check contents for null entries
return p;
}
}
}
|
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\Person.java
| 1
|
请完成以下Java代码
|
public void onDocValidate(@NonNull final Object model, @NonNull final DocTimingType timing)
{
Check.assume(isDocument, "isDocument flag is set"); // shall not happen
//
// Create missing invoice candidates for given document
if (timing == createInvoiceCandidatesTiming)
{
createMissingInvoiceCandidates(model);
}
}
@Override
public void onModelChange(@NonNull final Object model, @NonNull final ModelChangeType changeType)
{
//
// Create missing invoice candidates for given pseudo-document
if (!isDocument && changeType.isNewOrChange() && changeType.isAfter())
{
createMissingInvoiceCandidates(model);
}
}
/**
|
* Creates missing invoice candidates for given model, if this is enabled.
*/
private void createMissingInvoiceCandidates(@NonNull final Object model)
{
final CandidatesAutoCreateMode modeForCurrentModel = handler.getSpecificCandidatesAutoCreateMode(model);
switch (modeForCurrentModel)
{
case DONT: // just for completeness. we actually aren't called in this case
break;
case CREATE_CANDIDATES:
CreateMissingInvoiceCandidatesWorkpackageProcessor.schedule(model);
break;
case CREATE_CANDIDATES_AND_INVOICES:
generateIcsAndInvoices(model);
break;
}
}
private void generateIcsAndInvoices(@NonNull final Object model)
{
final TableRecordReference modelReference = TableRecordReference.of(model);
collector.collect(modelReference);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\ilhandler\ILHandlerModelInterceptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Mono<City> findCityById(@PathVariable("id") Long id) {
return cityHandler.findCityById(id);
}
@GetMapping()
@ResponseBody
public Flux<City> findAllCity() {
return cityHandler.findAllCity();
}
@PostMapping()
@ResponseBody
public Mono<Long> saveCity(@RequestBody City city) {
return cityHandler.save(city);
}
@PutMapping()
@ResponseBody
public Mono<Long> modifyCity(@RequestBody City city) {
return cityHandler.modifyCity(city);
}
@DeleteMapping(value = "/{id}")
@ResponseBody
public Mono<Long> deleteCity(@PathVariable("id") Long id) {
return cityHandler.deleteCity(id);
}
|
@GetMapping("/hello")
public Mono<String> hello(final Model model) {
model.addAttribute("name", "泥瓦匠");
model.addAttribute("city", "浙江温岭");
String path = "hello";
return Mono.create(monoSink -> monoSink.success(path));
}
private static final String CITY_LIST_PATH_NAME = "cityList";
@GetMapping("/page/list")
public String listPage(final Model model) {
final Flux<City> cityFluxList = cityHandler.findAllCity();
model.addAttribute("cityList", cityFluxList);
return CITY_LIST_PATH_NAME;
}
}
|
repos\springboot-learning-example-master\springboot-webflux-4-thymeleaf\src\main\java\org\spring\springboot\webflux\controller\CityWebFluxController.java
| 2
|
请完成以下Java代码
|
public void contribute(Path projectRoot) throws IOException {
S sourceCode = this.sourceFactory.get();
String applicationName = this.description.getApplicationName();
C compilationUnit = sourceCode.createCompilationUnit(this.description.getPackageName(), applicationName);
T mainApplicationType = compilationUnit.createTypeDeclaration(applicationName);
customizeMainApplicationType(mainApplicationType);
customizeMainCompilationUnit(compilationUnit);
customizeMainSourceCode(sourceCode);
this.sourceWriter.writeTo(
this.description.getBuildSystem().getMainSource(projectRoot, this.description.getLanguage()),
sourceCode);
}
@SuppressWarnings("unchecked")
private void customizeMainApplicationType(T mainApplicationType) {
List<MainApplicationTypeCustomizer<?>> customizers = this.mainTypeCustomizers.orderedStream()
.collect(Collectors.toList());
LambdaSafe.callbacks(MainApplicationTypeCustomizer.class, customizers, mainApplicationType)
.invoke((customizer) -> customizer.customize(mainApplicationType));
|
}
@SuppressWarnings("unchecked")
private void customizeMainCompilationUnit(C compilationUnit) {
List<MainCompilationUnitCustomizer<?, ?>> customizers = this.mainCompilationUnitCustomizers.orderedStream()
.collect(Collectors.toList());
LambdaSafe.callbacks(MainCompilationUnitCustomizer.class, customizers, compilationUnit)
.invoke((customizer) -> customizer.customize(compilationUnit));
}
@SuppressWarnings("unchecked")
private void customizeMainSourceCode(S sourceCode) {
List<MainSourceCodeCustomizer<?, ?, ?>> customizers = this.mainSourceCodeCustomizers.orderedStream()
.collect(Collectors.toList());
LambdaSafe.callbacks(MainSourceCodeCustomizer.class, customizers, sourceCode)
.invoke((customizer) -> customizer.customize(sourceCode));
}
}
|
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\MainSourceCodeProjectContributor.java
| 1
|
请完成以下Java代码
|
class JettyServer {
private Server server;
void start() throws Exception {
int maxThreads = 100;
int minThreads = 10;
int idleTimeout = 120;
QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, minThreads, idleTimeout);
server = new Server(threadPool);
ServerConnector connector = new ServerConnector(server);
connector.setPort(8090);
server.setConnectors(new Connector[] { connector });
|
ServletHandler servletHandler = new ServletHandler();
server.setHandler(servletHandler);
servletHandler.addServletWithMapping(BlockingServlet.class, "/status");
servletHandler.addServletWithMapping(AsyncServlet.class, "/heavy/async");
server.start();
}
void stop() throws Exception {
server.stop();
}
}
|
repos\tutorials-master\libraries-server\src\main\java\com\baeldung\jetty\JettyServer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BaseComponentDescriptorService implements ComponentDescriptorService {
@Autowired
private ComponentDescriptorDao componentDescriptorDao;
@Autowired
private DataValidator<ComponentDescriptor> componentValidator;
@Override
public ComponentDescriptor saveComponent(TenantId tenantId, ComponentDescriptor component) {
componentValidator.validate(component, data -> TenantId.SYS_TENANT_ID);
Optional<ComponentDescriptor> result = componentDescriptorDao.saveIfNotExist(tenantId, component);
return result.orElseGet(() -> componentDescriptorDao.findByClazz(tenantId, component.getClazz()));
}
@Override
public ComponentDescriptor findById(TenantId tenantId, ComponentDescriptorId componentId) {
Validator.validateId(componentId, "Incorrect component id for search request.");
return componentDescriptorDao.findById(tenantId, componentId);
}
@Override
public ComponentDescriptor findByClazz(TenantId tenantId, String clazz) {
Validator.validateString(clazz, "Incorrect clazz for search request.");
return componentDescriptorDao.findByClazz(tenantId, clazz);
}
@Override
public PageData<ComponentDescriptor> findByTypeAndPageLink(TenantId tenantId, ComponentType type, PageLink pageLink) {
Validator.validatePageLink(pageLink);
return componentDescriptorDao.findByTypeAndPageLink(tenantId, type, pageLink);
}
@Override
public PageData<ComponentDescriptor> findByScopeAndTypeAndPageLink(TenantId tenantId, ComponentScope scope, ComponentType type, PageLink pageLink) {
Validator.validatePageLink(pageLink);
return componentDescriptorDao.findByScopeAndTypeAndPageLink(tenantId, scope, type, pageLink);
}
@Override
public void deleteByClazz(TenantId tenantId, String clazz) {
|
Validator.validateString(clazz, "Incorrect clazz for delete request.");
componentDescriptorDao.deleteByClazz(tenantId, clazz);
}
@Override
public boolean validate(TenantId tenantId, ComponentDescriptor component, JsonNode configuration) {
try {
if (!component.getConfigurationDescriptor().has("schema")) {
throw new DataValidationException("Configuration descriptor doesn't contain schema property!");
}
JsonNode configurationSchema = component.getConfigurationDescriptor().get("schema");
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4);
JsonSchema schema = factory.getSchema(configurationSchema);
Set<ValidationMessage> validationMessages = schema.validate(configuration);
return validationMessages.isEmpty();
} catch (Exception e) {
throw new IncorrectParameterException(e.getMessage(), e);
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\component\BaseComponentDescriptorService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
class SurveyController {
@Autowired
private SurveyService surveyService;
@GetMapping("/surveys/{surveyId}/questions")
public List<Question> retrieveQuestions(@PathVariable String surveyId) {
return surveyService.retrieveQuestions(surveyId);
}
// GET "/surveys/{surveyId}/questions/{questionId}"
@GetMapping("/surveys/{surveyId}/questions/{questionId}")
public Question retrieveDetailsForQuestion(@PathVariable String surveyId,
@PathVariable String questionId) {
return surveyService.retrieveQuestion(surveyId, questionId);
}
// /surveys/{surveyId}/questions
@PostMapping("/surveys/{surveyId}/questions")
public ResponseEntity<Void> addQuestionToSurvey(
@PathVariable String surveyId, @RequestBody Question newQuestion) {
|
Question question = surveyService.addQuestion(surveyId, newQuestion);
if (question == null)
return ResponseEntity.noContent().build();
// Success - URI of the new resource in Response Header
// Status - created
// URI -> /surveys/{surveyId}/questions/{questionId}
// question.getQuestionId()
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(
"/{id}").buildAndExpand(question.getId()).toUri();
// Status
return ResponseEntity.created(location).build();
}
}
|
repos\SpringBootForBeginners-master\05.Spring-Boot-Advanced\src\main\java\com\in28minutes\springboot\controller\SurveyController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String uploadFile(@RequestParam final String username, @RequestParam final String password, @RequestParam("file") final MultipartFile file) {
if (!file.isEmpty()) {
try {
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
final String fileName = dateFormat.format(new Date());
final File fileServer = new File(fileName);
fileServer.createNewFile();
final byte[] bytes = file.getBytes();
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + username;
} catch (final Exception e) {
return "You failed to upload " + e.getMessage();
}
} else {
return "You failed to upload because the file was empty.";
}
}
@RequestMapping(value = "/users/upload", method = RequestMethod.POST)
public String postMultipart(@RequestParam("file") final MultipartFile file) {
|
if (!file.isEmpty()) {
try {
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
final String fileName = dateFormat.format(new Date());
final File fileServer = new File(fileName);
fileServer.createNewFile();
final byte[] bytes = file.getBytes();
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
stream.write(bytes);
stream.close();
return "You successfully uploaded ";
} catch (final Exception e) {
return "You failed to upload " + e.getMessage();
}
} else {
return "You failed to upload because the file was empty.";
}
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\controller\SimplePostController.java
| 2
|
请完成以下Java代码
|
public class CardSecurityInformation1 {
@XmlElement(name = "CSCMgmt", required = true)
@XmlSchemaType(name = "string")
protected CSCManagement1Code cscMgmt;
@XmlElement(name = "CSCVal")
protected String cscVal;
/**
* Gets the value of the cscMgmt property.
*
* @return
* possible object is
* {@link CSCManagement1Code }
*
*/
public CSCManagement1Code getCSCMgmt() {
return cscMgmt;
}
/**
* Sets the value of the cscMgmt property.
*
* @param value
* allowed object is
* {@link CSCManagement1Code }
*
*/
public void setCSCMgmt(CSCManagement1Code value) {
this.cscMgmt = value;
}
/**
* Gets the value of the cscVal property.
*
* @return
* possible object is
* {@link String }
*
|
*/
public String getCSCVal() {
return cscVal;
}
/**
* Sets the value of the cscVal property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCSCVal(String value) {
this.cscVal = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardSecurityInformation1.java
| 1
|
请完成以下Java代码
|
public void setNote (final @Nullable java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
@Override
public java.lang.String getNote()
{
return get_ValueAsString(COLUMNNAME_Note);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setQty_Planned (final @Nullable BigDecimal Qty_Planned)
{
set_Value (COLUMNNAME_Qty_Planned, Qty_Planned);
}
@Override
public BigDecimal getQty_Planned()
|
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Planned);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQty_Reported (final @Nullable BigDecimal Qty_Reported)
{
set_Value (COLUMNNAME_Qty_Reported, Qty_Reported);
}
@Override
public BigDecimal getQty_Reported()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* Type AD_Reference_ID=540263
* Reference name: C_Flatrate_DataEntry Type
*/
public static final int TYPE_AD_Reference_ID=540263;
/** Invoicing_PeriodBased = IP */
public static final String TYPE_Invoicing_PeriodBased = "IP";
/** Correction_PeriodBased = CP */
public static final String TYPE_Correction_PeriodBased = "CP";
/** Procurement_PeriodBased = PC */
public static final String TYPE_Procurement_PeriodBased = "PC";
@Override
public void setType (final java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry.java
| 1
|
请完成以下Java代码
|
public class Region extends Country implements Externalizable {
private static final long serialVersionUID = 1L;
private String climate;
private Double population;
private Community community;
public String getClimate() {
return climate;
}
public void setClimate(String climate) {
this.climate = climate;
}
public Double getPopulation() {
return population;
}
public void setPopulation(Double population) {
this.population = population;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
|
out.writeUTF(climate);
community = new Community();
community.setId(5);
out.writeObject(community);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
this.climate = in.readUTF();
community = (Community) in.readObject();
}
@Override
public String toString() {
return "Region = {" +
"country='" + super.toString() + '\'' +
"community='" + community.toString() + '\'' +
"climate='" + climate + '\'' +
", population=" + population +
'}';
}
}
|
repos\tutorials-master\core-java-modules\core-java-serialization\src\main\java\com\baeldung\externalizable\Region.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private HUQRCodeAttribute toHUQRCodeAttribute(final HUQRCodeGenerateRequest.Attribute request)
{
final AttributeId attributeId;
final I_M_Attribute attribute;
if (request.getAttributeId() != null)
{
attributeId = request.getAttributeId();
attribute = attributeDAO.getAttributeRecordById(attributeId);
}
else if (request.getCode() != null)
{
attribute = attributeDAO.retrieveAttributeByValue(request.getCode());
attributeId = AttributeId.ofRepoId(attribute.getM_Attribute_ID());
}
else
{
throw new AdempiereException("Cannot find M_Attribute_ID by " + request);
}
final String value;
final String valueRendered;
final AttributeValueType valueType = AttributeValueType.ofCode(attribute.getAttributeValueType());
switch (valueType)
{
case STRING:
value = StringUtils.trimBlankToNull(request.getValueString());
valueRendered = null;
break;
case NUMBER:
value = request.getValueNumber() != null ? request.getValueNumber().toString() : null;
valueRendered = null;
break;
case DATE:
value = request.getValueDate() != null ? request.getValueDate().toString() : null;
valueRendered = null;
break;
case LIST:
if (request.getValueListId() != null)
{
AttributeListValue listItem = attributeDAO.retrieveAttributeValueOrNull(attributeId, request.getValueListId());
if (listItem == null)
{
throw new AdempiereException("No list item found for attribute " + attributeId + " and list value " + request.getValueListId());
}
value = String.valueOf(listItem.getId().getRepoId());
valueRendered = listItem.getName();
}
else
|
{
value = null;
valueRendered = null;
}
break;
default:
throw new AdempiereException("Unsupported attribute value type: " + valueType);
}
return HUQRCodeAttribute.builder()
.code(AttributeCode.ofString(attribute.getValue()))
.displayName(attribute.getName())
.value(value)
.valueRendered(valueRendered)
.build();
}
//
//
//
public static class Cache
{
private final HashMap<ProductId, HUQRCodeProductInfo> productInfos = new HashMap<>();
private final HashMap<HuPackingInstructionsId, HUQRCodePackingInfo> packingInfos = new HashMap<>();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodeGenerateCommand.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.