instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public <T> JavaUtils acceptIfNotNull(@Nullable T value, Consumer<T> consumer) {
if (value != null) {
consumer.accept(value);
}
return this;
}
/**
* Invoke {@link Consumer#accept(Object)} with the value if it is not null or empty.
* @param value the value.
* @param consumer the consumer.
* @return this.
*/
public JavaUtils acceptIfHasText(@Nullable String value, Consumer<String> consumer) {
if (StringUtils.hasText(value)) {
consumer.accept(value);
}
return this;
}
/**
* Invoke {@link BiConsumer#accept(Object, Object)} with the arguments if the
* condition is true.
* @param condition the condition.
* @param t1 the first consumer argument
* @param t2 the second consumer argument
* @param consumer the consumer.
* @param <T1> the first argument type.
* @param <T2> the second argument type.
* @return this.
*/
public <T1, T2> JavaUtils acceptIfCondition(boolean condition, T1 t1, T2 t2, BiConsumer<T1, T2> consumer) {
if (condition) {
consumer.accept(t1, t2);
}
return this;
}
/**
* Invoke {@link BiConsumer#accept(Object, Object)} with the arguments if the t2
* argument is not null.
* @param t1 the first argument
* @param t2 the second consumer argument
* @param consumer the consumer.
* @param <T1> the first argument type.
* @param <T2> the second argument type.
* @return this.
*/ | public <T1, T2> JavaUtils acceptIfNotNull(T1 t1, @Nullable T2 t2, BiConsumer<T1, T2> consumer) {
if (t2 != null) {
consumer.accept(t1, t2);
}
return this;
}
/**
* Invoke {@link BiConsumer#accept(Object, Object)} with the arguments if the value
* argument is not null or empty.
* @param t1 the first consumer argument.
* @param value the second consumer argument
* @param <T> the first argument type.
* @param consumer the consumer.
* @return this.
*/
public <T> JavaUtils acceptIfHasText(T t1, @Nullable String value, BiConsumer<T, String> consumer) {
if (StringUtils.hasText(value)) {
consumer.accept(t1, value);
}
return this;
}
/**
* Invoke {@link Consumer#accept(Object)} with the value or alternative if one of them is not null.
* @param value the value.
* @param alternative the other value if the {@code value} argument is null.
* @param consumer the consumer.
* @param <T> the value type.
* @return this.
* @since 4.0
*/
public <T> JavaUtils acceptOrElseIfNotNull(@Nullable T value, @Nullable T alternative, Consumer<T> consumer) {
if (value != null) {
consumer.accept(value);
}
else if (alternative != null) {
consumer.accept(alternative);
}
return this;
}
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\utils\JavaUtils.java | 1 |
请完成以下Java代码 | public Mono<Void> handle(WebSocketSession proxySession) {
Mono<Void> serverClose = proxySession.closeStatus()
.filter(__ -> session.isOpen())
.map(this::adaptCloseStatus)
.flatMap(session::close);
Mono<Void> proxyClose = session.closeStatus()
.filter(__ -> proxySession.isOpen())
.map(this::adaptCloseStatus)
.flatMap(proxySession::close);
// Use retain() for Reactor Netty
Mono<Void> proxySessionSend = proxySession
.send(session.receive().doOnNext(WebSocketMessage::retain).doOnNext(webSocketMessage -> {
if (log.isTraceEnabled()) {
log.trace("proxySession(send from client): " + proxySession.getId()
+ ", corresponding session:" + session.getId() + ", packet: "
+ webSocketMessage.getPayloadAsText());
}
}));
// .log("proxySessionSend", Level.FINE);
Mono<Void> serverSessionSend = session
.send(proxySession.receive().doOnNext(WebSocketMessage::retain).doOnNext(webSocketMessage -> {
if (log.isTraceEnabled()) {
log.trace("session(send from backend): " + session.getId()
+ ", corresponding proxySession:" + proxySession.getId() + " packet: "
+ webSocketMessage.getPayloadAsText());
}
})); | // .log("sessionSend", Level.FINE);
// Ensure closeStatus from one propagates to the other
Mono.when(serverClose, proxyClose).subscribe();
// Complete when both sessions are done
return Mono.zip(proxySessionSend, serverSessionSend).then();
}
/**
* Copy subProtocols so they are available downstream.
* @return available subProtocols.
*/
@Override
public List<String> getSubProtocols() {
return ProxyWebSocketHandler.this.subProtocols;
}
});
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\WebsocketRoutingFilter.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_Process_Para getAD_Process_Para() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Process_Para_ID, org.compiere.model.I_AD_Process_Para.class);
}
@Override
public void setAD_Process_Para(org.compiere.model.I_AD_Process_Para AD_Process_Para)
{
set_ValueFromPO(COLUMNNAME_AD_Process_Para_ID, org.compiere.model.I_AD_Process_Para.class, AD_Process_Para);
}
/** Set Prozess-Parameter.
@param AD_Process_Para_ID Prozess-Parameter */
@Override
public void setAD_Process_Para_ID (int AD_Process_Para_ID)
{
if (AD_Process_Para_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Process_Para_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Process_Para_ID, Integer.valueOf(AD_Process_Para_ID));
}
/** Get Prozess-Parameter.
@return Prozess-Parameter */
@Override
public int getAD_Process_Para_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_Para_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Scheduler getAD_Scheduler() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Scheduler_ID, org.compiere.model.I_AD_Scheduler.class);
}
@Override
public void setAD_Scheduler(org.compiere.model.I_AD_Scheduler AD_Scheduler)
{
set_ValueFromPO(COLUMNNAME_AD_Scheduler_ID, org.compiere.model.I_AD_Scheduler.class, AD_Scheduler);
}
/** Set Ablaufsteuerung.
@param AD_Scheduler_ID
Schedule Processes
*/
@Override
public void setAD_Scheduler_ID (int AD_Scheduler_ID)
{
if (AD_Scheduler_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, Integer.valueOf(AD_Scheduler_ID));
}
/** Get Ablaufsteuerung. | @return Schedule Processes
*/
@Override
public int getAD_Scheduler_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Scheduler_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Default Parameter.
@param ParameterDefault
Default value of the parameter
*/
@Override
public void setParameterDefault (java.lang.String ParameterDefault)
{
set_Value (COLUMNNAME_ParameterDefault, ParameterDefault);
}
/** Get Default Parameter.
@return Default value of the parameter
*/
@Override
public java.lang.String getParameterDefault ()
{
return (java.lang.String)get_Value(COLUMNNAME_ParameterDefault);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Scheduler_Para.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_Country getTo_Country()
{
return get_ValueAsPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class);
}
@Override
public void setTo_Country(final org.compiere.model.I_C_Country To_Country)
{
set_ValueFromPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class, To_Country);
}
@Override
public void setTo_Country_ID (final int To_Country_ID)
{
if (To_Country_ID < 1)
set_Value (COLUMNNAME_To_Country_ID, null);
else
set_Value (COLUMNNAME_To_Country_ID, To_Country_ID);
}
@Override
public int getTo_Country_ID()
{
return get_ValueAsInt(COLUMNNAME_To_Country_ID);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override | public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setVATaxID (final java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Fiscal_Representation.java | 1 |
请完成以下Java代码 | public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Exclude.
@param IsExclude
Exclude access to the data - if not selected Include access to the data
*/
public void setIsExclude (boolean IsExclude)
{
set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude));
}
/** Get Exclude.
@return Exclude access to the data - if not selected Include access to the data
*/
public boolean isExclude ()
{
Object oo = get_Value(COLUMNNAME_IsExclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/ | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessProfile.java | 1 |
请完成以下Java代码 | public void setDK_ParcelHeight (java.math.BigDecimal DK_ParcelHeight)
{
set_Value (COLUMNNAME_DK_ParcelHeight, DK_ParcelHeight);
}
/** Get Pakethöhe.
@return Pakethöhe */
@Override
public java.math.BigDecimal getDK_ParcelHeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelHeight);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Paketlänge.
@param DK_ParcelLength Paketlänge */
@Override
public void setDK_ParcelLength (java.math.BigDecimal DK_ParcelLength)
{
set_Value (COLUMNNAME_DK_ParcelLength, DK_ParcelLength);
}
/** Get Paketlänge.
@return Paketlänge */
@Override
public java.math.BigDecimal getDK_ParcelLength ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelLength);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Sendungsnummer.
@param DK_ParcelNumber Sendungsnummer */
@Override
public void setDK_ParcelNumber (java.lang.String DK_ParcelNumber)
{
set_Value (COLUMNNAME_DK_ParcelNumber, DK_ParcelNumber);
}
/** Get Sendungsnummer.
@return Sendungsnummer */
@Override
public java.lang.String getDK_ParcelNumber ()
{
return (java.lang.String)get_Value(COLUMNNAME_DK_ParcelNumber);
}
/** Set Paketgewicht.
@param DK_ParcelWeight Paketgewicht */
@Override
public void setDK_ParcelWeight (java.math.BigDecimal DK_ParcelWeight)
{
set_Value (COLUMNNAME_DK_ParcelWeight, DK_ParcelWeight);
}
/** Get Paketgewicht.
@return Paketgewicht */
@Override
public java.math.BigDecimal getDK_ParcelWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelWeight);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Paketbreite.
@param DK_ParcelWidth Paketbreite */
@Override
public void setDK_ParcelWidth (java.math.BigDecimal DK_ParcelWidth) | {
set_Value (COLUMNNAME_DK_ParcelWidth, DK_ParcelWidth);
}
/** Get Paketbreite.
@return Paketbreite */
@Override
public java.math.BigDecimal getDK_ParcelWidth ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelWidth);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Referenz.
@param DK_Reference Referenz */
@Override
public void setDK_Reference (java.lang.String DK_Reference)
{
set_Value (COLUMNNAME_DK_Reference, DK_Reference);
}
/** Get Referenz.
@return Referenz */
@Override
public java.lang.String getDK_Reference ()
{
return (java.lang.String)get_Value(COLUMNNAME_DK_Reference);
}
/** Set Zeile Nr..
@param Line
Einzelne Zeile in dem Dokument
*/
@Override
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Einzelne Zeile in dem Dokument
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrderLine.java | 1 |
请完成以下Java代码 | public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAppname() {
return appname;
}
public void setAppname(String appname) {
this.appname = appname;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getAddressType() {
return addressType;
}
public void setAddressType(int addressType) { | this.addressType = addressType;
}
public String getAddressList() {
return addressList;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public void setAddressList(String addressList) {
this.addressList = addressList;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobGroup.java | 1 |
请完成以下Java代码 | protected Enumeration findResources(final String name) throws IOException {
Enumeration<URL> urls;
try {
urls = AccessController.doPrivileged(new PrivilegedExceptionAction<Enumeration<URL>>() {
@Override
public Enumeration<URL> run() throws IOException {
return bundle.getResources(name);
}
});
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
if (cause instanceof IOException)
throw (IOException) cause;
else
throw (RuntimeException) cause;
}
if (urls == null) {
urls = Collections.enumeration(new ArrayList<>());
}
return urls;
} | @SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class clazz;
try {
clazz = findClass(name);
} catch (ClassNotFoundException cnfe) {
if (classLoader != null) {
try {
clazz = classLoader.loadClass(name);
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException(name + " from bundle " + bundle.getBundleId() + " (" + bundle.getSymbolicName() + ")", cnfe);
}
} else {
throw new ClassNotFoundException(name + " from bundle " + bundle.getBundleId() + " (" + bundle.getSymbolicName() + ")", cnfe);
}
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
}
public Bundle getBundle() {
return bundle;
}
} | repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\blueprint\BundleDelegatingClassLoader.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() { | return age;
}
public void setAge(int age) {
this.age = age;
}
public long getTotal() {
return total;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", age=" + age
+ ", name=" + name + ", genre=" + genre + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootPageEntityOffsetPaginationExtraColumn\src\main\java\com\bookstore\entity\Author.java | 1 |
请完成以下Java代码 | public I_MSV3_Bestellung storePurchaseOrderRequest(@NonNull final OrderCreateRequest request)
{
final I_MSV3_Bestellung bestellungRecord = createRecord(request);
save(bestellungRecord);
for (final OrderCreateRequestPackage requestOrder : request.getOrderPackages())
{
final I_MSV3_BestellungAuftrag requestOrderRecord = createRecord(requestOrder);
requestOrderRecord.setMSV3_Bestellung(bestellungRecord);
save(requestOrderRecord);
for (final OrderCreateRequestPackageItem requestItem : requestOrder.getItems())
{
final I_MSV3_BestellungPosition bestellungPositionRecord = createRecord(requestItem);
bestellungPositionRecord.setMSV3_BestellungAuftrag(requestOrderRecord);
save(bestellungPositionRecord);
}
}
return bestellungRecord;
}
private I_MSV3_Bestellung createRecord(@NonNull final OrderCreateRequest request)
{
final I_MSV3_Bestellung record = newInstanceOutOfTrx(I_MSV3_Bestellung.class);
record.setAD_Org_ID(orgId.getRepoId());
record.setMSV3_BestellSupportId(request.getSupportId().getValueAsInt());
record.setMSV3_Id(request.getOrderId().getValueAsString());
return record;
} | private I_MSV3_BestellungAuftrag createRecord(@NonNull final OrderCreateRequestPackage requestOrder)
{
final I_MSV3_BestellungAuftrag record = newInstanceOutOfTrx(I_MSV3_BestellungAuftrag.class);
record.setAD_Org_ID(orgId.getRepoId());
record.setMSV3_Auftragsart(requestOrder.getOrderType().getV2SoapCode().value());
record.setMSV3_Auftragskennung(requestOrder.getOrderIdentification());
record.setMSV3_AuftragsSupportID(requestOrder.getSupportId().getValueAsInt());
record.setMSV3_GebindeId(requestOrder.getPackingMaterialId());
record.setMSV3_Id(requestOrder.getId().getValueAsString());
return record;
}
private I_MSV3_BestellungPosition createRecord(@NonNull final OrderCreateRequestPackageItem requestItem)
{
final I_MSV3_BestellungPosition record = newInstanceOutOfTrx(I_MSV3_BestellungPosition.class);
record.setAD_Org_ID(orgId.getRepoId());
record.setMSV3_Liefervorgabe(requestItem.getDeliverySpecifications().getV2SoapCode().value());
record.setMSV3_Menge(requestItem.getQty().getValueAsInt());
record.setMSV3_Pzn(requestItem.getPzn().getValueAsString());
record.setC_PurchaseCandidate_ID(MSV3PurchaseCandidateId.toRepoId(requestItem.getPurchaseCandidateId()));
return record;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\purchaseOrder\MSV3PurchaseOrderRequestPersister.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserEventListeners {
private static final Logger logger = LoggerFactory.getLogger(UserEventListeners.class);
public static final String EVENT_TYPE_CUSTOM_HEADER = "eventType";
private final UserRepository userRepository;
public UserEventListeners(UserRepository userRepository) {
this.userRepository = userRepository;
}
@SqsListener("${events.queues.user-created-by-name-queue}")
public void receiveStringMessage(String username) {
logger.info("Received message: {}", username);
userRepository.save(new User(UUID.randomUUID()
.toString(), username, null));
} | @SqsListener(value = "${events.queues.user-created-record-queue}")
public void receiveRecordMessage(UserCreatedEvent event) {
logger.info("Received message: {}", event);
userRepository.save(new User(event.id(), event.username(), event.email()));
}
@SqsListener("${events.queues.user-created-event-type-queue}")
public void customHeaderMessage(Message<UserCreatedEvent> message, @Header(EVENT_TYPE_CUSTOM_HEADER) String eventType,
@Header(SQS_APPROXIMATE_FIRST_RECEIVE_TIMESTAMP) Long firstReceive) {
logger.info("Received message {} with event type {}. First received at approximately {}.", message, eventType, firstReceive);
UserCreatedEvent payload = message.getPayload();
userRepository.save(new User(payload.id(), payload.username(), payload.email()));
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\sqs\introduction\UserEventListeners.java | 2 |
请完成以下Java代码 | public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Replicated.
@param IsReplicated
The data is successfully replicated
*/
public void setIsReplicated (boolean IsReplicated)
{
set_ValueNoCheck (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated));
}
/** Get Replicated.
@return The data is successfully replicated
*/
public boolean isReplicated ()
{
Object oo = get_Value(COLUMNNAME_IsReplicated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name. | @param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication_Run.java | 1 |
请完成以下Java代码 | public ActivityBehaviorFactory getActivityBehaviorFactory() {
return activityBehaviorFactory;
}
public void setActivityBehaviorFactory(ActivityBehaviorFactory activityBehaviorFactory) {
this.activityBehaviorFactory = activityBehaviorFactory;
}
public ListenerFactory getListenerFactory() {
return listenerFactory;
}
public void setListenerFactory(ListenerFactory listenerFactory) {
this.listenerFactory = listenerFactory;
}
public Map<String, SequenceFlow> getSequenceFlows() {
return sequenceFlows;
}
public ProcessDefinitionEntity getCurrentProcessDefinition() {
return currentProcessDefinition;
}
public void setCurrentProcessDefinition(ProcessDefinitionEntity currentProcessDefinition) {
this.currentProcessDefinition = currentProcessDefinition;
}
public FlowElement getCurrentFlowElement() {
return currentFlowElement;
}
public void setCurrentFlowElement(FlowElement currentFlowElement) {
this.currentFlowElement = currentFlowElement;
} | public Process getCurrentProcess() {
return currentProcess;
}
public void setCurrentProcess(Process currentProcess) {
this.currentProcess = currentProcess;
}
public void setCurrentSubProcess(SubProcess subProcess) {
currentSubprocessStack.push(subProcess);
}
public SubProcess getCurrentSubProcess() {
return currentSubprocessStack.peek();
}
public void removeCurrentSubProcess() {
currentSubprocessStack.pop();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java | 1 |
请完成以下Java代码 | public class X_AD_UI_Section extends org.compiere.model.PO implements I_AD_UI_Section, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 791232113L;
/** Standard Constructor */
public X_AD_UI_Section (Properties ctx, int AD_UI_Section_ID, String trxName)
{
super (ctx, AD_UI_Section_ID, trxName);
}
/** Load Constructor */
public X_AD_UI_Section (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_AD_Tab getAD_Tab()
{
return get_ValueAsPO(COLUMNNAME_AD_Tab_ID, org.compiere.model.I_AD_Tab.class);
}
@Override
public void setAD_Tab(org.compiere.model.I_AD_Tab AD_Tab)
{
set_ValueFromPO(COLUMNNAME_AD_Tab_ID, org.compiere.model.I_AD_Tab.class, AD_Tab);
}
@Override
public void setAD_Tab_ID (int AD_Tab_ID)
{
if (AD_Tab_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Tab_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Tab_ID, Integer.valueOf(AD_Tab_ID));
}
@Override
public int getAD_Tab_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Tab_ID);
}
@Override
public void setAD_UI_Section_ID (int AD_UI_Section_ID)
{
if (AD_UI_Section_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UI_Section_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UI_Section_ID, Integer.valueOf(AD_UI_Section_ID));
}
@Override
public int getAD_UI_Section_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_UI_Section_ID);
}
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
} | @Override
public java.lang.String getDescription()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
@Override
public void setHelp (java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return (java.lang.String)get_Value(COLUMNNAME_Help);
}
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setUIStyle (java.lang.String UIStyle)
{
set_Value (COLUMNNAME_UIStyle, UIStyle);
}
@Override
public java.lang.String getUIStyle()
{
return (java.lang.String)get_Value(COLUMNNAME_UIStyle);
}
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@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_AD_UI_Section.java | 1 |
请完成以下Spring Boot application配置 | ## Session store-type
spring.session.store-type=redis
## Session timeout default
server.servlet.session.timeout=600
## Session store to Redis key prefix
spring.session.redis.namespace=test:spring:session
## Redis config
| spring.redis.host=127.0.0.1
spring.redis.password=123456
spring.redis.port=6379
server.port=8088 | repos\springboot-demo-master\session\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public static ViewRowFieldNameAndJsonValues ofMap(@NonNull final ImmutableMap<String, Object> map)
{
if (map.isEmpty())
{
return EMPTY;
}
return new ViewRowFieldNameAndJsonValues(map);
}
private static final ViewRowFieldNameAndJsonValues EMPTY = new ViewRowFieldNameAndJsonValues();
private final ImmutableMap<String, Object> map;
private ViewRowFieldNameAndJsonValues(@NonNull final ImmutableMap<String, Object> map)
{
this.map = map;
}
private ViewRowFieldNameAndJsonValues()
{
map = ImmutableMap.of();
}
public ImmutableSet<String> getFieldNames()
{
return map.keySet();
}
public Comparable<?> getAsComparable(
@NonNull final String fieldName,
@NonNull final JSONOptions jsonOpts)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.isNull(valueObj))
{
return null;
}
else if (valueObj instanceof ITranslatableString)
{
return ((ITranslatableString)valueObj).translate(jsonOpts.getAdLanguage());
}
else if (valueObj instanceof Comparable)
{
return (Comparable<?>)valueObj;
}
else
{
return valueObj.toString();
}
}
public Object getAsJsonObject(
@NonNull final String fieldName,
@NonNull final JSONOptions jsonOpts)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.isNull(valueObj))
{
return null;
}
else if (valueObj instanceof ITranslatableString)
{
return ((ITranslatableString)valueObj).translate(jsonOpts.getAdLanguage());
}
else
{
return Values.valueToJsonObject(valueObj, jsonOpts);
}
}
public int getAsInt(@NonNull final String fieldName, final int defaultValueIfNotFoundOrError)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.toNullIfInstance(valueObj) == null)
{
return defaultValueIfNotFoundOrError;
}
else if (valueObj instanceof Number)
{
return ((Number)valueObj).intValue();
} | else if (valueObj instanceof LookupValue)
{
return ((LookupValue)valueObj).getIdAsInt();
}
else if (valueObj instanceof JSONLookupValue)
{
return ((JSONLookupValue)valueObj).getKeyAsInt();
}
else
{
return NumberUtils.asInt(valueObj, defaultValueIfNotFoundOrError);
}
}
public BigDecimal getAsBigDecimal(@NonNull final String fieldName, final BigDecimal defaultValueIfNotFoundOrError)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.isNull(valueObj))
{
return defaultValueIfNotFoundOrError;
}
else
{
return NumberUtils.asBigDecimal(valueObj, defaultValueIfNotFoundOrError);
}
}
public boolean getAsBoolean(@NonNull final String fieldName, final boolean defaultValueIfNotFoundOrError)
{
final Object valueObj = map.get(fieldName);
return StringUtils.toBoolean(valueObj, defaultValueIfNotFoundOrError);
}
public boolean isEmpty(@NonNull final String fieldName)
{
final Object valueObj = map.get(fieldName);
return valueObj == null || JSONNullValue.isNull(valueObj) || valueObj.toString().isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowFieldNameAndJsonValues.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Profile viewProfile(long viewerId, UserName usernameToView) {
final var viewer = userFindService.findById(viewerId).orElseThrow(NoSuchElementException::new);
return userFindService.findByUsername(usernameToView)
.map(viewer::viewProfile)
.orElseThrow(NoSuchElementException::new);
}
@Transactional(readOnly = true)
public Profile viewProfile(UserName userName) {
return userFindService.findByUsername(userName)
.map(User::getProfile)
.orElseThrow(NoSuchElementException::new);
}
@Transactional
public Profile followAndViewProfile(long followerId, UserName followeeUserName) { | final var followee = userFindService.findByUsername(followeeUserName).orElseThrow(NoSuchElementException::new);
return userFindService.findById(followerId)
.map(follower -> follower.followUser(followee))
.map(follower -> follower.viewProfile(followee))
.orElseThrow(NoSuchElementException::new);
}
@Transactional
public Profile unfollowAndViewProfile(long followerId, UserName followeeUserName) {
final var followee = userFindService.findByUsername(followeeUserName).orElseThrow(NoSuchElementException::new);
return userFindService.findById(followerId)
.map(follower -> follower.unfollowUser(followee))
.map(follower -> follower.viewProfile(followee))
.orElseThrow(NoSuchElementException::new);
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\ProfileService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<Serializable> getContent() {
if (content == null) {
content = new ArrayList<Serializable>();
}
return this.content;
}
/**
* The schema of the classification - e.g. eCl@ss.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClassificationSchema() { | return classificationSchema;
}
/**
* Sets the value of the classificationSchema property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClassificationSchema(String value) {
this.classificationSchema = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ClassificationType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MediatedCommissionSettingsRepo
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
@NonNull
public MediatedCommissionSettings getById(@NonNull final MediatedCommissionSettingsId commissionSettingsId)
{
final I_C_MediatedCommissionSettings mediatedCommissionSettings = InterfaceWrapperHelper.load(commissionSettingsId, I_C_MediatedCommissionSettings.class);
return toMediatedCommissionSettings(mediatedCommissionSettings);
}
@NonNull
private MediatedCommissionSettings toMediatedCommissionSettings(@NonNull final I_C_MediatedCommissionSettings record)
{
final ImmutableList<MediatedCommissionSettingsLine> lines = queryBL.createQueryBuilder(I_C_MediatedCommissionSettingsLine.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_MediatedCommissionSettings.COLUMNNAME_C_MediatedCommissionSettings_ID, record.getC_MediatedCommissionSettings_ID())
.create()
.stream()
.map(this::toMediatedCommissionLine)
.collect(ImmutableList.toImmutableList());
return MediatedCommissionSettings.builder()
.commissionSettingsId(MediatedCommissionSettingsId.ofRepoId(record.getC_MediatedCommissionSettings_ID()))
.commissionProductId(ProductId.ofRepoId(record.getCommission_Product_ID())) | .orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.pointsPrecision(record.getPointsPrecision())
.lines(lines)
.build();
}
@NonNull
private MediatedCommissionSettingsLine toMediatedCommissionLine(@NonNull final I_C_MediatedCommissionSettingsLine record)
{
final MediatedCommissionSettingsId settingsId = MediatedCommissionSettingsId.ofRepoId(record.getC_MediatedCommissionSettings_ID());
return MediatedCommissionSettingsLine.builder()
.mediatedCommissionSettingsLineId(MediatedCommissionSettingsLineId.ofRepoId(record.getC_MediatedCommissionSettingsLine_ID(), settingsId))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.percentOfBasedPoints(Percent.of(record.getPercentOfBasePoints()))
.seqNo(record.getSeqNo())
.productCategoryId(ProductCategoryId.ofRepoIdOrNull(record.getM_Product_Category_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\mediated\repository\MediatedCommissionSettingsRepo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CacheController {
@Autowired
private DemoService demoService;
//http://localhost:8080/put?name=abel&age=23&address=shanghai
@RequestMapping("/put")
public Person put(Person person){
return demoService.save(person);
}
//http://localhost:8080/able?id=1
@RequestMapping("/able")
@ResponseBody
public Person cacheable(Person person){ | return demoService.findOne(person);
}
//http://localhost:8080/evit?id=1
@RequestMapping("/evit")
public String evit(Long id){
demoService.remove(id);
return "ok";
}
} | repos\springBoot-master\springboot-Cache\src\main\java\com\us\example\controller\CacheController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotBlank(message = "Name is mandatory")
private String name;
@NotBlank(message = "Email is mandatory")
private String email;
public User() {}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
} | public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "User{" + "id=" + id + ", name=" + name + ", email=" + email + '}';
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\springbootcrudapp\application\entities\User.java | 2 |
请完成以下Java代码 | public class CreateProductCosts extends JavaProcess
{
private final ICurrentCostsRepository currentCostsRepository = Adempiere.getBean(ICurrentCostsRepository.class);
private int count_all = 0;
@Override
@RunOutOfTrx
protected String doIt()
{
final Iterator<I_M_Product> products = retrieveProducts();
Services.get(ITrxItemProcessorExecutorService.class)
.<I_M_Product, Void> createExecutor()
.setExceptionHandler(LoggerTrxItemExceptionHandler.instance)
.setProcessor(this::process)
.process(products);
return "@Updated@ #" + count_all;
} | private void process(final I_M_Product product)
{
currentCostsRepository.createDefaultProductCosts(product);
count_all++;
}
private Iterator<I_M_Product> retrieveProducts()
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_Product.class)
.addEqualsFilter(I_M_Product.COLUMNNAME_AD_Client_ID, getAD_Client_ID())
.addOnlyActiveRecordsFilter()
.orderBy(I_M_Product.COLUMN_M_Product_ID)
.create()
.iterate(I_M_Product.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\process\CreateProductCosts.java | 1 |
请完成以下Java代码 | public class Coffee {
private String name;
private String brand;
private LocalDateTime date;
public String getName() {
return name;
}
public Coffee setName(String name) {
this.name = name;
return this;
}
public String getBrand() {
return brand; | }
public Coffee setBrand(String brand) {
this.brand = brand;
return this;
}
public LocalDateTime getDate() {
return date;
}
public Coffee setDate(LocalDateTime date) {
this.date = date;
return this;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-data\src\main\java\com\baeldung\boot\jackson\model\Coffee.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<TaskEntity> findTasksBySubScopeIdScopeType(String subScopeId, String scopeType) {
return getTaskEntityManager().findTasksBySubScopeIdAndScopeType(subScopeId, scopeType);
}
@Override
public TaskQuery createTaskQuery(CommandExecutor commandExecutor, AbstractEngineConfiguration engineConfiguration) {
return new TaskQueryImpl(commandExecutor, configuration, getVariableServiceConfiguration(engineConfiguration), configuration.getIdmIdentityService());
}
@Override
public void changeTaskAssignee(TaskEntity taskEntity, String userId) {
getTaskEntityManager().changeTaskAssignee(taskEntity, userId);
}
@Override
public void changeTaskOwner(TaskEntity taskEntity, String ownerId) {
getTaskEntityManager().changeTaskOwner(taskEntity, ownerId);
}
@Override
public void updateTaskTenantIdForDeployment(String deploymentId, String tenantId) {
getTaskEntityManager().updateTaskTenantIdForDeployment(deploymentId, tenantId);
}
@Override
public void updateTask(TaskEntity taskEntity, boolean fireUpdateEvent) {
getTaskEntityManager().update(taskEntity, fireUpdateEvent);
}
@Override
public void updateAllTaskRelatedEntityCountFlags(boolean configProperty) {
getTaskEntityManager().updateAllTaskRelatedEntityCountFlags(configProperty);
}
@Override
public TaskEntity createTask() {
return getTaskEntityManager().create(); | }
@Override
public void insertTask(TaskEntity taskEntity, boolean fireCreateEvent) {
getTaskEntityManager().insert(taskEntity, fireCreateEvent);
}
@Override
public void deleteTask(TaskEntity task, boolean fireEvents) {
getTaskEntityManager().delete(task, fireEvents);
}
@Override
public void deleteTasksByExecutionId(String executionId) {
getTaskEntityManager().deleteTasksByExecutionId(executionId);
}
public TaskEntityManager getTaskEntityManager() {
return configuration.getTaskEntityManager();
}
@Override
public TaskEntity createTask(TaskBuilder taskBuilder) {
return getTaskEntityManager().createTask(taskBuilder);
}
protected VariableServiceConfiguration getVariableServiceConfiguration(AbstractEngineConfiguration engineConfiguration) {
return (VariableServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_VARIABLE_SERVICE_CONFIG);
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SignAuthConfiguration implements WebMvcConfigurer {
@Resource
JeecgBaseConfig jeecgBaseConfig;
@Bean
public SignAuthInterceptor signAuthInterceptor() {
return new SignAuthInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//------------------------------------------------------------
//查询需要进行签名拦截的接口 signUrls
String signUrls = jeecgBaseConfig.getSignUrls();
String[] signUrlsArray = null;
if (StringUtils.isNotBlank(signUrls)) {
signUrlsArray = signUrls.split(",");
} else {
signUrlsArray = PathMatcherUtil.SIGN_URL_LIST;
}
//------------------------------------------------------------
registry.addInterceptor(signAuthInterceptor()).addPathPatterns(signUrlsArray);
}
// 代码逻辑说明: issues/I53J5E post请求X_SIGN签名拦截校验后报错, request body 为空
@Bean
public RequestBodyReserveFilter requestBodyReserveFilter(){
return new RequestBodyReserveFilter();
}
@Bean
public FilterRegistrationBean reqBodyFilterRegistrationBean(){
FilterRegistrationBean registration = new FilterRegistrationBean(); | registration.setFilter(requestBodyReserveFilter());
registration.setName("requestBodyReserveFilter");
//------------------------------------------------------------
//查询需要进行签名拦截的接口 signUrls
String signUrls = jeecgBaseConfig.getSignUrls();
String[] signUrlsArray = null;
if (StringUtils.isNotBlank(signUrls)) {
signUrlsArray = signUrls.split(",");
} else {
signUrlsArray = PathMatcherUtil.SIGN_URL_LIST;
}
//------------------------------------------------------------
// 建议此处只添加post请求地址而不是所有的都需要走过滤器
registration.addUrlPatterns(signUrlsArray);
return registration;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\interceptor\SignAuthConfiguration.java | 2 |
请完成以下Java代码 | String replace(String string, char oldChar, char newChar) {
return string.replace(oldChar, newChar);
}
@Contract(value = "true -> false; false -> true", pure = true)
boolean not(boolean input) {
return !input;
}
@Contract("true -> new")
void contractExpectsWrongParameterType(List<Integer> integers) {
}
@Contract("_, _ -> new")
void contractExpectsMoreParametersThanMethodHas(String s) {
}
@Contract("_ -> _; null -> !null")
String secondContractClauseNotReachable(String s) {
return "";
}
@Contract("_ -> true")
void contractExpectsWrongReturnType(String s) {
}
// NB: the following examples demonstrate how to use the mutates attribute of the annotation
// This attribute is currently experimental and could be changed or removed in the future | @Contract(mutates = "param")
void incrementArrayFirstElement(Integer[] integers) {
if (integers.length > 0) {
integers[0] = integers[0] + 1;
}
}
@Contract(pure = true, mutates = "param")
void impossibleToMutateParamInPureFunction(List<String> strings) {
if (strings != null) {
strings.forEach(System.out::println);
}
}
@Contract(mutates = "param3")
void impossibleToMutateThirdParamWhenMethodHasOnlyTwoParams(int a, int b) {
}
@Contract(mutates = "param")
void impossibleToMutableImmutableType(String s) {
}
@Contract(mutates = "this")
static void impossibleToMutateThisInStaticMethod() {
}
} | repos\tutorials-master\jetbrains-annotations\src\main\java\com\baeldung\annotations\Demo.java | 1 |
请完成以下Java代码 | private static boolean isContextAvailable(@Nullable final IValidationContext evalCtx)
{
return evalCtx != IValidationContext.NULL
&& evalCtx != IValidationContext.DISABLED;
}
@Nullable
private static PaySelectionTrxType extractPaySelectionTrxType(@Nullable final IValidationContext evalCtx)
{
if (!isContextAvailable(evalCtx))
{
return null;
}
final String code = evalCtx.get_ValueAsString(PARAM_PaySelectionTrxType);
if (Check.isBlank(code))
{ | return null;
}
return PaySelectionTrxType.ofCode(code);
}
@Nullable
private static PaySelectionMatchingMode extractPaySelectionMatchingMode(@Nullable final NamePair item)
{
return item != null
? PaySelectionMatchingMode.ofNullableCode(item.getID())
: null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\PaySelectionModeByPaySelectionTrxTypeValRule.java | 1 |
请完成以下Java代码 | public void enableAuthorizationCheck() {
authorizationCheckEnabled = true;
}
public void disableAuthorizationCheck() {
authorizationCheckEnabled = false;
}
public boolean isAuthorizationCheckEnabled() {
return authorizationCheckEnabled;
}
public void setAuthorizationCheckEnabled(boolean authorizationCheckEnabled) {
this.authorizationCheckEnabled = authorizationCheckEnabled;
}
public void enableUserOperationLog() {
userOperationLogEnabled = true;
}
public void disableUserOperationLog() {
userOperationLogEnabled = false;
}
public boolean isUserOperationLogEnabled() {
return userOperationLogEnabled;
}
public void setLogUserOperationEnabled(boolean userOperationLogEnabled) {
this.userOperationLogEnabled = userOperationLogEnabled;
}
public void enableTenantCheck() {
tenantCheckEnabled = true;
}
public void disableTenantCheck() {
tenantCheckEnabled = false;
}
public void setTenantCheckEnabled(boolean tenantCheckEnabled) {
this.tenantCheckEnabled = tenantCheckEnabled;
}
public boolean isTenantCheckEnabled() {
return tenantCheckEnabled;
}
public JobEntity getCurrentJob() {
return currentJob;
}
public void setCurrentJob(JobEntity currentJob) {
this.currentJob = currentJob;
}
public boolean isRestrictUserOperationLogToAuthenticatedUsers() {
return restrictUserOperationLogToAuthenticatedUsers;
} | public void setRestrictUserOperationLogToAuthenticatedUsers(boolean restrictUserOperationLogToAuthenticatedUsers) {
this.restrictUserOperationLogToAuthenticatedUsers = restrictUserOperationLogToAuthenticatedUsers;
}
public String getOperationId() {
if (!getOperationLogManager().isUserOperationLogEnabled()) {
return null;
}
if (operationId == null) {
operationId = Context.getProcessEngineConfiguration().getIdGenerator().getNextId();
}
return operationId;
}
public void setOperationId(String operationId) {
this.operationId = operationId;
}
public OptimizeManager getOptimizeManager() {
return getSession(OptimizeManager.class);
}
public <T> void executeWithOperationLogPrevented(Command<T> command) {
boolean initialLegacyRestrictions =
isRestrictUserOperationLogToAuthenticatedUsers();
disableUserOperationLog();
setRestrictUserOperationLogToAuthenticatedUsers(true);
try {
command.execute(this);
} finally {
enableUserOperationLog();
setRestrictUserOperationLogToAuthenticatedUsers(initialLegacyRestrictions);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\CommandContext.java | 1 |
请完成以下Java代码 | public class DoubleDataPoint extends AbstractDataPoint {
@Getter
private final double value;
public DoubleDataPoint(long ts, double value) {
super(ts);
this.value = value;
}
@Override
public DataType getType() {
return DataType.DOUBLE;
}
@Override
public double getDouble() {
return value; | }
@Override
public String valueToString() {
return Double.toString(value);
}
@Override
public int compareTo(DataPoint dataPoint) {
if (dataPoint.getType() == DataType.DOUBLE || dataPoint.getType() == DataType.LONG) {
return Double.compare(value, dataPoint.getDouble());
} else {
return super.compareTo(dataPoint);
}
}
} | repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\data\dp\DoubleDataPoint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setServicePrincipal(String servicePrincipal) {
this.servicePrincipal = servicePrincipal;
}
public void setKeyTabLocation(Resource keyTabLocation) {
this.keyTabLocation = keyTabLocation;
}
public void setUseTicketCache(Boolean useTicketCache) {
this.useTicketCache = useTicketCache;
}
public void setIsInitiator(Boolean isInitiator) {
this.isInitiator = isInitiator;
}
public void setDebug(Boolean debug) {
this.debug = debug;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.hasText(this.servicePrincipal, "servicePrincipal must be specified");
if (this.keyTabLocation != null && this.keyTabLocation instanceof ClassPathResource) {
LOG.warn(
"Your keytab is in the classpath. This file needs special protection and shouldn't be in the classpath. JAAS may also not be able to load this file from classpath.");
}
if (!this.useTicketCache) {
Assert.notNull(this.keyTabLocation, "keyTabLocation must be specified when useTicketCache is false");
}
if (this.keyTabLocation != null) {
this.keyTabLocationAsString = this.keyTabLocation.getURL().toExternalForm();
if (this.keyTabLocationAsString.startsWith("file:")) {
this.keyTabLocationAsString = this.keyTabLocationAsString.substring(5); | }
}
}
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
HashMap<String, String> options = new HashMap<>();
options.put("principal", this.servicePrincipal);
if (this.keyTabLocation != null) {
options.put("useKeyTab", "true");
options.put("keyTab", this.keyTabLocationAsString);
options.put("storeKey", "true");
}
options.put("doNotPrompt", "true");
if (this.useTicketCache) {
options.put("useTicketCache", "true");
options.put("renewTGT", "true");
}
options.put("isInitiator", this.isInitiator.toString());
options.put("debug", this.debug.toString());
return new AppConfigurationEntry[] { new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options), };
}
} | repos\spring-security-main\kerberos\kerberos-client\src\main\java\org\springframework\security\kerberos\client\config\SunJaasKrb5LoginConfig.java | 2 |
请完成以下Java代码 | public void setAD_Replication_Run_ID (int AD_Replication_Run_ID)
{
if (AD_Replication_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Replication_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Replication_Run_ID, Integer.valueOf(AD_Replication_Run_ID));
}
/** Get Replication Run.
@return Data Replication Run
*/
public int getAD_Replication_Run_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Replication_Run_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Replicated.
@param IsReplicated
The data is successfully replicated
*/
public void setIsReplicated (boolean IsReplicated)
{
set_ValueNoCheck (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated));
}
/** Get Replicated.
@return The data is successfully replicated
*/ | public boolean isReplicated ()
{
Object oo = get_Value(COLUMNNAME_IsReplicated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication_Run.java | 1 |
请完成以下Java代码 | public class RefreshRoutesEvent extends ApplicationEvent {
private final Map<String, Object> metadata;
/**
* Create a new ApplicationEvent.
* @param source the object on which the event initially occurred (never {@code null})
*/
public RefreshRoutesEvent(Object source) {
super(source);
metadata = Map.of();
}
/**
* Create a new ApplicationEvent that should refresh filtering by {@link #metadata}.
* @param source the object on which the event initially occurred (never {@code null}) | * @param metadata map of metadata the routes should match ({code null} is considered
* a global refresh)
*/
public RefreshRoutesEvent(Object source, Map<String, Object> metadata) {
super(source);
this.metadata = metadata;
}
public boolean isScoped() {
return !CollectionUtils.isEmpty(getMetadata());
}
public Map<String, Object> getMetadata() {
return metadata;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\event\RefreshRoutesEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | void disableGemFireShutdownHook(@Nullable Environment environment) {
System.setProperty(GEMFIRE_DISABLE_SHUTDOWN_HOOK, Boolean.TRUE.toString());
}
}
static abstract class CacheDataImporterExporterReference extends AbstractCacheDataImporterExporter {
static final String EXPORT_ENABLED_PROPERTY_NAME =
AbstractCacheDataImporterExporter.CACHE_DATA_EXPORT_ENABLED_PROPERTY_NAME;
}
static class DisableGemFireShutdownHookCondition extends AbstractDisableGemFireShutdownHookSupport
implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return shouldDisableGemFireShutdownHook(context.getEnvironment()); | }
}
public static class DisableGemFireShutdownHookEnvironmentPostProcessor
extends AbstractDisableGemFireShutdownHookSupport implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
if (shouldDisableGemFireShutdownHook(environment)) {
disableGemFireShutdownHook(environment);
}
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\DataImportExportAutoConfiguration.java | 2 |
请完成以下Java代码 | public void setParameter(PreparedStatement ps, int i, ByteArrayRef parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, getValueToSet(parameter));
}
private String getValueToSet(ByteArrayRef parameter) {
if (parameter == null) {
// Note that this should not happen: ByteArrayRefs should always be initialized.
return null;
}
return parameter.getId();
}
@Override
public ByteArrayRef getResult(ResultSet rs, String columnName) throws SQLException {
String id = rs.getString(columnName);
return createVariableByteArrayRef(id);
}
@Override
public ByteArrayRef getResult(ResultSet rs, int columnIndex) throws SQLException {
String id = rs.getString(columnIndex);
return createVariableByteArrayRef(id);
}
@Override
public ByteArrayRef getResult(CallableStatement cs, int columnIndex) throws SQLException {
String id = cs.getString(columnIndex);
return createVariableByteArrayRef(id);
}
protected ByteArrayRef createVariableByteArrayRef(String id) {
if (id == null) {
return null; | }
return new ByteArrayRef(id, getCommandExecutor());
}
protected CommandExecutor getCommandExecutor() {
CommandContext commandContext = Context.getCommandContext();
if (commandContext != null) {
// There is always a command context and engine here
// However, just to be extra safe do a null check
return commandContext.getCommandExecutor();
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\ByteArrayRefTypeHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getComment() {
return comment;
}
/**
* Sets the value of the comment property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComment(String value) {
this.comment = value;
}
/**
* Gets the value of the iaccount property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getIaccount() {
return iaccount;
}
/**
* Sets the value of the iaccount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIaccount(String value) {
this.iaccount = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Address.java | 2 |
请完成以下Java代码 | public int getAD_BoilerPlate_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_BoilerPlate_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Process getJasperProcess() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_JasperProcess_ID, org.compiere.model.I_AD_Process.class);
}
@Override
public void setJasperProcess(org.compiere.model.I_AD_Process JasperProcess)
{
set_ValueFromPO(COLUMNNAME_JasperProcess_ID, org.compiere.model.I_AD_Process.class, JasperProcess);
}
/** Set Jasper Process.
@param JasperProcess_ID
The Jasper Process used by the printengine if any process defined
*/
@Override
public void setJasperProcess_ID (int JasperProcess_ID)
{
if (JasperProcess_ID < 1)
set_Value (COLUMNNAME_JasperProcess_ID, null);
else
set_Value (COLUMNNAME_JasperProcess_ID, Integer.valueOf(JasperProcess_ID));
}
/** Get Jasper Process.
@return The Jasper Process used by the printengine if any process defined
*/
@Override
public int getJasperProcess_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_JasperProcess_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 Betreff.
@param Subject
Mail Betreff
*/
@Override
public void setSubject (java.lang.String Subject)
{
set_Value (COLUMNNAME_Subject, Subject);
}
/** Get Betreff.
@return Mail Betreff
*/
@Override
public java.lang.String getSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_Subject);
}
/** Set Text.
@param TextSnippet Text */
@Override
public void setTextSnippet (java.lang.String TextSnippet)
{
set_Value (COLUMNNAME_TextSnippet, TextSnippet);
}
/** Get Text.
@return Text */
@Override
public java.lang.String getTextSnippet ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextSnippet);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate.java | 1 |
请完成以下Java代码 | public static List toList() {
SecurityRatingEnum[] ary = SecurityRatingEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", ary[i].name());
map.put("desc", ary[i].getDesc());
list.add(map);
}
return list;
}
/**
* 取枚举的json字符串
* | * @return
*/
public static String getJsonStr() {
SecurityRatingEnum[] enums = SecurityRatingEnum.values();
StringBuffer jsonStr = new StringBuffer("[");
for (SecurityRatingEnum senum : enums) {
if (!"[".equals(jsonStr.toString())) {
jsonStr.append(",");
}
jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
}
jsonStr.append("]");
return jsonStr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\enums\SecurityRatingEnum.java | 1 |
请完成以下Java代码 | public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event)
{
final ManageSchedulerRequest request = extractManageSchedulerRequest(event);
try (final IAutoCloseable ignored = switchCtx(request);
final MDC.MDCCloseable ignored1 = MDC.putCloseable("eventHandler.className", handler.getClass().getName()))
{
eventLogUserService.invokeHandlerAndLog(EventLogUserService.InvokeHandlerAndLogRequest.builder()
.handlerClass(handler.getClass())
.invokaction(() -> handleRequest(request))
.build());
}
}
private void handleRequest(@NonNull final ManageSchedulerRequest request)
{
handler.handleRequest(request); | }
private IAutoCloseable switchCtx(@NonNull final ManageSchedulerRequest request)
{
final Properties ctx = createCtx(request);
return Env.switchContext(ctx);
}
private Properties createCtx(@NonNull final ManageSchedulerRequest request)
{
final Properties ctx = Env.newTemporaryCtx();
Env.setClientId(ctx, request.getClientId());
return ctx;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scheduler\eventbus\SchedulerEventBusService.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getDeductionPerAmount() {
return deductionPerAmount;
}
public void setDeductionPerAmount(Integer deductionPerAmount) {
this.deductionPerAmount = deductionPerAmount;
}
public Integer getMaxPercentPerOrder() {
return maxPercentPerOrder;
}
public void setMaxPercentPerOrder(Integer maxPercentPerOrder) {
this.maxPercentPerOrder = maxPercentPerOrder;
}
public Integer getUseUnit() {
return useUnit;
}
public void setUseUnit(Integer useUnit) {
this.useUnit = useUnit;
}
public Integer getCouponStatus() {
return couponStatus;
}
public void setCouponStatus(Integer couponStatus) {
this.couponStatus = couponStatus; | }
@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(", deductionPerAmount=").append(deductionPerAmount);
sb.append(", maxPercentPerOrder=").append(maxPercentPerOrder);
sb.append(", useUnit=").append(useUnit);
sb.append(", couponStatus=").append(couponStatus);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsIntegrationConsumeSetting.java | 1 |
请完成以下Java代码 | public class BBANStructureBuilder implements IBBANStructureBuilder
{
private BBANStructure _BBANStructure;
public BBANStructureBuilder()
{
_BBANStructure = new BBANStructure();
}
@Override
public BBANStructure create()
{
for (final BBANStructureEntryBuilder line : entryBuilders)
{
line.create(_BBANStructure);
}
// sort entries
sortEntries();
return _BBANStructure;
}
private final ArrayList<BBANStructureEntryBuilder> entryBuilders = new ArrayList<>();
@Override
public BBANStructureEntryBuilder addBBANStructureEntry()
{
final BBANStructureEntryBuilder entryBuilder = new BBANStructureEntryBuilder(this);
entryBuilders.add(entryBuilder);
return entryBuilder;
}
private void sortEntries()
{
List<BBANStructureEntry> listEntries = _BBANStructure.getEntries();
// if there is no entry , than we have BBAN structure
if (listEntries.isEmpty())
{
_BBANStructure = null;
return;
} | // order list by seqNo
Collections.sort(listEntries, (entry1, entry2) -> {
String seqNo1 = entry1.getSeqNo();
if (Check.isEmpty(seqNo1, true))
{
seqNo1 = "10";
}
String seqNo2 = entry2.getSeqNo();
if (Check.isEmpty(seqNo2, true))
{
seqNo2 = "20";
}
final int no1 = Integer.valueOf(seqNo1);
final int no2 = Integer.valueOf(seqNo2);
// order
if (no1 > no2)
{
return 1;
}
else if (no1 < no2)
{
return -1;
}
else
{
return 0;
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\BBANStructureBuilder.java | 1 |
请完成以下Java代码 | public String Table_Period (Properties ctx, int WindowNo,
GridTab mTab, GridField mField, Object value, Object oldValue)
{
Integer A_Depreciation_Table_Header_ID = (Integer)value;
try
{
if (A_Depreciation_Table_Header_ID != null){
String SQL = "SELECT A_Term "
+ "FROM A_Depreciation_Table_Header "
+ "WHERE A_Depreciation_Table_Header_ID='"
+A_Depreciation_Table_Header_ID
+"'";
PreparedStatement pstmt = DB.prepareStatement(SQL,null);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
// Charges - Set Context
Env.setContext(ctx, WindowNo, "A_DEPRECIATION_MANUAL_PERIOD", rs.getString("A_Term"));
mTab.setValue ("A_DEPRECIATION_MANUAL_PERIOD", rs.getString("A_Term"));
}
rs.close();
pstmt.close();
}
}
catch (SQLException e)
{
log.info("PeriodType "+ e);
return e.getLocalizedMessage();
}
return "";
} // Period Type
/**
* Field_Clear. Used to set the Manual Period Field. This allows
* the Spread Field to be displayed when there is a code that
* has been setup as Yearly.
* The string in the Callout field is:
* <code>com.compiere.custom.CalloutEngine.Table_Period</code>
*
* @param ctx Context
* @param WindowNo current Window No
* @param mTab Model Tab
* @param mField Model Field
* @param value The new value
* @param oldValue The old value
* @return error message or "" if OK
*/
public String Field_Clear (Properties ctx, int WindowNo,
GridTab mTab, GridField mField, Object value, Object oldValue)
{
Object A_Depreciation_ID = value;
try | {
String SQL = "SELECT DepreciationType "
+ "FROM A_Depreciation "
+ "WHERE A_Depreciation_ID="
+ A_Depreciation_ID;
PreparedStatement pstmt = DB.prepareStatement(SQL,null);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
// Charges - Set Context
if ( (!rs.getString("DepreciationType").equals("TAB")) || (!rs.getString("DepreciationType").equals("MAN")) )
{
Env.setContext(ctx, WindowNo, "A_DEPRECIATION_MANUAL_PERIOD", "");
//mTab.setValue ("A_Depreciation_Manual_Period", null);
mTab.setValue ("A_Depreciation_Manual_Amount", null);
mTab.setValue ("A_Depreciation_Table_Header_ID", null);
}
if (rs.getString("DepreciationType").equals("TAB"))
{
mTab.setValue ("A_Depreciation_Manual_Amount", null);
}
if (rs.getString("DepreciationType").equals("MAN"))
{
mTab.setValue ("A_Depreciation_Table_Header_ID", null);
}
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.info("PeriodType "+ e);
return e.getLocalizedMessage();
}
return "";
} // Period Type
} // CalloutFA | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\FA\CalloutFA.java | 1 |
请完成以下Java代码 | private ITranslatableString extractPickDate(final @NotNull DDOrderReference ddOrderReference)
{
return TranslatableStrings.dateAndTime(ddOrderReference.getDisplayDate());
}
private ITranslatableString extractPlant(final @NotNull DDOrderReference ddOrderReference)
{
final ResourceId plantId = ddOrderReference.getPlantId();
return plantId != null
? TranslatableStrings.anyLanguage(sourceDocService.getPlantName(plantId))
: TranslatableStrings.empty();
}
private static ITranslatableString extractQty(final @NotNull DDOrderReference ddOrderReference)
{
final Quantity qty = ddOrderReference.getQty();
return qty != null
? TranslatableStrings.builder().appendQty(qty.toBigDecimal(), qty.getUOMSymbol()).build()
: TranslatableStrings.empty();
}
private ITranslatableString extractProductValueAndName(final @NotNull DDOrderReference ddOrderReference)
{
final ProductId productId = ddOrderReference.getProductId();
return productId != null
? TranslatableStrings.anyLanguage(productService.getProductValueAndName(productId))
: TranslatableStrings.empty();
}
private @NotNull ITranslatableString extractGTIN(final @NotNull DDOrderReference ddOrderReference)
{
return Optional.ofNullable(ddOrderReference.getProductId())
.flatMap(productService::getGTIN)
.map(GTIN::getAsString)
.map(TranslatableStrings::anyLanguage)
.orElse(TranslatableStrings.empty());
}
@NonNull
private ITranslatableString extractSourceDoc(@NonNull final DDOrderReference ddOrderReference)
{
ImmutablePair<ITranslatableString, String> documentTypeAndNo;
if (ddOrderReference.getSalesOrderId() != null)
{ | documentTypeAndNo = sourceDocService.getDocumentTypeAndName(ddOrderReference.getSalesOrderId());
}
else if (ddOrderReference.getPpOrderId() != null)
{
documentTypeAndNo = sourceDocService.getDocumentTypeAndName(ddOrderReference.getPpOrderId());
}
else
{
return TranslatableStrings.empty();
}
return TranslatableStrings.builder()
.append(documentTypeAndNo.getLeft())
.append(" ")
.append(documentTypeAndNo.getRight())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DistributionLauncherCaptionProvider.java | 1 |
请完成以下Java代码 | public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
CommandContext commandContext = Context.getCommandContext();
ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
ExecutionEntity executionEntity = (ExecutionEntity) execution;
StartEvent startEvent = (StartEvent) execution.getCurrentFlowElement();
if (startEvent.isInterrupting()) {
List<ExecutionEntity> childExecutions = executionEntityManager.collectChildren(executionEntity.getParent());
Collection<String> executionIdsNotToDelete = new ArrayList<>();
for (int i = childExecutions.size() - 1; i >= 0; i--) {
ExecutionEntity childExecutionEntity = childExecutions.get(i);
if (childExecutionEntity.isEnded() || childExecutionEntity.getId().equals(executionEntity.getId())) {
executionIdsNotToDelete.add(childExecutionEntity.getId());
}
}
executionEntityManager.deleteChildExecutions(executionEntity.getParent(), executionIdsNotToDelete, null,
DeleteReason.EVENT_SUBPROCESS_INTERRUPTING + "(" + startEvent.getId() + ")", true, executionEntity.getCurrentFlowElement());
}
ExecutionEntity newSubProcessExecution = executionEntityManager.createChildExecution(executionEntity.getParent());
newSubProcessExecution.setCurrentFlowElement((SubProcess) executionEntity.getCurrentFlowElement().getParentContainer());
newSubProcessExecution.setEventScope(false);
newSubProcessExecution.setScope(true);
CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(newSubProcessExecution);
ExecutionEntity outgoingFlowExecution = executionEntityManager.createChildExecution(newSubProcessExecution);
outgoingFlowExecution.setCurrentFlowElement(startEvent);
CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(outgoingFlowExecution); | CommandContextUtil.getProcessEngineConfiguration(commandContext).getListenerNotificationHelper().executeExecutionListeners(
startEvent, outgoingFlowExecution, ExecutionListener.EVENTNAME_START);
leave(outgoingFlowExecution);
}
protected Map<String, Object> processDataObjects(Collection<ValuedDataObject> dataObjects) {
Map<String, Object> variablesMap = new HashMap<>();
// convert data objects to process variables
if (dataObjects != null) {
for (ValuedDataObject dataObject : dataObjects) {
variablesMap.put(dataObject.getName(), dataObject.getValue());
}
}
return variablesMap;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\EventSubProcessTimerStartEventActivityBehavior.java | 1 |
请完成以下Java代码 | public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
Optional<AnnotatedElement> element = context.getElement();
MergedAnnotations annotations = MergedAnnotations.from(element.get(),
MergedAnnotations.SearchStrategy.TYPE_HIERARCHY);
MergedAnnotation<LogLevels> mergedAnnotation = annotations.get(LogLevels.class);
if (mergedAnnotation.isPresent()) {
LogLevels loglevels = mergedAnnotation.synthesize();
Store store = context.getStore(Namespace.create(getClass(), context));
store.put(STORE_ANNOTATION_KEY, loglevels);
}
return ENABLED;
}
@Override
public void beforeAll(ExtensionContext context) {
Store store = context.getStore(Namespace.create(getClass(), context));
LogLevels logLevels = store.get(STORE_ANNOTATION_KEY, LogLevels.class);
if (logLevels != null) {
store.put(STORE_CONTAINER_KEY, JUnitUtils.adjustLogLevels(context.getDisplayName(),
Arrays.asList((logLevels.classes())),
Arrays.asList(logLevels.categories()),
Level.toLevel(logLevels.level())));
}
}
@Override
public void beforeEach(ExtensionContext context) {
Store store = context.getStore(Namespace.create(getClass(), context));
LogLevels logLevels = store.get(STORE_ANNOTATION_KEY, LogLevels.class);
if (logLevels != null) { // Method level annotation
if (store.get(STORE_CONTAINER_KEY) == null) {
store.put(STORE_CONTAINER_KEY, JUnitUtils.adjustLogLevels(context.getDisplayName(),
Arrays.asList((logLevels.classes())),
Arrays.asList(logLevels.categories()),
Level.toLevel(logLevels.level())));
}
}
else {
Optional<Method> testMethod = context.getTestMethod();
if (testMethod.isPresent()
&& this.loggedMethods.putIfAbsent(testMethod.get().getName(), Boolean.TRUE) == null) {
LOGGER.info(() -> "+++++++++++++++++++++++++++++ Begin " + testMethod.get().getName());
}
} | }
@Override
public void afterEach(ExtensionContext context) {
Store store = context.getStore(Namespace.create(getClass(), context));
LevelsContainer container = store.get(STORE_CONTAINER_KEY, LevelsContainer.class);
if (container != null) {
LogLevels logLevels = store.get(STORE_ANNOTATION_KEY, LogLevels.class);
if (logLevels != null) {
JUnitUtils.revertLevels(context.getDisplayName(), container);
store.remove(STORE_CONTAINER_KEY);
}
}
}
@Override
public void afterAll(ExtensionContext context) {
Store store = context.getStore(Namespace.create(getClass(), context));
LogLevels logLevels = store.remove(STORE_ANNOTATION_KEY, LogLevels.class);
if (logLevels != null) {
LevelsContainer container = store.get(STORE_CONTAINER_KEY, LevelsContainer.class);
if (container != null) {
JUnitUtils.revertLevels(context.getDisplayName(), container);
}
store.remove(STORE_CONTAINER_KEY);
}
this.loggedMethods.clear();
}
} | repos\spring-amqp-main\spring-rabbit-junit\src\main\java\org\springframework\amqp\rabbit\junit\LogLevelsCondition.java | 1 |
请完成以下Java代码 | public Collection<Attribute<?>> getAllAttributes() {
List<Attribute<?>> allAttributes = new ArrayList<Attribute<?>>();
allAttributes.addAll(getAttributes());
Collection<ModelElementType> baseTypes = ModelUtil.calculateAllBaseTypes(this);
for (ModelElementType baseType : baseTypes) {
allAttributes.addAll(baseType.getAttributes());
}
return allAttributes;
}
/**
* Return the attribute for the attribute name
*
* @param attributeName the name of the attribute
* @return the attribute or null if it not exists
*/
public Attribute<?> getAttribute(String attributeName) {
for (Attribute<?> attribute : getAllAttributes()) {
if (attribute.getAttributeName().equals(attributeName)) {
return attribute;
}
}
return null;
}
public ChildElementCollection<?> getChildElementCollection(ModelElementType childElementType) {
for (ChildElementCollection<?> childElementCollection : getChildElementCollections()) {
if (childElementType.equals(childElementCollection.getChildElementType(model))) {
return childElementCollection;
}
}
return null;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + ((model == null) ? 0 : model.hashCode());
result = prime * result + ((typeName == null) ? 0 : typeName.hashCode());
result = prime * result + ((typeNamespace == null) ? 0 : typeNamespace.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;
}
ModelElementTypeImpl other = (ModelElementTypeImpl) obj;
if (model == null) {
if (other.model != null) {
return false;
}
} else if (!model.equals(other.model)) {
return false;
}
if (typeName == null) {
if (other.typeName != null) {
return false;
}
} else if (!typeName.equals(other.typeName)) {
return false;
}
if (typeNamespace == null) {
if (other.typeNamespace != null) {
return false;
}
} else if (!typeNamespace.equals(other.typeNamespace)) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\ModelElementTypeImpl.java | 1 |
请完成以下Java代码 | public boolean isAlwaysUseArraysForDmnMultiHitPolicies() {
return alwaysUseArraysForDmnMultiHitPolicies;
}
public CmmnEngineConfiguration setAlwaysUseArraysForDmnMultiHitPolicies(boolean alwaysUseArraysForDmnMultiHitPolicies) {
this.alwaysUseArraysForDmnMultiHitPolicies = alwaysUseArraysForDmnMultiHitPolicies;
return this;
}
public CaseDefinitionLocalizationManager getCaseDefinitionLocalizationManager() {
return caseDefinitionLocalizationManager;
}
public CmmnEngineConfiguration setCaseDefinitionLocalizationManager(CaseDefinitionLocalizationManager caseDefinitionLocalizationManager) {
this.caseDefinitionLocalizationManager = caseDefinitionLocalizationManager;
return this;
} | public CaseLocalizationManager getCaseLocalizationManager() {
return caseLocalizationManager;
}
public CmmnEngineConfiguration setCaseLocalizationManager(CaseLocalizationManager caseLocalizationManager) {
this.caseLocalizationManager = caseLocalizationManager;
return this;
}
public PlanItemLocalizationManager getPlanItemLocalizationManager() {
return planItemLocalizationManager;
}
public CmmnEngineConfiguration setPlanItemLocalizationManager(PlanItemLocalizationManager planItemLocalizationManager) {
this.planItemLocalizationManager = planItemLocalizationManager;
return this;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ReferenceType getOrdrspReference() {
return ordrspReference;
}
/**
* Sets the value of the ordrspReference property.
*
* @param value
* allowed object is
* {@link ReferenceType }
*
*/
public void setOrdrspReference(ReferenceType value) {
this.ordrspReference = value;
}
/**
* Gets the value of the contractNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContractNumber() {
return contractNumber;
}
/**
* Sets the value of the contractNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContractNumber(String value) {
this.contractNumber = value;
}
/**
* Gets the value of the agreementNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAgreementNumber() {
return agreementNumber;
}
/**
* Sets the value of the agreementNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAgreementNumber(String value) {
this.agreementNumber = value; | }
/**
* Gets the value of the timeForPayment property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getTimeForPayment() {
return timeForPayment;
}
/**
* Sets the value of the timeForPayment property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setTimeForPayment(BigInteger value) {
this.timeForPayment = value;
}
/**
* Consignment reference.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConsignmentReference() {
return consignmentReference;
}
/**
* Sets the value of the consignmentReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsignmentReference(String value) {
this.consignmentReference = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\RECADVExtensionType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public Object getValue(ValueFields valueFields) {
if (valueFields.getLongValue() != null) {
return valueFields.getLongValue() == 1;
}
return null;
}
@Override
public void setValue(Object value, ValueFields valueFields) {
if (value == null) {
valueFields.setLongValue(null);
} else { | Boolean booleanValue = (Boolean) value;
if (booleanValue) {
valueFields.setLongValue(1L);
} else {
valueFields.setLongValue(0L);
}
}
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return Boolean.class.isAssignableFrom(value.getClass()) || boolean.class.isAssignableFrom(value.getClass());
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\BooleanType.java | 2 |
请完成以下Java代码 | public FileValue convertToTypedValue(UntypedValueImpl untypedValue) {
throw new UnsupportedOperationException("Currently no automatic conversation from UntypedValue to FileValue");
}
public FileValue readValue(TypedValueField value, boolean deserializeValue) {
Map<String, Object> valueInfo = value.getValueInfo();
String filename = (String) valueInfo.get(VALUE_INFO_FILE_NAME);
DeferredFileValueImpl fileValue = new DeferredFileValueImpl(filename, engineClient);
String mimeType = (String) valueInfo.get(VALUE_INFO_FILE_MIME_TYPE);
if (mimeType != null) {
fileValue.setMimeType(mimeType);
}
String encoding = (String) valueInfo.get(VALUE_INFO_FILE_ENCODING);
if (encoding != null) {
fileValue.setEncoding(encoding);
}
return fileValue;
}
public void writeValue(FileValue fileValue, TypedValueField typedValueField) {
Map<String, Object> valueInfo = new HashMap<>();
valueInfo.put(VALUE_INFO_FILE_NAME, fileValue.getFilename());
if (fileValue.getEncoding() != null) {
valueInfo.put(VALUE_INFO_FILE_ENCODING, fileValue.getEncoding());
}
if (fileValue.getMimeType() != null) {
valueInfo.put(VALUE_INFO_FILE_MIME_TYPE, fileValue.getMimeType());
}
typedValueField.setValueInfo(valueInfo);
byte[] bytes = ((FileValueImpl) fileValue).getByteArray(); | if (bytes != null) {
typedValueField.setValue(Base64.encodeBase64String(bytes));
}
}
protected boolean canWriteValue(TypedValue typedValue) {
if (typedValue == null || typedValue.getType() == null) {
// untyped value
return false;
}
return typedValue.getType().getName().equals(valueType.getName()) && !isDeferred(typedValue);
}
protected boolean canReadValue(TypedValueField typedValueField) {
Object value = typedValueField.getValue();
return value == null || value instanceof String;
}
protected boolean isDeferred(Object variableValue) {
return variableValue instanceof DeferredFileValue && !((DeferredFileValue) variableValue).isLoaded();
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\mapper\FileValueMapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DictionaryService {
private static final Logger logger = LoggerFactory.getLogger(DictionaryService.class);
static final Map<String, String> dictionary = new HashMap<>();
static {
dictionary.put("serendipity", "The occurrence and development of events by chance in a happy or beneficial way.");
dictionary.put("eloquent", "Fluent or persuasive in speaking or writing.");
dictionary.put("quintessential", "Representing the most perfect or typical example of a quality or class.");
dictionary.put("resilient", "Able to withstand or recover quickly from difficult conditions.");
dictionary.put("peregrinate", "To travel or wander from place to place, especially on foot.");
dictionary.put("susurrus", "A whispering or rustling sound, like that of leaves or the wind.");
dictionary.put("quixotic", "Extremely idealistic, unrealistic, and impractical.");
dictionary.put("lacuna", "An unfilled space or gap; a missing portion in a manuscript or text.");
dictionary.put("ephemeral", "Lasting for a very short time; transient.");
dictionary.put("syzygy", "The alignment of three celestial bodies in a straight line, commonly the Earth, Moon, and Sun.");
dictionary.put("pusillanimous", "Showing a lack of courage or determination; timid.");
dictionary.put("mellifluous", "(of a voice or words) Sweet or musical; pleasant to hear.");
dictionary.put("defenestration", "The act of throwing someone out of a window.");
dictionary.put("pulchritudinous", "Having great physical beauty or appeal.");
}
private final Random random = new Random();
public String getRandomWord() {
try { | // Randomly pause for a duration between 1 and 5 seconds
int delay = 1000 + random.nextInt(4000);
logger.info("Mandatory pause period of {} milliseconds", delay);
Thread.sleep(delay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Object[] words = dictionary.keySet().toArray();
return (String) words[random.nextInt(words.length)];
}
public String getWordMeaning(String word) {
return dictionary.getOrDefault(word, "Meaning not found.");
}
} | repos\tutorials-master\libraries-open-telemetry\otel-collector\dictionary-service\src\main\java\com\baeldung\DictionaryService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class GetProductFromFileRouteBuilder extends IdAwareRouteBuilder
{
public static final String UPSERT_PRODUCT_PROCESSOR_ID = "GetProductFromFileRouteBuilder.UPSERT_PRODUCT_PROCESSOR_ID";
public static final String UPSERT_PRODUCT_ENDPOINT_ID = "GetProductFromFileRouteBuilder.UPSERT_PRODUCT_ENDPOINT_ID";
@NonNull
private final ProductFileEndpointConfig fileEndpointConfig;
@Getter
@NonNull
private final String routeId;
@NonNull
private final JsonExternalSystemRequest enabledByExternalSystemRequest;
@NonNull
private final PInstanceLogger pInstanceLogger;
@Builder
private GetProductFromFileRouteBuilder(
@NonNull final ProductFileEndpointConfig fileEndpointConfig,
@NonNull final CamelContext camelContext,
@NonNull final String routeId,
@NonNull final JsonExternalSystemRequest enabledByExternalSystemRequest,
@NonNull final ProcessLogger processLogger)
{
super(camelContext);
this.fileEndpointConfig = fileEndpointConfig;
this.routeId = routeId;
this.enabledByExternalSystemRequest = enabledByExternalSystemRequest;
this.pInstanceLogger = PInstanceLogger.builder()
.processLogger(processLogger)
.pInstanceId(enabledByExternalSystemRequest.getAdPInstanceId())
.build();
}
@Override
public void configure()
{
//@formatter:off
from(fileEndpointConfig.getProductFileEndpoint())
.id(routeId)
.streamCache("true")
.log("Product Sync Route Started with Id=" + routeId)
.process(exchange -> PInstanceUtil.setPInstanceHeader(exchange, enabledByExternalSystemRequest)) | .split(body().tokenize("\n"))
.streaming()
.process(exchange -> PInstanceUtil.setPInstanceHeader(exchange, enabledByExternalSystemRequest))
.filter(new SkipFirstLinePredicate())
.doTry()
.unmarshal(new BindyCsvDataFormat(ProductRow.class))
.process(getProductUpsertProcessor()).id(UPSERT_PRODUCT_PROCESSOR_ID)
.choice()
.when(bodyAs(ProductUpsertCamelRequest.class).isNull())
.log(LoggingLevel.INFO, "Nothing to do! No product to upsert!")
.otherwise()
.log(LoggingLevel.DEBUG, "Calling metasfresh-api to upsert Product: ${body}")
.to(direct(MF_UPSERT_PRODUCT_V2_CAMEL_URI)).id(UPSERT_PRODUCT_ENDPOINT_ID)
.endChoice()
.end()
.endDoTry()
.doCatch(Throwable.class)
.to(direct(ERROR_WRITE_TO_ADISSUE))
.end()
.end();
//@formatter:on
}
@NonNull
private ProductUpsertProcessor getProductUpsertProcessor()
{
return ProductUpsertProcessor.builder()
.externalSystemRequest(enabledByExternalSystemRequest)
.pInstanceLogger(pInstanceLogger)
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\product\GetProductFromFileRouteBuilder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<T> listByColumn(Map<String, Object> paramMap) {
if (paramMap == null) {
return null;
}
return sessionTemplate.selectList(getStatement(SQL_LIST_BY_COLUMN), paramMap);
}
/**
* 根据column查询记录数.
*/
public Long getCountByColumn(Map<String, Object> paramMap) {
if (paramMap == null) {
return null;
}
return sessionTemplate.selectOne(getStatement(SQL_COUNT_BY_COLUMN), paramMap);
}
/**
* 根据id删除数据.
*/
public int delete(Long id) {
return (int) sessionTemplate.delete(getStatement(SQL_DELETE_BY_ID), id);
}
/**
* 根据id批量删除数据.
*/
public int delete(List<T> list) {
if (list.isEmpty() || list.size() <= 0) {
return 0;
} else {
return (int) sessionTemplate.delete(getStatement(SQL_BATCH_DELETE_BY_IDS), list);
}
}
/**
* 根据column批量删除数据.
*/
public int delete(Map<String, Object> paramMap) {
if (paramMap == null) {
return 0;
} else {
return (int) sessionTemplate.delete(getStatement(SQL_BATCH_DELETE_BY_COLUMN), paramMap);
}
}
/**
* 分页查询数据 .
*/
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) {
if (paramMap == null) {
paramMap = new HashMap<String, Object>();
}
// 统计总记录数
Long totalCount = sessionTemplate.selectOne(getStatement(SQL_LIST_PAGE_COUNT), paramMap); | // 校验当前页数
int currentPage = PageBean.checkCurrentPage(totalCount.intValue(), pageParam.getNumPerPage(), pageParam.getPageNum());
pageParam.setPageNum(currentPage); // 为当前页重新设值
// 校验页面输入的每页记录数numPerPage是否合法
int numPerPage = PageBean.checkNumPerPage(pageParam.getNumPerPage()); // 校验每页记录数
pageParam.setNumPerPage(numPerPage); // 重新设值
// 根据页面传来的分页参数构造SQL分页参数
paramMap.put("pageFirst", (pageParam.getPageNum() - 1) * pageParam.getNumPerPage());
paramMap.put("pageSize", pageParam.getNumPerPage());
paramMap.put("startRowNum", (pageParam.getPageNum() - 1) * pageParam.getNumPerPage());
paramMap.put("endRowNum", pageParam.getPageNum() * pageParam.getNumPerPage());
// 获取分页数据集
List<Object> list = sessionTemplate.selectList(getStatement(SQL_LIST_PAGE), paramMap);
Object isCount = paramMap.get("isCount"); // 是否统计当前分页条件下的数据:1:是,其他为否
if (isCount != null && "1".equals(isCount.toString())) {
Map<String, Object> countResultMap = sessionTemplate.selectOne(getStatement(SQL_COUNT_BY_PAGE_PARAM), paramMap);
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), totalCount.intValue(), list, countResultMap);
} else {
// 构造分页对象
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), totalCount.intValue(), list);
}
}
/**
* 函数功能说明 : 获取Mapper命名空间. 修改者名字: Along 修改日期: 2016-1-8 修改内容:
*
* @参数:@param sqlId
* @参数:@return
* @return:String
* @throws
*/
public String getStatement(String sqlId) {
String name = this.getClass().getName();
// 单线程用StringBuilder,确保速度;多线程用StringBuffer,确保安全
StringBuilder sb = new StringBuilder();
sb.append(name).append(".").append(sqlId);
return sb.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\dao\impl\PermissionBaseDaoImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<String> getTagFields() {
return this.tagFields;
}
public void setRemoteFields(List<String> remoteFields) {
this.remoteFields = remoteFields;
}
public void setLocalFields(List<String> localFields) {
this.localFields = localFields;
}
public void setTagFields(List<String> tagFields) {
this.tagFields = tagFields;
}
public static class Correlation {
/**
* Whether to enable correlation of the baggage context with logging contexts.
*/
private boolean enabled = true;
/**
* List of fields that should be correlated with the logging context. That
* means that these fields would end up as key-value pairs in e.g. MDC.
*/
private List<String> fields = new ArrayList<>();
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public List<String> getFields() {
return this.fields;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
}
}
public static class Propagation {
/**
* Tracing context propagation types produced and consumed by the application.
* Setting this property overrides the more fine-grained propagation type
* properties.
*/
private @Nullable List<PropagationType> type;
/**
* Tracing context propagation types produced by the application.
*/
private List<PropagationType> produce = List.of(PropagationType.W3C);
/**
* Tracing context propagation types consumed by the application.
*/
private List<PropagationType> consume = List.of(PropagationType.values());
public void setType(@Nullable List<PropagationType> type) {
this.type = type;
}
public void setProduce(List<PropagationType> produce) { | this.produce = produce;
}
public void setConsume(List<PropagationType> consume) {
this.consume = consume;
}
public @Nullable List<PropagationType> getType() {
return this.type;
}
public List<PropagationType> getProduce() {
return this.produce;
}
public List<PropagationType> getConsume() {
return this.consume;
}
/**
* Supported propagation types. The declared order of the values matter.
*/
public enum PropagationType {
/**
* <a href="https://www.w3.org/TR/trace-context/">W3C</a> propagation.
*/
W3C,
/**
* <a href="https://github.com/openzipkin/b3-propagation#single-header">B3
* single header</a> propagation.
*/
B3,
/**
* <a href="https://github.com/openzipkin/b3-propagation#multiple-headers">B3
* multiple headers</a> propagation.
*/
B3_MULTI
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\TracingProperties.java | 2 |
请完成以下Java代码 | protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
ServiceTask serviceTask = new ServiceTask();
serviceTask.setType(ServiceTask.DMN_TASK);
JsonNode decisionTableReferenceNode = getProperty(PROPERTY_DECISIONTABLE_REFERENCE, elementNode);
if (
decisionTableReferenceNode != null &&
decisionTableReferenceNode.has("id") &&
!(decisionTableReferenceNode.get("id").isNull())
) {
String decisionTableId = decisionTableReferenceNode.get("id").asText();
if (decisionTableMap != null) {
String decisionTableKey = decisionTableMap.get(decisionTableId);
FieldExtension decisionTableKeyField = new FieldExtension();
decisionTableKeyField.setFieldName(PROPERTY_DECISIONTABLE_REFERENCE_KEY);
decisionTableKeyField.setStringValue(decisionTableKey);
serviceTask.getFieldExtensions().add(decisionTableKeyField);
}
} | return serviceTask;
}
@Override
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {}
@Override
public void setDecisionTableMap(Map<String, String> decisionTableMap) {
this.decisionTableMap = decisionTableMap;
}
protected void addExtensionAttributeToExtension(ExtensionElement element, String attributeName, String value) {
ExtensionAttribute extensionAttribute = new ExtensionAttribute(NAMESPACE, attributeName);
extensionAttribute.setNamespacePrefix("modeler");
extensionAttribute.setValue(value);
element.addAttribute(extensionAttribute);
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\DecisionTaskJsonConverter.java | 1 |
请完成以下Java代码 | public void setR_Status_ID (int R_Status_ID)
{
if (R_Status_ID < 1)
set_Value (COLUMNNAME_R_Status_ID, null);
else
set_Value (COLUMNNAME_R_Status_ID, Integer.valueOf(R_Status_ID));
}
/** Get Status.
@return Request Status
*/
public int getR_Status_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Request Status.
@param R_Status_Value Request Status */
public void setR_Status_Value (String R_Status_Value)
{
set_Value (COLUMNNAME_R_Status_Value, R_Status_Value);
}
/** Get Request Status.
@return Request Status */
public String getR_Status_Value ()
{
return (String)get_Value(COLUMNNAME_R_Status_Value);
} | public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_RV_R_Group_Prospect.java | 1 |
请完成以下Java代码 | public boolean hasNext()
{
addingLocked = true;
while (!iterators.isEmpty())
{
final Iterator<E> it = iterators.get(0);
final boolean hasNext = it.hasNext();
if (hasNext)
{
return true;
}
final Iterator<E> removedIterator = iterators.remove(0);
IteratorUtils.close(removedIterator);
}
return false;
}
@Override
public E next()
{
addingLocked = true; | return iterators.get(0).next();
}
@Override
public void remove()
{
iterators.get(0).remove();
addingLocked = true;
}
@Override
public void close()
{
for (final Iterator<?> iterator : iterators)
{
IteratorUtils.close(iterator);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\IteratorChain.java | 1 |
请完成以下Java代码 | public String toString()
{
// NOTE: we are making it translateable friendly because it's displayed in Prefereces->Info->Rollen
final String preferenceTypeName;
if (this == NONE)
{
preferenceTypeName = "@None@";
}
else if (this == CLIENT)
{
preferenceTypeName = "@AD_Client_ID@";
}
else if (this == ORGANIZATION)
{
preferenceTypeName = "@AD_Org_ID@";
}
else if (this == USER)
{
preferenceTypeName = "@AD_User_ID@";
}
else
{
// shall not happen
preferenceTypeName = preferenceType;
}
return "@PreferenceType@: " + preferenceTypeName;
}
/** @return false, i.e. never inherit this constraint because it shall be defined by current role itself */
@Override
public boolean isInheritable()
{
return false;
}
/**
* @return preference type (see X_AD_Role.PREFERENCETYPE_*)
*/
public String getPreferenceType()
{
return preferenceType;
}
/**
* Show (Value) Preference Menu
*
* @return true if preference type is not {@link #NONE}.
*/
public boolean isShowPreference()
{
return !isNone();
} | public boolean isNone()
{
return this == NONE;
}
public boolean isClient()
{
return this == CLIENT;
}
public boolean isOrganization()
{
return this == ORGANIZATION;
}
public boolean isUser()
{
return this == USER;
}
/**
*
* @return true if this level allows user to view table record change log (i.e. this level is {@link #CLIENT})
*/
public boolean canViewRecordChangeLog()
{
return isClient();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\UserPreferenceLevelConstraint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PropertyConversion {
private Duration timeInDefaultUnit;
private Duration timeInNano;
@DurationUnit(ChronoUnit.DAYS)
private Duration timeInDays;
private DataSize sizeInDefaultUnit;
private DataSize sizeInGB;
@DataSizeUnit(DataUnit.TERABYTES)
private DataSize sizeInTB;
private Employee employee;
// Getters and setters
public Duration getTimeInDefaultUnit() {
return timeInDefaultUnit;
}
public void setTimeInDefaultUnit(Duration timeInDefaultUnit) {
this.timeInDefaultUnit = timeInDefaultUnit;
}
public Duration getTimeInNano() {
return timeInNano;
}
public void setTimeInNano(Duration timeInNano) {
this.timeInNano = timeInNano;
}
public Duration getTimeInDays() {
return timeInDays;
}
public void setTimeInDays(Duration timeInDays) {
this.timeInDays = timeInDays;
}
public DataSize getSizeInDefaultUnit() {
return sizeInDefaultUnit; | }
public void setSizeInDefaultUnit(DataSize sizeInDefaultUnit) {
this.sizeInDefaultUnit = sizeInDefaultUnit;
}
public DataSize getSizeInGB() {
return sizeInGB;
}
public void setSizeInGB(DataSize sizeInGB) {
this.sizeInGB = sizeInGB;
}
public DataSize getSizeInTB() {
return sizeInTB;
}
public void setSizeInTB(DataSize sizeInTB) {
this.sizeInTB = sizeInTB;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\java\com\baeldung\configurationproperties\PropertyConversion.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CustomPredicatesConfig {
@Bean
public GoldenCustomerRoutePredicateFactory goldenCustomer(GoldenCustomerService goldenCustomerService) {
return new GoldenCustomerRoutePredicateFactory(goldenCustomerService);
}
//@Bean
public RouteLocator routes(RouteLocatorBuilder builder, GoldenCustomerRoutePredicateFactory gf ) {
return builder.routes()
.route("dsl_golden_route", r ->
r.predicate(gf.apply(new Config(true, "customerId")))
.and() | .path("/dsl_api/**")
.filters(f -> f.stripPrefix(1))
.uri("https://httpbin.org")
)
.route("dsl_common_route", r ->
r.predicate(gf.apply(new Config(false, "customerId")))
.and()
.path("/dsl_api/**")
.filters(f -> f.stripPrefix(1))
.uri("https://httpbin.org")
)
.build();
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\spring-cloud-gateway-intro\src\main\java\com\baeldung\springcloudgateway\custompredicates\config\CustomPredicatesConfig.java | 2 |
请完成以下Java代码 | public static TimerJobEntity rescheduleTimerJob(String timerJobId, TimerEventDefinition timerEventDefinition) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
TimerJobService timerJobService = processEngineConfiguration.getJobServiceConfiguration().getTimerJobService();
TimerJobEntity timerJob = timerJobService.findTimerJobById(timerJobId);
if (timerJob != null) {
BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(timerJob.getProcessDefinitionId());
Event eventElement = (Event) bpmnModel.getFlowElement(TimerEventHandler.getActivityIdFromConfiguration(timerJob.getJobHandlerConfiguration()));
boolean isInterruptingTimer = false;
if (eventElement instanceof BoundaryEvent) {
isInterruptingTimer = ((BoundaryEvent) eventElement).isCancelActivity();
}
ExecutionEntity execution = processEngineConfiguration.getExecutionEntityManager().findById(timerJob.getExecutionId());
TimerJobEntity rescheduledTimerJob = TimerUtil.createTimerEntityForTimerEventDefinition(timerEventDefinition,
eventElement, isInterruptingTimer, execution,
timerJob.getJobHandlerType(), timerJob.getJobHandlerConfiguration());
timerJobService.deleteTimerJob(timerJob);
timerJobService.insertTimerJob(rescheduledTimerJob);
FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableEventBuilder.createJobRescheduledEvent(FlowableEngineEventType.JOB_RESCHEDULED,
rescheduledTimerJob, timerJob.getId()), processEngineConfiguration.getEngineCfgKey());
// job rescheduled event should occur before new timer scheduled event
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.TIMER_SCHEDULED, rescheduledTimerJob), | processEngineConfiguration.getEngineCfgKey());
}
return rescheduledTimerJob;
}
return null;
}
public static String prepareRepeat(String dueDate) {
if (dueDate.startsWith("R") && dueDate.split("/").length == 2) {
Clock clock = CommandContextUtil.getProcessEngineConfiguration().getClock();
return dueDate.replace("/", "/" + clock.getCurrentTime().toInstant().toString() + "/");
}
return dueDate;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\TimerUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Optional<ExternalProjectReference> getByRequestOptional(@NonNull final GetExternalProjectRequest getExternalProjectRequest)
{
return queryBL.createQueryBuilder(I_S_ExternalProjectReference.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_S_ExternalProjectReference.COLUMNNAME_ExternalSystem_ID, getExternalProjectRequest.getExternalSystem().getId().getRepoId())
.addEqualsFilter(I_S_ExternalProjectReference.COLUMNNAME_ExternalReference, getExternalProjectRequest.getExternalReference())
.addEqualsFilter(I_S_ExternalProjectReference.COLUMNNAME_ExternalProjectOwner, getExternalProjectRequest.getExternalProjectOwner())
.create()
.firstOnlyOptional(I_S_ExternalProjectReference.class)
.map(this::buildExternalProjectReference);
}
@NonNull
public ExternalProjectReference getById(@NonNull final ExternalProjectReferenceId externalProjectReferenceId)
{
final I_S_ExternalProjectReference record = InterfaceWrapperHelper.load(externalProjectReferenceId, I_S_ExternalProjectReference.class);
return buildExternalProjectReference(record);
}
@NonNull
private ExternalProjectReference buildExternalProjectReference(@NonNull final I_S_ExternalProjectReference record)
{
final Optional<ExternalProjectType> externalProjectType = ExternalProjectType.getTypeByValue(record.getProjectType()); | if (!externalProjectType.isPresent())
{
throw new AdempiereException("Unknown project type!")
.appendParametersToMessage()
.setParameter(I_S_ExternalProjectReference.COLUMNNAME_S_ExternalProjectReference_ID, record.getS_ExternalProjectReference_ID())
.setParameter(I_S_ExternalProjectReference.COLUMNNAME_ProjectType, record.getProjectType());
}
return ExternalProjectReference.builder()
.externalProjectReferenceId(ExternalProjectReferenceId.ofRepoId(record.getS_ExternalProjectReference_ID()))
.externalProjectReference(record.getExternalReference())
.projectOwner(record.getExternalProjectOwner())
.externalProjectType(externalProjectType.get())
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\external\project\ExternalProjectRepository.java | 2 |
请完成以下Java代码 | public void deleteComments() {
ensureHistoryEnabled(Status.FORBIDDEN);
ensureProcessInstanceExists(Status.NOT_FOUND);
TaskService taskService = engine.getTaskService();
try {
taskService.deleteProcessInstanceComments(processInstanceId);
} catch (AuthorizationException e) {
throw e;
} catch (NullValueException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
}
private void ensureHistoryEnabled(Status status) {
if (!isHistoryEnabled()) {
throw new InvalidRequestException(status, "History is not enabled");
}
}
private boolean isHistoryEnabled() {
IdentityService identityService = engine.getIdentityService();
Authentication currentAuthentication = identityService.getCurrentAuthentication();
try {
identityService.clearAuthentication(); | int historyLevel = engine.getManagementService().getHistoryLevel();
return historyLevel > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE;
} finally {
identityService.setAuthentication(currentAuthentication);
}
}
private void ensureProcessInstanceExists(Status status) {
HistoricProcessInstance historicProcessInstance = engine.getHistoryService().createHistoricProcessInstanceQuery()
.processInstanceId(processInstanceId).singleResult();
if (historicProcessInstance == null) {
throw new InvalidRequestException(status, "No process instance found for id " + processInstanceId);
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\ProcessInstanceCommentResourceImpl.java | 1 |
请完成以下Java代码 | public VertragsdatenTag getTag() {
return tag;
}
/**
* Sets the value of the tag property.
*
* @param value
* allowed object is
* {@link VertragsdatenTag }
*
*/
public void setTag(VertragsdatenTag value) {
this.tag = value;
}
/**
* Gets the value of the zeitpunkt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar } | *
*/
public XMLGregorianCalendar getZeitpunkt() {
return zeitpunkt;
}
/**
* Sets the value of the zeitpunkt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setZeitpunkt(XMLGregorianCalendar value) {
this.zeitpunkt = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VertragsdatenHauptbestellzeit.java | 1 |
请完成以下Java代码 | private static final class IssueCandidate
{
// Services
private final transient IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
//
@NonNull private final I_PP_Order_BOMLine orderBOMLine;
@NonNull private final ProductId productId;
//
@NonNull @Setter(AccessLevel.NONE) private Quantity qtyToIssue;
private final Set<I_M_HU> husToAssign = new TreeSet<>(HUByIdComparator.instance);
@Setter(AccessLevel.NONE)
@Getter(AccessLevel.NONE)
private final Map<Integer, MaterialTrackingWithQuantity> id2materialTracking = new HashMap<>();
private IssueCandidate(
@NonNull final I_PP_Order_BOMLine ppOrderBOMLine,
@NonNull final ProductId productId)
{
this.orderBOMLine = ppOrderBOMLine;
this.productId = productId;
final IPPOrderBOMBL orderBOMBL = Services.get(IPPOrderBOMBL.class);
final I_C_UOM uom = orderBOMBL.getBOMLineUOM(ppOrderBOMLine);
qtyToIssue = Quantity.zero(uom);
}
public ImmutableSet<MaterialTrackingWithQuantity> getMaterialTrackings()
{
return ImmutableSet.copyOf(id2materialTracking.values());
}
/**
* @param huToAssign HU to be assigned to generated cost collector
*/
public void addQtyToIssue(@NonNull final ProductId productId, @NonNull final Quantity qtyToIssueToAdd, @NonNull final I_M_HU huToAssign)
{
// Validate
if (!ProductId.equals(productId, this.productId))
{
throw new HUException("Invalid product to issue."
+ "\nExpected: " + this.productId
+ "\nGot: " + productId
+ "\n@PP_Order_BOMLine_ID@: " + orderBOMLine); | }
final UOMConversionContext uomConversionCtx = UOMConversionContext.of(productId);
final Quantity qtyToIssueToAddConv = uomConversionBL.convertQuantityTo(qtyToIssueToAdd, uomConversionCtx, qtyToIssue.getUOM());
qtyToIssue = qtyToIssue.add(qtyToIssueToAddConv);
husToAssign.add(huToAssign);
}
private void addMaterialTracking(
@NonNull final I_M_Material_Tracking materialTracking,
@NonNull final Quantity quantity)
{
MaterialTrackingWithQuantity materialTrackingWithQuantity = this.id2materialTracking.get(materialTracking.getM_Material_Tracking_ID());
if (materialTrackingWithQuantity == null)
{
materialTrackingWithQuantity = new MaterialTrackingWithQuantity(materialTracking);
this.id2materialTracking.put(materialTracking.getM_Material_Tracking_ID(), materialTrackingWithQuantity);
}
materialTrackingWithQuantity.addQuantity(quantity);
}
public boolean isZeroQty()
{
return getQtyToIssue().isZero();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\HUPPOrderIssueReceiptCandidatesProcessor.java | 1 |
请完成以下Java代码 | public class CoapResourceObserver implements ResourceObserver {
@Override
public void changedName(String old) {
}
@Override
public void changedPath(String old) {
}
@Override
public void addedChild(Resource child) {
}
@Override
public void removedChild(Resource child) {
}
@Override
public void addedObserveRelation(ObserveRelation relation) {
}
@Override
public void removedObserveRelation(ObserveRelation relation) {
}
}
private void sendOtaData(CoapExchange exchange) {
String idStr = exchange.getRequestOptions().getUriPath().get(exchange.getRequestOptions().getUriPath().size() - 1
);
UUID currentId = UUID.fromString(idStr);
Response response = new Response(CoAP.ResponseCode.CONTENT);
byte[] otaData = this.getOtaData(currentId);
if (otaData != null && otaData.length > 0) { | log.debug("Read ota data (length): [{}]", otaData.length);
response.setPayload(otaData);
if (exchange.getRequestOptions().getBlock2() != null) {
int szx = exchange.getRequestOptions().getBlock2().getSzx();
int chunkSize = exchange.getRequestOptions().getBlock2().getSize();
boolean lastFlag = otaData.length <= chunkSize;
response.getOptions().setBlock2(szx, lastFlag, 0);
log.trace("With block2 Send currentId: [{}], length: [{}], chunkSize [{}], szx [{}], moreFlag [{}]", currentId, otaData.length, chunkSize, szx, lastFlag);
} else {
log.trace("With block1 Send currentId: [{}], length: [{}], ", currentId, otaData.length);
}
exchange.respond(response);
} else {
log.trace("Ota packaged currentId: [{}] is not found.", currentId);
}
}
private byte[] getOtaData(UUID currentId) {
return otaPackageDataCache.get(currentId.toString());
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\LwM2mTransportCoapResource.java | 1 |
请完成以下Java代码 | public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
} | @Override
public boolean isEnabled() {
return true;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
} | repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\security\UserPrincipal.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean hasErrors() {
return !this.errors.isEmpty();
}
/**
* Return error details regarding the validation attempt
* @return the collection of results in this result, if any; returns an empty list
* otherwise
*/
public Collection<Saml2Error> getErrors() {
return Collections.unmodifiableCollection(this.errors);
}
/**
* Return a new {@link Saml2ResponseValidatorResult} that contains both the given
* {@link Saml2Error} and the errors from the result
* @param error the {@link Saml2Error} to append
* @return a new {@link Saml2ResponseValidatorResult} for further reporting
*/
public Saml2ResponseValidatorResult concat(Saml2Error error) {
Assert.notNull(error, "error cannot be null");
Collection<Saml2Error> errors = new ArrayList<>(this.errors);
errors.add(error);
return failure(errors);
}
/**
* Return a new {@link Saml2ResponseValidatorResult} that contains the errors from the
* given {@link Saml2ResponseValidatorResult} as well as this result.
* @param result the {@link Saml2ResponseValidatorResult} to merge with this one
* @return a new {@link Saml2ResponseValidatorResult} for further reporting
*/
public Saml2ResponseValidatorResult concat(Saml2ResponseValidatorResult result) {
Assert.notNull(result, "result cannot be null");
Collection<Saml2Error> errors = new ArrayList<>(this.errors);
errors.addAll(result.getErrors());
return failure(errors);
}
/**
* Construct a successful {@link Saml2ResponseValidatorResult}
* @return an {@link Saml2ResponseValidatorResult} with no errors | */
public static Saml2ResponseValidatorResult success() {
return NO_ERRORS;
}
/**
* Construct a failure {@link Saml2ResponseValidatorResult} with the provided detail
* @param errors the list of errors
* @return an {@link Saml2ResponseValidatorResult} with the errors specified
*/
public static Saml2ResponseValidatorResult failure(Saml2Error... errors) {
return failure(Arrays.asList(errors));
}
/**
* Construct a failure {@link Saml2ResponseValidatorResult} with the provided detail
* @param errors the list of errors
* @return an {@link Saml2ResponseValidatorResult} with the errors specified
*/
public static Saml2ResponseValidatorResult failure(Collection<Saml2Error> errors) {
if (errors.isEmpty()) {
return NO_ERRORS;
}
return new Saml2ResponseValidatorResult(errors);
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\core\Saml2ResponseValidatorResult.java | 2 |
请完成以下Java代码 | public void takeWhileAndTakeUntilStream() {
Stream<Integer> infiniteInts = Stream.iterate(0, i -> i + 1);
Stream<Integer> finiteIntsWhileLessThan10 = StreamUtils.takeWhile(infiniteInts, i -> i < 10);
Stream<Integer> finiteIntsUntilGreaterThan10 = StreamUtils.takeUntil(infiniteInts, i -> i > 10);
}
public void skipWhileAndSkipUntilStream() {
Stream<Integer> ints = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> skippedWhileConditionMet = StreamUtils.skipWhile(ints, i -> i < 4);
Stream<Integer> skippedUntilConditionMet = StreamUtils.skipWhile(ints, i -> i > 4);
}
public void unfoldStream() {
Stream<Integer> unfolded = StreamUtils.unfold(1, i -> (i < 10) ? Optional.of(i + 1) : Optional.empty());
}
public void windowedStream() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
List<List<Integer>> windows = StreamUtils.windowed(integerStream, 2).collect(toList());
List<List<Integer>> windowsWithSkipIndex = StreamUtils.windowed(integerStream, 3, 2).collect(toList()); | List<List<Integer>> windowsWithSkipIndexAndAllowLowerSize = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList());
}
public void groupRunsStreams() {
Stream<Integer> integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5);
List<List<Integer>> runs = StreamUtils.groupRuns(integerStream).collect(toList());
}
public void aggreagateOnBiElementPredicate() {
Stream<String> stream = Stream.of("a1", "b1", "b2", "c1");
Stream<List<String>> aggregated = StreamUtils.aggregate(stream, (e1, e2) -> e1.charAt(0) == e2.charAt(0));
}
} | repos\tutorials-master\libraries\src\main\java\com\baeldung\protonpack\StreamUtilsExample.java | 1 |
请完成以下Java代码 | public void setDownloadOptionsHeaderValue(@Nullable String downloadOptionHeaderValue) {
this.downloadOptionsHeaderValue = downloadOptionHeaderValue;
}
public @Nullable String getPermittedCrossDomainPoliciesHeaderValue() {
return permittedCrossDomainPoliciesHeaderValue;
}
public void setPermittedCrossDomainPoliciesHeaderValue(
@Nullable String permittedCrossDomainPoliciesHeaderValue) {
this.permittedCrossDomainPoliciesHeaderValue = permittedCrossDomainPoliciesHeaderValue;
}
public @Nullable String getPermissionPolicyHeaderValue() {
return permissionPolicyHeaderValue;
}
public void setPermissionPolicyHeaderValue(@Nullable String permissionPolicyHeaderValue) {
this.permissionPolicyHeaderValue = permissionPolicyHeaderValue;
}
/**
* bind the route specific/opt-in header names to enable, in lower case.
*/
void setEnable(Set<String> enable) {
if (enable != null) {
this.routeFilterConfigProvided = true;
this.routeEnabledHeaders = enable.stream()
.map(String::toLowerCase)
.collect(Collectors.toUnmodifiableSet());
}
}
/**
* @return the route specific/opt-in header names to enable, in lower case.
*/
Set<String> getRouteEnabledHeaders() {
return routeEnabledHeaders;
}
/**
* bind the route specific/opt-out header names to disable, in lower case.
*/
void setDisable(Set<String> disable) {
if (disable != null) {
this.routeFilterConfigProvided = true;
this.routeDisabledHeaders = disable.stream()
.map(String::toLowerCase)
.collect(Collectors.toUnmodifiableSet());
}
}
/**
* @return the route specific/opt-out header names to disable, in lower case
*/
Set<String> getRouteDisabledHeaders() {
return routeDisabledHeaders;
} | /**
* @return the route specific/opt-out permission policies.
*/
protected @Nullable String getRoutePermissionsPolicyHeaderValue() {
return routePermissionsPolicyHeaderValue;
}
/**
* bind the route specific/opt-out permissions policy.
*/
void setPermissionsPolicy(@Nullable String permissionsPolicy) {
this.routeFilterConfigProvided = true;
this.routePermissionsPolicyHeaderValue = permissionsPolicy;
}
/**
* @return flag whether route specific arguments were bound.
*/
boolean isRouteFilterConfigProvided() {
return routeFilterConfigProvided;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SecureHeadersGatewayFilterFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
System.out.println("\nInsert new book to an author ...");
System.out.println("---------------------------------------------");
bookstoreService.insertNewBook();
System.out.println("---------------------------------------------");
System.out.println("\nList all books of an author ...");
System.out.println("---------------------------------------------");
bookstoreService.fetchBooksOfAuthorById(); | System.out.println("---------------------------------------------");
System.out.println("\nList a page books (first page with two books) of an author ...");
System.out.println("---------------------------------------------");
bookstoreService.fetchPageBooksOfAuthorById();
System.out.println("---------------------------------------------");
System.out.println("\nFetch a list of books and add new book ...");
System.out.println("---------------------------------------------");
bookstoreService.fetchBooksOfAuthorByIdAndAddNewBook();
System.out.println("---------------------------------------------");
System.out.println("\nFetch a list of books and delete the first book ...");
System.out.println("---------------------------------------------");
bookstoreService.fetchBooksOfAuthorByIdAndDeleteFirstBook();
System.out.println("---------------------------------------------");
};
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootJustManyToOne\src\main\java\com\bookstore\MainApplication.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected static class RabbitTemplateConfiguration {
@Bean
@ConditionalOnMissingBean
RabbitTemplateConfigurer rabbitTemplateConfigurer(RabbitProperties properties,
ObjectProvider<MessageConverter> messageConverter,
ObjectProvider<RabbitTemplateRetrySettingsCustomizer> retrySettingsCustomizers) {
RabbitTemplateConfigurer configurer = new RabbitTemplateConfigurer(properties);
configurer.setMessageConverter(messageConverter.getIfUnique());
configurer.setRetrySettingsCustomizers(retrySettingsCustomizers.orderedStream().toList());
return configurer;
}
@Bean
@ConditionalOnSingleCandidate(ConnectionFactory.class)
@ConditionalOnMissingBean(RabbitOperations.class)
RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory,
ObjectProvider<RabbitTemplateCustomizer> customizers) {
RabbitTemplate template = new RabbitTemplate();
configurer.configure(template, connectionFactory);
customizers.orderedStream().forEach((customizer) -> customizer.customize(template));
return template;
}
@Bean
@ConditionalOnSingleCandidate(ConnectionFactory.class)
@ConditionalOnBooleanProperty(name = "spring.rabbitmq.dynamic", matchIfMissing = true)
@ConditionalOnMissingBean
AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
} | }
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RabbitMessagingTemplate.class)
@ConditionalOnMissingBean(RabbitMessagingTemplate.class)
@Import(RabbitTemplateConfiguration.class)
protected static class RabbitMessagingTemplateConfiguration {
@Bean
@ConditionalOnSingleCandidate(RabbitTemplate.class)
RabbitMessagingTemplate rabbitMessagingTemplate(RabbitTemplate rabbitTemplate) {
return new RabbitMessagingTemplate(rabbitTemplate);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int update(Long id, PmsProductAttributeParam productAttributeParam) {
PmsProductAttribute pmsProductAttribute = new PmsProductAttribute();
pmsProductAttribute.setId(id);
BeanUtils.copyProperties(productAttributeParam, pmsProductAttribute);
return productAttributeMapper.updateByPrimaryKeySelective(pmsProductAttribute);
}
@Override
public PmsProductAttribute getItem(Long id) {
return productAttributeMapper.selectByPrimaryKey(id);
}
@Override
public int delete(List<Long> ids) {
//获取分类
PmsProductAttribute pmsProductAttribute = productAttributeMapper.selectByPrimaryKey(ids.get(0));
Integer type = pmsProductAttribute.getType();
PmsProductAttributeCategory pmsProductAttributeCategory = productAttributeCategoryMapper.selectByPrimaryKey(pmsProductAttribute.getProductAttributeCategoryId());
PmsProductAttributeExample example = new PmsProductAttributeExample();
example.createCriteria().andIdIn(ids);
int count = productAttributeMapper.deleteByExample(example);
//删除完成后修改数量 | if(type==0){
if(pmsProductAttributeCategory.getAttributeCount()>=count){
pmsProductAttributeCategory.setAttributeCount(pmsProductAttributeCategory.getAttributeCount()-count);
}else{
pmsProductAttributeCategory.setAttributeCount(0);
}
}else if(type==1){
if(pmsProductAttributeCategory.getParamCount()>=count){
pmsProductAttributeCategory.setParamCount(pmsProductAttributeCategory.getParamCount()-count);
}else{
pmsProductAttributeCategory.setParamCount(0);
}
}
productAttributeCategoryMapper.updateByPrimaryKey(pmsProductAttributeCategory);
return count;
}
@Override
public List<ProductAttrInfo> getProductAttrInfo(Long productCategoryId) {
return productAttributeDao.getProductAttrInfo(productCategoryId);
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductAttributeServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class DataSourceBeanCreationFailureAnalyzer extends AbstractFailureAnalyzer<DataSourceBeanCreationException> {
private final Environment environment;
DataSourceBeanCreationFailureAnalyzer(Environment environment) {
this.environment = environment;
}
@Override
protected FailureAnalysis analyze(Throwable rootFailure, DataSourceBeanCreationException cause) {
return getFailureAnalysis(cause);
}
private FailureAnalysis getFailureAnalysis(DataSourceBeanCreationException cause) {
String description = getDescription(cause);
String action = getAction(cause);
return new FailureAnalysis(description, action, cause);
}
private String getDescription(DataSourceBeanCreationException cause) {
StringBuilder description = new StringBuilder();
description.append("Failed to configure a DataSource: ");
if (!StringUtils.hasText(cause.getProperties().getUrl())) {
description.append("'url' attribute is not specified and ");
}
description.append(String.format("no embedded datasource could be configured.%n"));
description.append(String.format("%nReason: %s%n", cause.getMessage()));
return description.toString();
}
private String getAction(DataSourceBeanCreationException cause) {
StringBuilder action = new StringBuilder();
action.append(String.format("Consider the following:%n"));
if (EmbeddedDatabaseConnection.NONE == cause.getConnection()) {
action.append(String
.format("\tIf you want an embedded database (H2, HSQL or Derby), please put it on the classpath.%n"));
}
else {
action.append(String.format("\tReview the configuration of %s%n.", cause.getConnection()));
} | action
.append("\tIf you have database settings to be loaded from a particular "
+ "profile you may need to activate it")
.append(getActiveProfiles());
return action.toString();
}
private String getActiveProfiles() {
StringBuilder message = new StringBuilder();
String[] profiles = this.environment.getActiveProfiles();
if (ObjectUtils.isEmpty(profiles)) {
message.append(" (no profiles are currently active).");
}
else {
message.append(" (the profiles ");
message.append(StringUtils.arrayToCommaDelimitedString(profiles));
message.append(" are currently active).");
}
return message.toString();
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceBeanCreationFailureAnalyzer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private ServiceRepairProjectTaskStatus computeStatus()
{
final @NonNull ServiceRepairProjectTaskType type = getType();
switch (type)
{
case REPAIR_ORDER:
return computeStatusForRepairOrderType();
case SPARE_PARTS:
return computeStatusForSparePartsType();
default:
throw new AdempiereException("Unknown type for " + this);
}
}
private ServiceRepairProjectTaskStatus computeStatusForRepairOrderType()
{
if (getRepairOrderId() == null)
{
return ServiceRepairProjectTaskStatus.NOT_STARTED;
}
else
{
return isRepairOrderDone()
? ServiceRepairProjectTaskStatus.COMPLETED
: ServiceRepairProjectTaskStatus.IN_PROGRESS;
}
}
private ServiceRepairProjectTaskStatus computeStatusForSparePartsType()
{
if (getQtyToReserve().signum() <= 0)
{
return ServiceRepairProjectTaskStatus.COMPLETED;
}
else if (getQtyReservedOrConsumed().signum() == 0)
{
return ServiceRepairProjectTaskStatus.NOT_STARTED;
} | else
{
return ServiceRepairProjectTaskStatus.IN_PROGRESS;
}
}
public ServiceRepairProjectTask withRepairOrderId(@NonNull final PPOrderId repairOrderId)
{
return toBuilder()
.repairOrderId(repairOrderId)
.build()
.withUpdatedStatus();
}
public ServiceRepairProjectTask withRepairOrderDone(
@Nullable final String repairOrderSummary,
@Nullable final ProductId repairServicePerformedId)
{
return toBuilder()
.isRepairOrderDone(true)
.repairOrderSummary(repairOrderSummary)
.repairServicePerformedId(repairServicePerformedId)
.build()
.withUpdatedStatus();
}
public ServiceRepairProjectTask withRepairOrderNotDone()
{
return toBuilder()
.isRepairOrderDone(false)
.repairOrderSummary(null)
.repairServicePerformedId(null)
.build()
.withUpdatedStatus();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\model\ServiceRepairProjectTask.java | 2 |
请完成以下Java代码 | public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* @return the webappProperty
*/
public WebappProperty getWebappProperty() {
return webappProperty;
}
/**
* @param webappProperty
* webappProperty to set
*/
public void setWebappProperty(WebappProperty webappProperty) { | this.webappProperty = webappProperty;
}
/**
* @param input - String to trim
* @param charachter - Char to trim
* @return the trimmed String
*/
protected String trimChar(String input, char charachter) {
input = StringUtils.trimLeadingCharacter(input, charachter);
input = StringUtils.trimTrailingCharacter(input, charachter);
return input;
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\filter\ResourceLoadingProcessEnginesFilter.java | 1 |
请完成以下Java代码 | public void segment(String text, List<String> output)
{
String normalized = normalize(text);
segment(text, normalized, output);
}
public void segment(String text, String normalized, List<String> output)
{
if (text.isEmpty()) return;
Instance instance = new CWSInstance(normalized, model.featureMap);
segment(text, instance, output);
}
public void segment(String text, Instance instance, List<String> output)
{
int[] tagArray = instance.tagArray;
model.viterbiDecode(instance, tagArray);
StringBuilder result = new StringBuilder();
result.append(text.charAt(0));
for (int i = 1; i < tagArray.length; i++)
{
if (tagArray[i] == CWSTagSet.B || tagArray[i] == CWSTagSet.S)
{
output.add(result.toString());
result.setLength(0);
}
result.append(text.charAt(i));
}
if (result.length() != 0)
{
output.add(result.toString());
}
}
public List<String> segment(String sentence)
{
List<String> result = new LinkedList<String>();
segment(sentence, result);
return result;
}
/**
* 在线学习
*
* @param segmentedSentence 分好词的句子,空格或tab分割,不含词性
* @return 是否学习成功(失败的原因是参数错误)
*/
public boolean learn(String segmentedSentence)
{
return learn(segmentedSentence.split("\\s+"));
} | /**
* 在线学习
*
* @param words 分好词的句子
* @return 是否学习成功(失败的原因是参数错误)
*/
public boolean learn(String... words)
{
// for (int i = 0; i < words.length; i++) // 防止传入带词性的词语
// {
// int index = words[i].indexOf('/');
// if (index > 0)
// {
// words[i] = words[i].substring(0, index);
// }
// }
return learn(new CWSInstance(words, model.featureMap));
}
@Override
protected Instance createInstance(Sentence sentence, FeatureMap featureMap)
{
return CWSInstance.create(sentence, featureMap);
}
@Override
public double[] evaluate(String corpora) throws IOException
{
// 这里用CWS的F1
double[] prf = Utility.prf(Utility.evaluateCWS(corpora, this));
return prf;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronSegmenter.java | 1 |
请完成以下Java代码 | public class Lane implements HasDIBounds {
protected String id;
protected String name;
protected List<String> flowNodeIds;
protected int x = -1;
protected int y = -1;
protected int width = -1;
protected int height = -1;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() { | return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public List<String> getFlowNodeIds() {
if(flowNodeIds == null) {
flowNodeIds = new ArrayList<String>();
}
return flowNodeIds;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\Lane.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JwtTokenFilter extends OncePerRequestFilter {
@Autowired private UserRepository userRepository;
@Autowired private JwtService jwtService;
private final String header = "Authorization";
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
getTokenString(request.getHeader(header))
.flatMap(token -> jwtService.getSubFromToken(token))
.ifPresent(
id -> {
if (SecurityContextHolder.getContext().getAuthentication() == null) {
userRepository
.findById(id)
.ifPresent(
user -> {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(
user, null, Collections.emptyList());
authenticationToken.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
});
}
});
filterChain.doFilter(request, response); | }
private Optional<String> getTokenString(String header) {
if (header == null) {
return Optional.empty();
} else {
String[] split = header.split(" ");
if (split.length < 2) {
return Optional.empty();
} else {
return Optional.ofNullable(split[1]);
}
}
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\security\JwtTokenFilter.java | 2 |
请完成以下Java代码 | public String updateProcessBusinessKey(String bzKey) {
if (isProcessInstanceType() && bzKey != null) {
setBusinessKey(bzKey);
Context.getCommandContext().getHistoryManager().updateProcessBusinessKeyInHistory(this);
if (Context.getProcessEngineConfiguration() != null && Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, this),
EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
}
return bzKey;
}
return null;
}
public void deleteIdentityLink(String userId, String groupId, String type) {
List<IdentityLinkEntity> identityLinks = Context.getCommandContext().getIdentityLinkEntityManager()
.findIdentityLinkByProcessInstanceUserGroupAndType(id, userId, groupId, type);
for (IdentityLinkEntity identityLink : identityLinks) {
Context.getCommandContext().getIdentityLinkEntityManager().deleteIdentityLink(identityLink, true);
}
getIdentityLinks().removeAll(identityLinks);
}
// NOT IN V5
@Override
public boolean isMultiInstanceRoot() {
return false;
} | @Override
public void setMultiInstanceRoot(boolean isMultiInstanceRoot) {
}
@Override
public String getPropagatedStageInstanceId() {
return null;
}
protected void callJobProcessors(JobProcessorContext.Phase processorType, AbstractJobEntity abstractJobEntity, ProcessEngineConfigurationImpl processEngineConfiguration) {
JobProcessorContextImpl jobProcessorContext = new JobProcessorContextImpl(processorType, abstractJobEntity);
for (JobProcessor jobProcessor : processEngineConfiguration.getJobProcessors()) {
jobProcessor.process(jobProcessorContext);
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntity.java | 1 |
请完成以下Java代码 | protected CommandInterceptor createTransactionInterceptor(boolean requiresNew) {
return new JakartaTransactionInterceptor(transactionManager, requiresNew, this);
}
@Override
protected void initTransactionManager() {
if(transactionManager == null){
if(transactionManagerJndiName == null || transactionManagerJndiName.length() == 0) {
throw LOG.invalidConfigTransactionManagerIsNull();
}
try {
transactionManager = (TransactionManager) new InitialContext().lookup(transactionManagerJndiName);
} catch(NamingException e) {
throw LOG.invalidConfigCannotFindTransactionManger(transactionManagerJndiName+"'.", e);
}
} | }
@Override
protected void initTransactionContextFactory() {
if(transactionContextFactory == null) {
transactionContextFactory = new JakartaTransactionContextFactory(transactionManager);
}
}
public TransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\JakartaTransactionProcessEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String toString() {
return "Actuator root web endpoint";
}
private void sendFailureResponse(HttpServletResponse response, SecurityResponse securityResponse) {
try {
response.sendError(securityResponse.getStatus().value(), securityResponse.getMessage());
}
catch (Exception ex) {
logger.debug("Failed to send error response", ex);
}
}
}
/**
* {@link ServletWebOperation} wrapper to add security.
*/
private static class SecureServletWebOperation implements ServletWebOperation {
private final ServletWebOperation delegate;
private final SecurityInterceptor securityInterceptor;
private final EndpointId endpointId;
SecureServletWebOperation(ServletWebOperation delegate, SecurityInterceptor securityInterceptor,
EndpointId endpointId) {
this.delegate = delegate;
this.securityInterceptor = securityInterceptor;
this.endpointId = endpointId;
}
@Override
public @Nullable Object handle(HttpServletRequest request, @Nullable Map<String, String> body) {
SecurityResponse securityResponse = this.securityInterceptor.preHandle(request, this.endpointId);
if (!securityResponse.getStatus().equals(HttpStatus.OK)) {
return new ResponseEntity<Object>(securityResponse.getMessage(), securityResponse.getStatus());
}
return this.delegate.handle(request, body); | }
}
static class CloudFoundryWebEndpointServletHandlerMappingRuntimeHints implements RuntimeHintsRegistrar {
private final ReflectiveRuntimeHintsRegistrar reflectiveRegistrar = new ReflectiveRuntimeHintsRegistrar();
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.reflectiveRegistrar.registerRuntimeHints(hints, CloudFoundryLinksHandler.class);
this.bindingRegistrar.registerReflectionHints(hints.reflection(), Link.class);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\servlet\CloudFoundryWebEndpointServletHandlerMapping.java | 2 |
请完成以下Java代码 | public void setC_ReferenceNo_Type_ID (int C_ReferenceNo_Type_ID)
{
if (C_ReferenceNo_Type_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_Type_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_Type_ID, Integer.valueOf(C_ReferenceNo_Type_ID));
}
/** Get Reference No Type.
@return Reference No Type */
@Override
public int getC_ReferenceNo_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_Type_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{ | return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo_Type_Table.java | 1 |
请完成以下Java代码 | public InventoryLine withInventoryLineHUs(@NonNull final List<InventoryLineHU> newInventoryLineHUs)
{
return toBuilder()
.huAggregationType(computeHUAggregationType(newInventoryLineHUs, this.huAggregationType))
.clearInventoryLineHUs()
.inventoryLineHUs(newInventoryLineHUs)
.build();
}
public InventoryLine withCounting(@NonNull final InventoryLineCountRequest request)
{
final ArrayList<InventoryLineHU> newLineHUs = new ArrayList<>(inventoryLineHUs.size() + 1);
boolean updated = false;
boolean isSingleLineHUPlaceholder = inventoryLineHUs.size() == 1
&& inventoryLineHUs.get(0).getId() == null
&& inventoryLineHUs.get(0).getHuId() == null;
if (!isSingleLineHUPlaceholder)
{
for (InventoryLineHU lineHU : inventoryLineHUs)
{
if (!updated && HuId.equals(lineHU.getHuId(), request.getHuId()))
{
newLineHUs.add(lineHU.updatingFrom(request));
updated = true;
}
else
{
newLineHUs.add(lineHU);
}
}
}
if (!updated)
{
newLineHUs.add(InventoryLineHU.of(request));
}
return toBuilder()
.huAggregationType(computeHUAggregationType(newLineHUs, this.huAggregationType))
.qtyCountFixed(computeQtyCountSum(newLineHUs))
.clearInventoryLineHUs()
.inventoryLineHUs(newLineHUs) | .counted(newLineHUs.stream().allMatch(InventoryLineHU::isCounted))
.build();
}
@Nullable
private static HUAggregationType computeHUAggregationType(
@NonNull final List<InventoryLineHU> newInventoryLineHUs,
@Nullable final HUAggregationType prevHUAggregationType)
{
return newInventoryLineHUs.size() > 1 ? HUAggregationType.MULTI_HU : prevHUAggregationType;
}
public boolean isEligibleForCounting()
{
return !isCounted();
}
public InventoryLineHU getInventoryLineHUById(@NonNull final InventoryLineHUId id)
{
return inventoryLineHUs.stream()
.filter(lineHU -> InventoryLineHUId.equals(lineHU.getId(), id))
.findFirst()
.orElseThrow(() -> new AdempiereException("No Line HU found for " + id + " in " + this));
}
public Optional<InventoryLineHU> getInventoryLineHUByHUId(@NonNull final HuId huId)
{
return inventoryLineHUs.stream()
.filter(lineHU -> HuId.equals(lineHU.getHuId(), huId))
.findFirst();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLine.java | 1 |
请完成以下Java代码 | public static String toString(JSONArray ja) throws JSONException {
JSONObject jo = ja.optJSONObject(0);
if (jo != null) {
JSONArray names = jo.names();
if (names != null) {
return rowToString(names) + toString(names, ja);
}
}
return null;
}
/**
* Produce a comma delimited text from a JSONArray of JSONObjects using a provided list of names. The list of names is not included in the output.
*
* @param names
* A JSONArray of strings.
* @param ja
* A JSONArray of JSONObjects. | * @return A comma delimited text.
* @throws JSONException
*/
public static String toString(JSONArray names, JSONArray ja) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ja.length(); i += 1) {
JSONObject jo = ja.optJSONObject(i);
if (jo != null) {
sb.append(rowToString(jo.toJSONArray(names)));
}
}
return sb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\CDL.java | 1 |
请完成以下Java代码 | public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReporter() {
return reporter; | }
public void setReporter(String reporter) {
this.reporter = reporter;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\metrics\MetricsIntervalResultDto.java | 1 |
请完成以下Java代码 | public static class Demand {
@XmlAttribute(name = "tc_demand_id", required = true)
protected long tcDemandId;
@XmlAttribute(name = "tc_token", required = true)
protected String tcToken;
@XmlAttribute(name = "insurance_demand_date", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar insuranceDemandDate;
@XmlAttribute(name = "insurance_demand_id")
protected String insuranceDemandId;
/**
* Gets the value of the tcDemandId property.
*
*/
public long getTcDemandId() {
return tcDemandId;
}
/**
* Sets the value of the tcDemandId property.
*
*/
public void setTcDemandId(long value) {
this.tcDemandId = value;
}
/**
* Gets the value of the tcToken property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTcToken() {
return tcToken;
}
/**
* Sets the value of the tcToken property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTcToken(String value) {
this.tcToken = value;
} | /**
* Gets the value of the insuranceDemandDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getInsuranceDemandDate() {
return insuranceDemandDate;
}
/**
* Sets the value of the insuranceDemandDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setInsuranceDemandDate(XMLGregorianCalendar value) {
this.insuranceDemandDate = value;
}
/**
* Gets the value of the insuranceDemandId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInsuranceDemandId() {
return insuranceDemandId;
}
/**
* Sets the value of the insuranceDemandId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInsuranceDemandId(String value) {
this.insuranceDemandId = 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\ProcessingType.java | 1 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
return Objects.equals(this.text, ((PemContent) obj).text);
}
@Override
public int hashCode() {
return Objects.hash(this.text);
}
@Override
public String toString() {
return this.text;
}
/**
* Load {@link PemContent} from the given content (either the PEM content itself or a
* reference to the resource to load).
* @param content the content to load
* @param resourceLoader the resource loader used to load content
* @return a new {@link PemContent} instance or {@code null}
* @throws IOException on IO error
*/
static @Nullable PemContent load(@Nullable String content, ResourceLoader resourceLoader) throws IOException {
if (!StringUtils.hasLength(content)) {
return null;
}
if (isPresentInText(content)) {
return new PemContent(content);
}
try (InputStream in = resourceLoader.getResource(content).getInputStream()) {
return load(in);
}
catch (IOException | UncheckedIOException ex) {
throw new IOException("Error reading certificate or key from file '%s'".formatted(content), ex);
}
}
/**
* Load {@link PemContent} from the given {@link Path}.
* @param path a path to load the content from
* @return the loaded PEM content
* @throws IOException on IO error
*/
public static PemContent load(Path path) throws IOException {
Assert.notNull(path, "'path' must not be null");
try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) { | return load(in);
}
}
/**
* Load {@link PemContent} from the given {@link InputStream}.
* @param in an input stream to load the content from
* @return the loaded PEM content
* @throws IOException on IO error
*/
public static PemContent load(InputStream in) throws IOException {
return of(StreamUtils.copyToString(in, StandardCharsets.UTF_8));
}
/**
* Return a new {@link PemContent} instance containing the given text.
* @param text the text containing PEM encoded content
* @return a new {@link PemContent} instance
*/
@Contract("!null -> !null")
public static @Nullable PemContent of(@Nullable String text) {
return (text != null) ? new PemContent(text) : null;
}
/**
* Return if PEM content is present in the given text.
* @param text the text to check
* @return if the text includes PEM encoded content.
*/
public static boolean isPresentInText(@Nullable String text) {
return text != null && PEM_HEADER.matcher(text).find() && PEM_FOOTER.matcher(text).find();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemContent.java | 1 |
请完成以下Java代码 | public class TransitionInstanceHandler implements MigratingInstanceParseHandler<TransitionInstance> {
@Override
public void handle(MigratingInstanceParseContext parseContext, TransitionInstance transitionInstance) {
if (!isAsyncTransitionInstance(transitionInstance)) {
return;
}
MigrationInstruction applyingInstruction = parseContext.getInstructionFor(transitionInstance.getActivityId());
ScopeImpl sourceScope = parseContext.getSourceProcessDefinition().findActivity(transitionInstance.getActivityId());
ScopeImpl targetScope = null;
if (applyingInstruction != null) {
String activityId = applyingInstruction.getTargetActivityId();
targetScope = parseContext.getTargetProcessDefinition().findActivity(activityId);
}
ExecutionEntity asyncExecution = Context
.getCommandContext()
.getExecutionManager()
.findExecutionById(transitionInstance.getExecutionId());
MigratingTransitionInstance migratingTransitionInstance = parseContext.getMigratingProcessInstance()
.addTransitionInstance(
applyingInstruction,
transitionInstance,
sourceScope,
targetScope,
asyncExecution);
MigratingActivityInstance parentInstance = parseContext.getMigratingActivityInstanceById(transitionInstance.getParentActivityInstanceId());
migratingTransitionInstance.setParent(parentInstance);
List<JobEntity> jobs = asyncExecution.getJobs();
parseContext.handleDependentTransitionInstanceJobs(migratingTransitionInstance, jobs); | parseContext.handleDependentVariables(migratingTransitionInstance, collectTransitionInstanceVariables(migratingTransitionInstance));
}
/**
* Workaround for CAM-5609: In general, only async continuations should be represented as TransitionInstances, but
* due to this bug, completed multi-instances are represented like that as well. We tolerate the second case.
*/
protected boolean isAsyncTransitionInstance(TransitionInstance transitionInstance) {
String executionId = transitionInstance.getExecutionId();
ExecutionEntity execution = Context.getCommandContext().getExecutionManager().findExecutionById(executionId);
for (JobEntity job : execution.getJobs()) {
if (AsyncContinuationJobHandler.TYPE.equals(job.getJobHandlerType())) {
return true;
}
}
return false;
}
protected List<VariableInstanceEntity> collectTransitionInstanceVariables(MigratingTransitionInstance instance) {
List<VariableInstanceEntity> variables = new ArrayList<VariableInstanceEntity>();
ExecutionEntity representativeExecution = instance.resolveRepresentativeExecution();
if (representativeExecution.isConcurrent()) {
variables.addAll(representativeExecution.getVariablesInternal());
}
else {
variables.addAll(ActivityInstanceHandler.getConcurrentLocalVariables(representativeExecution));
}
return variables;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\TransitionInstanceHandler.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
LATCH.await();
Thread.sleep(5_000);
context.close();
}
@Bean
public RecordMessageConverter converter() {
return new JsonMessageConverter();
}
@Bean
public BatchMessagingMessageConverter batchConverter() {
return new BatchMessagingMessageConverter(converter());
}
@Bean
public NewTopic topic2() {
return TopicBuilder.name("topic2").partitions(1).replicas(1).build();
}
@Bean
public NewTopic topic3() {
return TopicBuilder.name("topic3").partitions(1).replicas(1).build();
}
} | @Component
class Listener {
private static final Logger LOGGER = LoggerFactory.getLogger(Listener.class);
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@KafkaListener(id = "fooGroup2", topics = "topic2")
public void listen1(List<Foo2> foos) throws IOException {
LOGGER.info("Received: " + foos);
foos.forEach(f -> kafkaTemplate.send("topic3", f.getFoo().toUpperCase()));
LOGGER.info("Messages sent, hit Enter to commit tx");
System.in.read();
}
@KafkaListener(id = "fooGroup3", topics = "topic3")
public void listen2(List<String> in) {
LOGGER.info("Received: " + in);
Application.LATCH.countDown();
}
} | repos\spring-kafka-main\samples\sample-03\src\main\java\com\example\Application.java | 1 |
请完成以下Java代码 | public class AnnotationGrpcCodecDiscoverer implements ApplicationContextAware, GrpcCodecDiscoverer {
private ApplicationContext applicationContext;
private Collection<GrpcCodecDefinition> definitions;
@Override
public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public Collection<GrpcCodecDefinition> findGrpcCodecs() {
if (this.definitions == null) {
log.debug("Searching for codecs...");
final String[] beanNames = this.applicationContext.getBeanNamesForAnnotation(GrpcCodec.class); | final ImmutableList.Builder<GrpcCodecDefinition> builder = ImmutableList.builder();
for (final String beanName : beanNames) {
final Codec codec = this.applicationContext.getBean(beanName, Codec.class);
final GrpcCodec annotation = this.applicationContext.findAnnotationOnBean(beanName, GrpcCodec.class);
builder.add(new GrpcCodecDefinition(codec, annotation.advertised(), annotation.codecType()));
log.debug("Found gRPC codec: {}, bean: {}, class: {}",
codec.getMessageEncoding(), beanName, codec.getClass().getName());
}
this.definitions = builder.build();
log.debug("Done");
}
return this.definitions;
}
} | repos\grpc-spring-master\grpc-common-spring-boot\src\main\java\net\devh\boot\grpc\common\codec\AnnotationGrpcCodecDiscoverer.java | 1 |
请完成以下Java代码 | public UserQuery memberOfGroups(List<String> groupIds) {
if (groupIds == null) {
throw new FlowableIllegalArgumentException("Provided groupIds is null");
}
this.groupIds = groupIds;
return this;
}
@Override
public UserQuery tenantId(String tenantId) {
if (tenantId == null) {
throw new FlowableIllegalArgumentException("TenantId is null");
}
this.tenantId = tenantId;
return this;
}
// sorting //////////////////////////////////////////////////////////
@Override
public UserQuery orderByUserId() {
return orderBy(UserQueryProperty.USER_ID);
}
@Override
public UserQuery orderByUserEmail() {
return orderBy(UserQueryProperty.EMAIL);
}
@Override
public UserQuery orderByUserFirstName() {
return orderBy(UserQueryProperty.FIRST_NAME);
}
@Override
public UserQuery orderByUserLastName() {
return orderBy(UserQueryProperty.LAST_NAME);
}
// results //////////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getUserEntityManager(commandContext).findUserCountByQueryCriteria(this);
}
@Override
public List<User> executeList(CommandContext commandContext) {
return CommandContextUtil.getUserEntityManager(commandContext).findUserByQueryCriteria(this);
}
// getters //////////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
public List<String> getIds() {
return ids;
}
public String getIdIgnoreCase() {
return idIgnoreCase;
}
public String getFirstName() {
return firstName;
}
public String getFirstNameLike() {
return firstNameLike;
}
public String getFirstNameLikeIgnoreCase() {
return firstNameLikeIgnoreCase;
}
public String getLastName() {
return lastName;
}
public String getLastNameLike() {
return lastNameLike;
}
public String getLastNameLikeIgnoreCase() {
return lastNameLikeIgnoreCase;
} | public String getEmail() {
return email;
}
public String getEmailLike() {
return emailLike;
}
public String getGroupId() {
return groupId;
}
public List<String> getGroupIds() {
return groupIds;
}
public String getFullNameLike() {
return fullNameLike;
}
public String getFullNameLikeIgnoreCase() {
return fullNameLikeIgnoreCase;
}
public String getDisplayName() {
return displayName;
}
public String getDisplayNameLike() {
return displayNameLike;
}
public String getDisplayNameLikeIgnoreCase() {
return displayNameLikeIgnoreCase;
}
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\UserQueryImpl.java | 1 |
请完成以下Java代码 | public HistoricDetailQuery orderByVariableRevision() {
orderBy(HistoricDetailQueryProperty.VARIABLE_REVISION);
return this;
}
public HistoricDetailQuery orderByVariableType() {
orderBy(HistoricDetailQueryProperty.VARIABLE_TYPE);
return this;
}
public HistoricDetailQuery orderPartiallyByOccurrence() {
orderBy(HistoricDetailQueryProperty.SEQUENCE_COUNTER);
return this;
}
public HistoricDetailQuery orderByTenantId() {
return orderBy(HistoricDetailQueryProperty.TENANT_ID);
}
// getters and setters //////////////////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getTaskId() { | return taskId;
}
public String getActivityId() {
return activityId;
}
public String getType() {
return type;
}
public boolean getExcludeTaskRelated() {
return excludeTaskRelated;
}
public String getDetailId() {
return detailId;
}
public String[] getProcessInstanceIds() {
return processInstanceIds;
}
public Date getOccurredBefore() {
return occurredBefore;
}
public Date getOccurredAfter() {
return occurredAfter;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isInitial() {
return initial;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDetailQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DistributionNetworkId implements RepoIdAware
{
int repoId;
@JsonCreator
public static DistributionNetworkId ofRepoId(final int repoId)
{
return new DistributionNetworkId(repoId);
}
public static DistributionNetworkId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new DistributionNetworkId(repoId) : null;
}
public static int toRepoId(final DistributionNetworkId id)
{
return id != null ? id.getRepoId() : -1;
} | public static boolean equals(final DistributionNetworkId o1, final DistributionNetworkId o2)
{
return Objects.equals(o1, o2);
}
private DistributionNetworkId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "DD_NetworkDistribution_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\material\planning\ddorder\DistributionNetworkId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DataSource userDataSource() {
// 获得 DataSourceProperties 对象
DataSourceProperties properties = this.userDataSourceProperties();
// 创建 HikariDataSource 对象
return createHikariDataSource(properties);
}
/**
* 创建 quartz 数据源的配置对象
*/
@Bean(name = "quartzDataSourceProperties")
@ConfigurationProperties(prefix = "spring.datasource.quartz") // 读取 spring.datasource.quartz 配置到 DataSourceProperties 对象
public DataSourceProperties quartzDataSourceProperties() {
return new DataSourceProperties();
}
/**
* 创建 quartz 数据源
*/
@Bean(name = "quartzDataSource")
@ConfigurationProperties(prefix = "spring.datasource.quartz.hikari") | @QuartzDataSource
public DataSource quartzDataSource() {
// 获得 DataSourceProperties 对象
DataSourceProperties properties = this.quartzDataSourceProperties();
// 创建 HikariDataSource 对象
return createHikariDataSource(properties);
}
private static HikariDataSource createHikariDataSource(DataSourceProperties properties) {
// 创建 HikariDataSource 对象
HikariDataSource dataSource = properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
// 设置线程池名
if (StringUtils.hasText(properties.getName())) {
dataSource.setPoolName(properties.getName());
}
return dataSource;
}
} | repos\SpringBoot-Labs-master\lab-28\lab-28-task-quartz-jdbc\src\main\java\cn\iocoder\springboot\lab28\task\config\DataSourceConfiguration.java | 2 |
请完成以下Java代码 | public Set<CtxName> getParameters()
{
return stringExpression.getParameters();
}
@Override
public V evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
final String sql = stringExpression.evaluate(ctx, onVariableNotFound);
if (Check.isEmpty(sql, true))
{
logger.warn("Expression " + stringExpression + " was evaluated to empty string. Returning no result: {}", noResultValue);
return noResultValue;
}
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
rs = pstmt.executeQuery();
if (rs.next())
{
final V value = valueRetriever.get(rs);
return value;
}
else
{
if (onVariableNotFound == OnVariableNotFound.Fail)
{
throw ExpressionEvaluationException.newWithPlainMessage("Got no result for " + this)
.setParameter("SQL", sql) | .appendParametersToMessage();
}
logger.warn("Got no result for {} (SQL: {})", this, sql);
return noResultValue;
}
}
catch (final SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDefaultValueExpression.java | 1 |
请完成以下Java代码 | public Integer getBusinessSystemId() {
return businessSystemId;
}
public void setBusinessSystemId(Integer businessSystemId) {
this.businessSystemId = businessSystemId;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getOccurCount() {
return occurCount;
}
public void setOccurCount(Integer occurCount) {
this.occurCount = occurCount;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Date getResponsedTime() {
return responsedTime;
}
public void setResponsedTime(Date responsedTime) {
this.responsedTime = responsedTime;
}
public String getResponsedBy() {
return responsedBy;
}
public void setResponsedBy(String responsedBy) {
this.responsedBy = responsedBy;
}
public Date getResolvedTime() {
return resolvedTime;
}
public void setResolvedTime(Date resolvedTime) {
this.resolvedTime = resolvedTime;
}
public String getResolvedBy() {
return resolvedBy;
} | public void setResolvedBy(String resolvedBy) {
this.resolvedBy = resolvedBy;
}
public Date getClosedTime() {
return closedTime;
}
public void setClosedTime(Date closedTime) {
this.closedTime = closedTime;
}
public String getClosedBy() {
return closedBy;
}
public void setClosedBy(String closedBy) {
this.closedBy = closedBy;
}
@Override
public String toString() {
return "Event{" +
"id=" + id +
", rawEventId=" + rawEventId +
", host=" + host +
", ip=" + ip +
", source=" + source +
", type=" + type +
", startTime=" + startTime +
", endTime=" + endTime +
", content=" + content +
", dataType=" + dataType +
", suggest=" + suggest +
", businessSystemId=" + businessSystemId +
", departmentId=" + departmentId +
", status=" + status +
", occurCount=" + occurCount +
", owner=" + owner +
", responsedTime=" + responsedTime +
", responsedBy=" + responsedBy +
", resolvedTime=" + resolvedTime +
", resolvedBy=" + resolvedBy +
", closedTime=" + closedTime +
", closedBy=" + closedBy +
'}';
}
} | repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\Event.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyInStockingUOM()
{
final I_C_UOM uomTo = Services.get(IProductBL.class).getStockUOM(product);
return getQty(uomTo);
}
protected void addQty(final int qtyToAdd)
{
qty = qty.add(BigDecimal.valueOf(qtyToAdd));
}
protected void subtractQty(final int qtyToSubtract)
{
qty = qty.subtract(BigDecimal.valueOf(qtyToSubtract));
}
/**
*
* @return packing materials amount(qty)'s unit of measure
*/
public I_C_UOM getC_UOM()
{
return uom;
}
private int getC_UOM_ID()
{
final int uomId = uom == null ? -1 : uom.getC_UOM_ID();
return uomId > 0 ? uomId : -1;
}
public I_M_Locator getM_Locator()
{
return locator;
}
private int getM_Locator_ID()
{
final int locatorId = locator == null ? -1 : locator.getM_Locator_ID();
return locatorId > 0 ? locatorId : -1;
}
public I_M_Material_Tracking getM_MaterialTracking()
{
return materialTracking;
}
private int getM_MaterialTracking_ID()
{
final int materialTrackingId = materialTracking == null ? -1 : materialTracking.getM_Material_Tracking_ID();
return materialTrackingId > 0 ? materialTrackingId : -1; | }
protected void add(@NonNull final HUPackingMaterialDocumentLineCandidate candidateToAdd)
{
if (this == candidateToAdd)
{
throw new IllegalArgumentException("Cannot add to it self: " + candidateToAdd);
}
if (!Objects.equals(getProductId(), candidateToAdd.getProductId())
|| getC_UOM_ID() != candidateToAdd.getC_UOM_ID()
|| getM_Locator_ID() != candidateToAdd.getM_Locator_ID()
|| getM_MaterialTracking_ID() != candidateToAdd.getM_MaterialTracking_ID())
{
throw new HUException("Candidates are not matching."
+ "\nthis: " + this
+ "\ncandidate to add: " + candidateToAdd);
}
qty = qty.add(candidateToAdd.qty);
// add sources; might be different
addSources(candidateToAdd.getSources());
}
public void addSourceIfNotNull(final IHUPackingMaterialCollectorSource huPackingMaterialCollectorSource)
{
if (huPackingMaterialCollectorSource != null)
{
sources.add(huPackingMaterialCollectorSource);
}
}
private void addSources(final Set<IHUPackingMaterialCollectorSource> huPackingMaterialCollectorSources)
{
if (!huPackingMaterialCollectorSources.isEmpty())
{
sources.addAll(huPackingMaterialCollectorSources);
}
}
public Set<IHUPackingMaterialCollectorSource> getSources()
{
return ImmutableSet.copyOf(sources);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\spi\impl\HUPackingMaterialDocumentLineCandidate.java | 1 |
请完成以下Java代码 | public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
// @formatter:off
return oauth2Token().map((token) -> bearer(request, token))
.defaultIfEmpty(request)
.flatMap(next::exchange);
// @formatter:on
}
private Mono<OAuth2Token> oauth2Token() {
// @formatter:off
return currentAuthentication()
.filter((authentication) -> authentication.getCredentials() instanceof OAuth2Token)
.map(Authentication::getCredentials)
.cast(OAuth2Token.class);
// @formatter:on
} | private Mono<Authentication> currentAuthentication() {
// @formatter:off
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication);
// @formatter:on
}
private ClientRequest bearer(ClientRequest request, OAuth2Token token) {
// @formatter:off
return ClientRequest.from(request)
.headers((headers) -> headers.setBearerAuth(token.getTokenValue()))
.build();
// @formatter:on
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\web\reactive\function\client\ServerBearerExchangeFilterFunction.java | 1 |
请完成以下Java代码 | private String toJsonString(@NonNull final Object obj)
{
try
{
return jsonObjectMapper.writeValueAsString(obj);
}
catch (final JsonProcessingException ex)
{
logger.warn("Failed converting {} to JSON. Returning toString()", obj, ex);
return obj.toString();
}
}
@Nullable
private static PPCostCollectorId extractCostCollectorId(@NonNull final JsonResponseIssueToManufacturingOrderDetail issueDetail) | {
return toPPCostCollectorId(issueDetail.getCostCollectorId());
}
@Nullable
private static PPCostCollectorId toPPCostCollectorId(@Nullable final JsonMetasfreshId id)
{
return id != null ? PPCostCollectorId.ofRepoIdOrNull(id.getValue()) : null;
}
@Nullable
private static JsonMetasfreshId toJsonMetasfreshId(@Nullable final PPCostCollectorId costCollectorId)
{
return costCollectorId != null ? JsonMetasfreshId.of(costCollectorId.getRepoId()) : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v1\ManufacturingOrderReportProcessCommand.java | 1 |
请完成以下Java代码 | public static void createRevisioned(final Database<XmlResourceManager> database) {
try (final XmlResourceManager resMgr = database.openResourceManager("resource")) {
try (final XmlNodeTrx firstWtx = resMgr.beginNodeTrx()) {
final XmlShredder shredder = new XmlShredder.Builder(firstWtx, XmlShredder.createStringReader(REVXML),
InsertPosition.AS_FIRST_CHILD).commitAfterwards().build();
shredder.call();
}
try (final XmlNodeTrx secondWtx = resMgr.beginNodeTrx()) {
secondWtx.moveToFirstChild();
secondWtx.moveToFirstChild();
secondWtx.moveToFirstChild();
secondWtx.setValue("A Contrived Test Document");
secondWtx.moveToParent();
secondWtx.moveToRightSibling();
secondWtx.moveToRightSibling();
secondWtx.moveToFirstChild();
secondWtx.moveToRightSibling();
final long key = secondWtx.getNodeKey();
secondWtx.insertAttribute(new QNm("role"), "bold");
secondWtx.moveTo(key);
secondWtx.moveToRightSibling();
secondWtx.setValue("changed in it.");
secondWtx.moveToParent();
secondWtx.insertElementAsRightSibling(new QNm("para"));
secondWtx.insertTextAsFirstChild("This is a new para 2b."); | secondWtx.moveToParent();
secondWtx.moveToRightSibling();
secondWtx.moveToRightSibling();
secondWtx.moveToFirstChild();
secondWtx.setValue("This is a different para 4.");
secondWtx.moveToParent();
secondWtx.insertElementAsRightSibling(new QNm("para"));
secondWtx.insertTextAsFirstChild("This is a new para 4b.");
secondWtx.moveToParent();
secondWtx.moveToRightSibling();
secondWtx.moveToRightSibling();
secondWtx.remove();
secondWtx.remove();
secondWtx.commit();
secondWtx.moveToDocumentRoot();
secondWtx.moveToFirstChild();
secondWtx.moveToFirstChild();
secondWtx.remove();
secondWtx.commit();
}
}
}
} | repos\tutorials-master\persistence-modules\sirix\src\main\java\io\sirix\tutorial\xml\XmlDocumentCreator.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.