instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private static final class NullExpression extends NullExpressionTemplate<Date, DateStringExpression> implements DateStringExpression { public NullExpression(final Compiler<Date, DateStringExpression> compiler) { super(compiler); } } private static final class ConstantExpression extends ConstantExpressionTemplate<Date, DateStringExpression> implements DateStringExpression { public ConstantExpression(final ExpressionContext context, final Compiler<Date, DateStringExpression> compiler, final String expressionStr, final Date constantValue) { super(context, compiler, expressionStr, constantValue); } } private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<Date, DateStringExpression> implements DateStringExpression { public SingleParameterExpression(final ExpressionContext context, final Compiler<Date, DateStringExpression> compiler, final String expressionStr, final CtxName parameter)
{ super(context, compiler, expressionStr, parameter); } @Override protected Object extractParameterValue(final Evaluatee ctx) { return parameter.getValueAsDate(ctx); } } private static final class GeneralExpression extends GeneralExpressionTemplate<Date, DateStringExpression> implements DateStringExpression { public GeneralExpression(final ExpressionContext context, final Compiler<Date, DateStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks) { super(context, compiler, expressionStr, expressionChunks); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\DateStringExpressionSupport.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 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); }
/** Set Parameter Value. @param ParameterValue Parameter Value */ public void setParameterValue (String ParameterValue) { set_Value (COLUMNNAME_ParameterValue, ParameterValue); } /** Get Parameter Value. @return Parameter Value */ public String getParameterValue () { return (String)get_Value(COLUMNNAME_ParameterValue); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_ProcessorParameter.java
1
请在Spring Boot框架中完成以下Java代码
public void onMessage(String message, Session session) { try{ //jackson ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //JSON字符串转 HashMap HashMap hashMap = mapper.readValue(message, HashMap.class); //消息类型 String type = (String) hashMap.get("type"); //to user String toUser = (String) hashMap.get("toUser"); Session toUserSession = sessionMap.get(toUser); String fromUser = (String) hashMap.get("fromUser"); //msg String msg = (String) hashMap.get("msg"); //sdp String sdp = (String) hashMap.get("sdp"); //ice Map iceCandidate = (Map) hashMap.get("iceCandidate"); HashMap<String, Object> map = new HashMap<>(); map.put("type",type); //呼叫的用户不在线 if(toUserSession == null){ toUserSession = session; map.put("type","call_back"); map.put("fromUser","系统消息"); map.put("msg","Sorry,呼叫的用户不在线!"); send(toUserSession,mapper.writeValueAsString(map)); return; } //对方挂断 if ("hangup".equals(type)) { map.put("fromUser",fromUser); map.put("msg","对方挂断!"); } //视频通话请求 if ("call_start".equals(type)) { map.put("fromUser",fromUser); map.put("msg","1"); }
//视频通话请求回应 if ("call_back".equals(type)) { map.put("fromUser",toUser); map.put("msg",msg); } //offer if ("offer".equals(type)) { map.put("fromUser",toUser); map.put("sdp",sdp); } //answer if ("answer".equals(type)) { map.put("fromUser",toUser); map.put("sdp",sdp); } //ice if ("_ice".equals(type)) { map.put("fromUser",toUser); map.put("iceCandidate",iceCandidate); } send(toUserSession,mapper.writeValueAsString(map)); }catch(Exception e){ e.printStackTrace(); } } /** * 封装一个send方法,发送消息到前端 */ private void send(Session session, String message) { try { System.out.println(message); session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } }
repos\springboot-demo-master\WebRTC\src\main\java\com\et\webrtc\config\WebRtcWSServer.java
2
请完成以下Java代码
public class ImmutableRelyingPartyRegistrationRequest implements RelyingPartyRegistrationRequest { private final PublicKeyCredentialCreationOptions options; private final RelyingPartyPublicKey publicKey; /** * Creates a new instance. * @param options the {@link PublicKeyCredentialCreationOptions} that were saved when * {@link WebAuthnRelyingPartyOperations#createCredentialRequestOptions(PublicKeyCredentialRequestOptionsRequest)} * was called. * @param publicKey this is submitted by the client and if validated stored. */ public ImmutableRelyingPartyRegistrationRequest(PublicKeyCredentialCreationOptions options, @Nullable RelyingPartyPublicKey publicKey) { Assert.notNull(options, "options cannot be null"); Assert.notNull(publicKey, "publicKey cannot be null");
this.options = options; this.publicKey = publicKey; } @Override public PublicKeyCredentialCreationOptions getCreationOptions() { return this.options; } @Override public RelyingPartyPublicKey getPublicKey() { return this.publicKey; } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\management\ImmutableRelyingPartyRegistrationRequest.java
1
请在Spring Boot框架中完成以下Java代码
public class SyncConfirm extends AbstractEntity { private String entryType; @Column(nullable=true) private long entryId; /** * See {@link #getEntryUuid()} */ private String entryUuid; private String serverEventId; /** * See {@link #getDateConfirmed()}. */ @Temporal(TemporalType.TIMESTAMP) private Date dateConfirmed; /** * See {@link #getDateConfirmReceived()}. */ @Temporal(TemporalType.TIMESTAMP) private Date dateConfirmReceived; @Override protected void toString(final MoreObjects.ToStringHelper toStringHelper) { toStringHelper .add("entryType", entryType) .add("entryUuid", entryUuid) .add("serverEventId", serverEventId) .add("dateCreated", getDateCreated()) .add("dateConfirmReceived", dateConfirmReceived); } public String getEntryType() { return entryType; } public void setEntryType(String entryType) { this.entryType = entryType; } /** * * @return the UUID of the entry this sync confirm record is about. */ public String getEntryUuid() { return entryUuid; } public void setEntryUuid(String entry_uuid) { this.entryUuid = entry_uuid; }
public String getServerEventId() { return serverEventId; } public void setServerEventId(String serverEventId) { this.serverEventId = serverEventId; } /** * * @return the date when this record was created, which is also the date when the sync request was submitted towards the remote endpoint. */ @Override public Date getDateCreated() { return super.getDateCreated(); } /** * * @return the date when the remote endpoint actually confirmed the data receipt. */ public Date getDateConfirmed() { return dateConfirmed; } public void setDateConfirmed(Date dateConfirmed) { this.dateConfirmed = dateConfirmed; } /** * * @return the date when our local endpoint received the remote endpoint's confirmation. */ public Date getDateConfirmReceived() { return dateConfirmReceived; } public void setDateConfirmReceived(Date dateConfirmReceived) { this.dateConfirmReceived = dateConfirmReceived; } public long getEntryId() { return entryId; } public void setEntryId(long entryId) { this.entryId = entryId; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\SyncConfirm.java
2
请完成以下Java代码
public class ASILayout { public static final Builder builder() { return new Builder(); } private final DocumentId asiDescriptorId; private final ITranslatableString caption; private final ITranslatableString description; private final List<DocumentLayoutElementDescriptor> elements; private ASILayout(final Builder builder) { super(); asiDescriptorId = builder.asiDescriptorId; caption = TranslatableStrings.nullToEmpty(builder.caption); description = TranslatableStrings.nullToEmpty(builder.description); elements = ImmutableList.copyOf(builder.buildElements()); } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("asiDescriptorId", asiDescriptorId) .add("caption", caption) .add("elements", elements.isEmpty() ? null : elements) .toString(); } public DocumentId getASIDescriptorId() { return asiDescriptorId; } public String getCaption(final String adLanguage) { return caption.translate(adLanguage); } public String getDescription(final String adLanguage) { return description.translate(adLanguage); } public List<DocumentLayoutElementDescriptor> getElements() { return elements; } public static final class Builder { public DocumentId asiDescriptorId; private ITranslatableString caption; private ITranslatableString description; private final List<DocumentLayoutElementDescriptor.Builder> elementBuilders = new ArrayList<>(); private Builder() { super(); } public ASILayout build() { return new ASILayout(this); } private List<DocumentLayoutElementDescriptor> buildElements() { return elementBuilders .stream() .map(elementBuilder -> elementBuilder.build()) .collect(GuavaCollectors.toImmutableList()); }
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("asiDescriptorId", asiDescriptorId) .add("caption", caption) .add("elements-count", elementBuilders.size()) .toString(); } public Builder setASIDescriptorId(final DocumentId asiDescriptorId) { this.asiDescriptorId = asiDescriptorId; return this; } public Builder setCaption(final ITranslatableString caption) { this.caption = caption; return this; } public Builder setDescription(final ITranslatableString description) { this.description = description; return this; } public Builder addElement(final DocumentLayoutElementDescriptor.Builder elementBuilder) { Check.assumeNotNull(elementBuilder, "Parameter elementBuilder is not null"); elementBuilders.add(elementBuilder); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASILayout.java
1
请完成以下Java代码
private boolean processWorkPackage(@NonNull final I_C_Queue_WorkPackage workPackage) { boolean success = false; try { final IWorkpackageProcessor workPackageProcessor = getWorkpackageProcessor(workPackage); final PerformanceMonitoringService perfMonService = getPerfMonService(); final WorkpackageProcessorTask task = new WorkpackageProcessorTask(this, workPackageProcessor, workPackage, logsRepository, perfMonService); executeTask(task); success = true; return true; } finally { if (!success) { logger.info("Submitting for processing next workPackage failed. workPackage={}.", workPackage); getEventDispatcher().unregisterListeners(workPackage.getC_Queue_WorkPackage_ID()); } } } private IWorkpackageProcessor getWorkpackageProcessor(final I_C_Queue_WorkPackage workPackage) { final IWorkpackageProcessorFactory factory = getActualWorkpackageProcessorFactory(); final Properties ctx = InterfaceWrapperHelper.getCtx(workPackage); final int packageProcessorId = workPackage.getC_Queue_PackageProcessor_ID(); return factory.getWorkpackageProcessor(ctx, packageProcessorId); } private PerformanceMonitoringService getPerfMonService() {
PerformanceMonitoringService performanceMonitoringService = _performanceMonitoringService; if (performanceMonitoringService == null || performanceMonitoringService instanceof NoopPerformanceMonitoringService) { performanceMonitoringService = _performanceMonitoringService = SpringContextHolder.instance.getBeanOr( PerformanceMonitoringService.class, NoopPerformanceMonitoringService.INSTANCE); } return performanceMonitoringService; } private IQueueProcessorEventDispatcher getEventDispatcher() { return queueProcessorFactory.getQueueProcessorEventDispatcher(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\AbstractQueueProcessor.java
1
请完成以下Java代码
public State nextStateIgnoreRootState(Character character) { return nextState(character, true); } public State addState(Character character) { State nextState = nextStateIgnoreRootState(character); if (nextState == null) { nextState = new State(this.depth + 1); this.success.put(character, nextState); } return nextState; } public Collection<State> getStates() { return this.success.values();
} public Collection<Character> getTransitions() { return this.success.keySet(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("State{"); sb.append("depth=").append(depth); sb.append(", emits=").append(emits); sb.append(", success=").append(success.keySet()); sb.append(", failure=").append(failure); sb.append('}'); return sb.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\trie\State.java
1
请完成以下Java代码
public void callingRuntimeHalt() { try { System.out.println("Inside try"); Runtime.getRuntime() .halt(1); } finally { System.out.println("Inside finally"); } } public void infiniteLoop() { try { System.out.println("Inside try"); while (true) { } } finally { System.out.println("Inside finally"); } }
public void daemonThread() throws InterruptedException { Runnable runnable = () -> { try { System.out.println("Inside try"); } finally { try { Thread.sleep(1000); System.out.println("Inside finally"); } catch (InterruptedException e) { e.printStackTrace(); } } }; Thread regular = new Thread(runnable); Thread daemon = new Thread(runnable); daemon.setDaemon(true); regular.start(); Thread.sleep(300); daemon.start(); } }
repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\finallykeyword\FinallyNotExecutedCases.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } OrderLine other = (OrderLine) obj; if (product == null) { if (other.product != null) { return false; } } else if (!product.equals(other.product)) { return false; } if (quantity != other.quantity) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((product == null) ? 0 : product.hashCode());
result = prime * result + quantity; return result; } @Override public String toString() { return "OrderLine [product=" + product + ", quantity=" + quantity + "]"; } Money cost() { return product.getPrice() .multipliedBy(quantity); } Product getProduct() { return product; } int getQuantity() { return quantity; } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\OrderLine.java
1
请完成以下Java代码
public int getExportUser_ID() { return get_ValueAsInt(COLUMNNAME_ExportUser_ID); } @Override public void setExternalSystem_ExportAudit_ID (final int ExternalSystem_ExportAudit_ID) { if (ExternalSystem_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_ExportAudit_ID, ExternalSystem_ExportAudit_ID); } @Override public int getExternalSystem_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ExportAudit_ID); } @Override public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class); } @Override public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem) { set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID()
{ return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_ExportAudit.java
1
请完成以下Java代码
public void setC_BPartner_Contact_QuickInput_Attributes_ID (final int C_BPartner_Contact_QuickInput_Attributes_ID) { if (C_BPartner_Contact_QuickInput_Attributes_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_Attributes_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_Attributes_ID, C_BPartner_Contact_QuickInput_Attributes_ID); } @Override public int getC_BPartner_Contact_QuickInput_Attributes_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Contact_QuickInput_Attributes_ID); } @Override public org.compiere.model.I_C_BPartner_Contact_QuickInput getC_BPartner_Contact_QuickInput() { return get_ValueAsPO(COLUMNNAME_C_BPartner_Contact_QuickInput_ID, org.compiere.model.I_C_BPartner_Contact_QuickInput.class); } @Override public void setC_BPartner_Contact_QuickInput(final org.compiere.model.I_C_BPartner_Contact_QuickInput C_BPartner_Contact_QuickInput) { set_ValueFromPO(COLUMNNAME_C_BPartner_Contact_QuickInput_ID, org.compiere.model.I_C_BPartner_Contact_QuickInput.class, C_BPartner_Contact_QuickInput); }
@Override public void setC_BPartner_Contact_QuickInput_ID (final int C_BPartner_Contact_QuickInput_ID) { if (C_BPartner_Contact_QuickInput_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_Contact_QuickInput_ID, C_BPartner_Contact_QuickInput_ID); } @Override public int getC_BPartner_Contact_QuickInput_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Contact_QuickInput_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput_Attributes.java
1
请完成以下Java代码
public class DifferentPairs { /** * Show all different pairs using traditional "for" loop * * @param input - number's array * @param sum - given sum * @return - number's array with all existing pairs. This list will contain just one pair's element because * the other one can be calculated with SUM - element_1 = element_2 */ public static List<Integer> findPairsWithForLoop(int[] input, int sum) { final List<Integer> allDifferentPairs = new ArrayList<>(); // Aux. hash map final Map<Integer, Integer> pairs = new HashMap<>(); for (int i : input) { if (pairs.containsKey(i)) { if (pairs.get(i) != null) { // Add pair to returned list allDifferentPairs.add(i); } // Mark pair as added to prevent duplicates pairs.put(sum - i, null); } else if (!pairs.containsValue(i)) { // Add pair to aux. hash map pairs.put(sum - i, i); } } return allDifferentPairs; } /** * Show all different pairs using Java 8 stream API * * @param input - number's array * @param sum - given sum * @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2 */ public static List<Integer> findPairsWithStreamApi(int[] input, int sum) { final List<Integer> allDifferentPairs = new ArrayList<>(); // Aux. hash map final Map<Integer, Integer> pairs = new HashMap<>(); IntStream.range(0, input.length).forEach(i -> { if (pairs.containsKey(input[i])) { if (pairs.get(input[i]) != null) { // Add pair to returned list allDifferentPairs.add(input[i]); } // Mark pair as added to prevent duplicates pairs.put(sum - input[i], null); } else if (!pairs.containsValue(input[i])) { // Add pair to aux. hash map pairs.put(sum - input[i], input[i]); } } ); return allDifferentPairs; } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\pairsaddupnumber\DifferentPairs.java
1
请完成以下Java代码
public <P> Object set(List<Object> location, String target, P value) { return location.set(Integer.parseInt(target), value); } @Override public Object recurse(List<Object> location, String target) { return location.get(Integer.parseInt(target)); } }; @SuppressWarnings({"unchecked", "rawtypes"}) public static <P> void mapVariable(String objectPath, Map<String, Object> variables, P file) { String[] segments = PERIOD.split(objectPath); if (segments.length < 2) { throw new RuntimeException("object-path in map must have at least two segments"); } else if (!"variables".equals(segments[0])) { throw new RuntimeException("can only map into variables"); } Object currentLocation = variables; for (int i = 1; i < segments.length; i++) { String segmentName = segments[i]; MultipartVariableMapper.Mapper mapper = determineMapper(currentLocation, objectPath, segmentName); if (i == segments.length - 1) { if (null != mapper.set(currentLocation, segmentName, file)) { throw new RuntimeException("expected null value when mapping " + objectPath);
} } else { currentLocation = mapper.recurse(currentLocation, segmentName); if (null == currentLocation) { throw new RuntimeException("found null intermediate value when trying to map " + objectPath); } } } } private static MultipartVariableMapper.Mapper<?> determineMapper(Object currentLocation, String objectPath, String segmentName) { if (currentLocation instanceof Map) { return MAP_MAPPER; } else if (currentLocation instanceof List) { return LIST_MAPPER; } throw new RuntimeException("expected a map or list at " + segmentName + " when trying to map " + objectPath); } interface Mapper<T> { <P> Object set(T location, String target, P value); Object recurse(T location, String target); } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphql\fileupload\MultipartVariableMapper.java
1
请完成以下Java代码
public class CamundaEntryImpl extends CamundaGenericValueElementImpl implements CamundaEntry { protected static Attribute<String> camundaKeyAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaEntry.class, CAMUNDA_ELEMENT_ENTRY) .namespaceUri(CAMUNDA_NS) .instanceProvider(new ModelTypeInstanceProvider<CamundaEntry>() { public CamundaEntry newInstance(ModelTypeInstanceContext instanceContext) { return new CamundaEntryImpl(instanceContext); } }); camundaKeyAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_KEY) .namespace(CAMUNDA_NS) .required() .build();
typeBuilder.build(); } public CamundaEntryImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getCamundaKey() { return camundaKeyAttribute.getValue(this); } public void setCamundaKey(String camundaKey) { camundaKeyAttribute.setValue(this, camundaKey); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaEntryImpl.java
1
请完成以下Java代码
protected String doIt() throws Exception { final I_M_Product product = productDAO.getById(getRecord_ID()); final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryFilter<I_M_Product> productFilter = queryBL.createCompositeQueryFilter(I_M_Product.class) .addOnlyActiveRecordsFilter() .addCompareFilter( I_M_Product.COLUMNNAME_M_Product_ID, CompareQueryFilter.Operator.EQUAL, product.getM_Product_ID()); if (product.isDiscontinued()) { final ZoneId zoneId = orgDAO.getTimeZone(OrgId.ofRepoId(product.getAD_Org_ID())); final Optional<LocalDate> discontinuedFrom = Optional.ofNullable(product.getDiscontinuedFrom()) .map(discontinuedFromTimestamp -> TimeUtil.asLocalDate(discontinuedFromTimestamp, zoneId)); if (!discontinuedFrom.isPresent())
{ throw new AdempiereException(ERROR_MISSING_DISCONTINUED_FROM) .appendParametersToMessage() .setParameter("ProductId", product.getM_Product_ID()); } priceListDAO.updateProductPricesIsActive(productFilter, discontinuedFrom.get(), false); } else { priceListDAO.updateProductPricesIsActive(productFilter, null, true); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\process\M_ProductPrice_ActivationBasedOnProductDiscontinuedFlag_Process.java
1
请在Spring Boot框架中完成以下Java代码
public class BankStatementLineId implements RepoIdAware { int repoId; private BankStatementLineId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_BankStatementLine_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } @NonNull @JsonCreator public static BankStatementLineId ofRepoId(final int repoId) { return new BankStatementLineId(repoId); } @Nullable
public static BankStatementLineId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static Optional<BankStatementLineId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));} public static boolean equals(@Nullable BankStatementLineId id1, @Nullable BankStatementLineId id2) { return Objects.equals(id1, id2); } public static int toRepoId(@Nullable BankStatementLineId id) {return id != null ? id.getRepoId() : -1;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\banking\BankStatementLineId.java
2
请完成以下Java代码
private void print(String amt) { try { System.out.println(amt + " = " + getAmtInWords(amt)); } catch (Exception e) { e.printStackTrace(); } } // print /** * Test * * @param args * ignored */ public static void main(String[] args) {
AmtInWords_PL aiw = new AmtInWords_PL(); // aiw.print (".23"); Error aiw.print("0.23"); aiw.print("1.23"); aiw.print("12.345"); aiw.print("123.45"); aiw.print("1234.56"); aiw.print("12345.78"); aiw.print("10345.78"); aiw.print("123457.89"); aiw.print("323457.89"); aiw.print("23457.89"); aiw.print("1,234,578.90"); } // main } // AmtInWords_EN
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\AmtInWords_PL.java
1
请完成以下Java代码
public IAttributeAggregationStrategy retrieveAggregationStrategy() { return NullAggregationStrategy.instance; } @Override public IAttributeSplitterStrategy retrieveSplitterStrategy() { return NullSplitterStrategy.instance; } @Override public IHUAttributeTransferStrategy retrieveTransferStrategy() { return SkipHUAttributeTransferStrategy.instance; } @Override public boolean isUseInASI() { return false; } @Override public boolean isDefinedByTemplate() { return false; } @Override public void addAttributeValueListener(final IAttributeValueListener listener) { // nothing } @Override public List<ValueNamePair> getAvailableValues() { throw new InvalidAttributeValueException("method not supported for " + this); } @Override public IAttributeValuesProvider getAttributeValuesProvider() { throw new InvalidAttributeValueException("method not supported for " + this); } @Override public I_C_UOM getC_UOM() { return null; } @Override public IAttributeValueCallout getAttributeValueCallout() { return NullAttributeValueCallout.instance; } @Override public IAttributeValueGenerator getAttributeValueGeneratorOrNull() { return null; } @Override public void removeAttributeValueListener(final IAttributeValueListener listener) {
// nothing } @Override public boolean isReadonlyUI() { return true; } @Override public boolean isDisplayedUI() { return false; } @Override public boolean isMandatory() { return false; } @Override public int getDisplaySeqNo() { return 0; } @Override public NamePair getNullAttributeValue() { return null; } /** * @return true; we consider Null attributes as always generated */ @Override public boolean isNew() { return true; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\NullAttributeValue.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getRegTime() { return regTime; }
public void setRegTime(Date regTime) { this.regTime = regTime; } @Override public String toString() { return "User{" + "id=" + id + ", userName='" + userName + '\'' + ", passWord='" + passWord + '\'' + ", age=" + age + ", regTime=" + regTime + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-8 课:Spring Data Jpa 和 Thymeleaf 综合实践\spring-boot-Jpa-thymeleaf\src\main\java\com\neo\model\User.java
1
请完成以下Java代码
protected void createMuleActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createMuleActivityBehavior(serviceTask)); } protected void createCamelActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createCamelActivityBehavior(serviceTask)); } protected void createShellActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createShellActivityBehavior(serviceTask)); } protected void createActivityBehaviorForCustomServiceTaskType(BpmnParse bpmnParse, ServiceTask serviceTask) { logger.warn( "Invalid service task type: '" + serviceTask.getType() + "' " + " for service task " + serviceTask.getId() ); } protected void createClassDelegateServiceTask(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createClassDelegateServiceTask(serviceTask)); }
protected void createServiceTaskDelegateExpressionActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior( bpmnParse.getActivityBehaviorFactory().createServiceTaskDelegateExpressionActivityBehavior(serviceTask) ); } protected void createServiceTaskExpressionActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior( bpmnParse.getActivityBehaviorFactory().createServiceTaskExpressionActivityBehavior(serviceTask) ); } protected void createWebServiceActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createWebServiceActivityBehavior(serviceTask)); } protected void createDefaultServiceTaskActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createDefaultServiceTaskBehavior(serviceTask)); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\ServiceTaskParseHandler.java
1
请在Spring Boot框架中完成以下Java代码
public String getBankAccountType() { return bankAccountType; } /** 银行卡类型 **/ public void setBankAccountType(String bankAccountType) { this.bankAccountType = bankAccountType; } /** 证件类型 **/ public String getCardType() { return cardType; } /** 证件类型 **/ public void setCardType(String cardType) { this.cardType = cardType; } /** 证件号码 **/ public String getCardNo() { return cardNo; } /** 证件号码 **/ public void setCardNo(String cardNo) { this.cardNo = cardNo; } /** 手机号码 **/ public String getMobileNo() { return mobileNo; } /** 手机号码 **/ public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; }
/** 银行名称 **/ public String getBankName() { return bankName; } /** 银行名称 **/ public void setBankName(String bankName) { this.bankName = bankName; } /** 用户编号 **/ public String getUserNo() { return userNo; } /** 用户编号 **/ public void setUserNo(String userNo) { this.userNo = userNo; } /** 是否默认 **/ public String getIsDefault() { return isDefault; } /** 是否默认 **/ public void setIsDefault(String isDefault) { this.isDefault = isDefault; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserBankAccount.java
2
请完成以下Java代码
public Date getLastSuspendedBefore() { return lastSuspendedBefore; } public Date getLastSuspendedAfter() { return lastSuspendedAfter; } public Date getCompletedBefore() { return completedBefore; } public Date getCompletedAfter() { return completedAfter; } public Date getTerminatedBefore() { return terminatedBefore; } public Date getTerminatedAfter() { return terminatedAfter; } public Date getOccurredBefore() { return occurredBefore; } public Date getOccurredAfter() { return occurredAfter; } public Date getExitBefore() { return exitBefore; } public Date getExitAfter() { return exitAfter; } public Date getEndedBefore() { return endedBefore; } public Date getEndedAfter() { return endedAfter; } public String getStartUserId() { return startUserId; } public String getAssignee() { return assignee; } public String getCompletedBy() { return completedBy; } public String getReferenceId() { return referenceId; } public String getReferenceType() { return referenceType; } public boolean isEnded() { return ended; } public boolean isNotEnded() { return notEnded; } public String getEntryCriterionId() { return entryCriterionId; } public String getExitCriterionId() { return exitCriterionId; } public String getFormKey() { return formKey; }
public String getExtraValue() { return extraValue; } public String getInvolvedUser() { return involvedUser; } public Collection<String> getInvolvedGroups() { return involvedGroups; } public boolean isOnlyStages() { return onlyStages; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isIncludeLocalVariables() { return includeLocalVariables; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public List<List<String>> getSafeCaseInstanceIds() { return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeCaseInstanceIds = safeProcessInstanceIds; } public Collection<String> getCaseInstanceIds() { return caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricPlanItemInstanceQueryImpl.java
1
请完成以下Java代码
public class TbEntityRemoteSubsInfo { @Getter private final TenantId tenantId; @Getter private final EntityId entityId; @Getter private final Map<String, TbSubscriptionsInfo> subs = new ConcurrentHashMap<>(); // By service ID public boolean updateAndCheckIsEmpty(String serviceId, TbEntitySubEvent event) { var current = subs.get(serviceId); if (current != null && current.seqNumber > event.getSeqNumber()) { log.warn("[{}][{}] Duplicate subscription event received. Current: {}, Event: {}", tenantId, entityId, current, event.getInfo()); return false; } switch (event.getType()) { case CREATED: subs.put(serviceId, event.getInfo()); break; case UPDATED: var newSubInfo = event.getInfo(); if (newSubInfo.isEmpty()) { subs.remove(serviceId); return isEmpty();
} else { subs.put(serviceId, newSubInfo); } break; case DELETED: subs.remove(serviceId); return isEmpty(); } return false; } public boolean removeAndCheckIsEmpty(String serviceId) { if (subs.remove(serviceId) != null) { return subs.isEmpty(); } else { return false; } } public boolean isEmpty() { return subs.isEmpty(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbEntityRemoteSubsInfo.java
1
请完成以下Java代码
public String toString() { return "HUTrxQuery [" + "M_HU_Trx_Hdr_ID=" + M_HU_Trx_Hdr_ID + ", Exclude_M_HU_Trx_Line_ID=" + Exclude_M_HU_Trx_Line_ID + ", Parent_M_HU_Trx_Line_ID=" + Parent_M_HU_Trx_Line_ID + ", Ref_HU_Item_ID=" + Ref_HU_Item_ID + ", AD_Table_ID/Record_ID=" + AD_Table_ID + "/" + Record_ID + "]"; } @Override public int getM_HU_Trx_Hdr_ID() { return M_HU_Trx_Hdr_ID; } @Override public void setM_HU_Trx_Hdr_ID(final int m_HU_Trx_Hdr_ID) { M_HU_Trx_Hdr_ID = m_HU_Trx_Hdr_ID; } @Override public int getExclude_M_HU_Trx_Line_ID() { return Exclude_M_HU_Trx_Line_ID; } @Override public void setExclude_M_HU_Trx_Line_ID(final int exclude_M_HU_Trx_Line_ID) { Exclude_M_HU_Trx_Line_ID = exclude_M_HU_Trx_Line_ID; } @Override public int getParent_M_HU_Trx_Line_ID() { return Parent_M_HU_Trx_Line_ID; } @Override public void setParent_M_HU_Trx_Line_ID(final int parent_M_HU_Trx_Line_ID) { Parent_M_HU_Trx_Line_ID = parent_M_HU_Trx_Line_ID; } @Override public void setM_HU_Item_ID(final int Ref_HU_Item_ID) { this.Ref_HU_Item_ID = Ref_HU_Item_ID; } @Override public int getM_HU_Item_ID() { return Ref_HU_Item_ID; } @Override
public int getAD_Table_ID() { return AD_Table_ID; } @Override public void setAD_Table_ID(final int aD_Table_ID) { AD_Table_ID = aD_Table_ID; } @Override public int getRecord_ID() { return Record_ID; } @Override public void setRecord_ID(final int record_ID) { Record_ID = record_ID; } @Override public void setM_HU_ID(int m_hu_ID) { M_HU_ID = m_hu_ID; } @Override public int getM_HU_ID() { return M_HU_ID; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxQuery.java
1
请完成以下Java代码
private final class JwkSetHolder implements Supplier<JWKSet> { private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); private final Clock clock = Clock.systemUTC(); private final String jwkSetUrl; private JWKSet jwkSet; private Instant lastUpdatedAt; private JwkSetHolder(String jwkSetUrl) { this.jwkSetUrl = jwkSetUrl; } @Override public JWKSet get() { this.rwLock.readLock().lock(); if (shouldRefresh()) { this.rwLock.readLock().unlock(); this.rwLock.writeLock().lock(); try { if (shouldRefresh()) { this.jwkSet = retrieve(this.jwkSetUrl); this.lastUpdatedAt = Instant.now(); } this.rwLock.readLock().lock();
} finally { this.rwLock.writeLock().unlock(); } } try { return this.jwkSet; } finally { this.rwLock.readLock().unlock(); } } private boolean shouldRefresh() { // Refresh every 5 minutes return (this.jwkSet == null || this.clock.instant().isAfter(this.lastUpdatedAt.plus(5, ChronoUnit.MINUTES))); } } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\X509SelfSignedCertificateVerifier.java
1
请完成以下Java代码
public class InvoicesView_MarkPreparedForAllocation extends InvoicesViewBasedProcess implements IProcessPrecondition { @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!InvoicesViewFactory.isEnablePreparedForAllocationFlag()) { return ProcessPreconditionsResolution.rejectWithInternalReason("Feature not enabled"); } if (!hasEligibleRows()) { return ProcessPreconditionsResolution.rejectWithInternalReason("No eligible rows selected"); } return ProcessPreconditionsResolution.accept(); }
@Override protected String doIt() { getView().markPreparedForAllocation(getSelectedRowIds()); return MSG_OK; } public boolean hasEligibleRows() { return getView() .streamByIds(getSelectedRowIds()) .anyMatch(invoiceRow -> !invoiceRow.isPreparedForAllocation()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\InvoicesView_MarkPreparedForAllocation.java
1
请完成以下Java代码
public IView getView(@NonNull final String viewIdStr) { final ViewId viewId = ViewId.ofViewIdString(viewIdStr); final IView view = getViewIfExists(viewId); if (view == null) { throw new EntityNotFoundException("No view found for viewId=" + viewId); } return view; } @Override public IView getViewIfExists(final ViewId viewId) { final IView view = getViewsStorageFor(viewId).getByIdOrNull(viewId); if (view == null) { throw new EntityNotFoundException("View not found: " + viewId.toJson()); } DocumentPermissionsHelper.assertViewAccess(viewId.getWindowId(), viewId.getViewId(), UserSession.getCurrentPermissions()); return view; } @Override public void closeView(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { getViewsStorageFor(viewId).closeById(viewId, closeAction); logger.trace("Closed/Removed view {} using close action {}", viewId, closeAction); } @Override public void invalidateView(final ViewId viewId) { getViewsStorageFor(viewId).invalidateView(viewId); logger.trace("Invalided view {}", viewId); } @Override public void invalidateView(final IView view) { invalidateView(view.getViewId()); } @Override public void notifyRecordsChangedAsync(@NonNull final TableRecordReferenceSet recordRefs) { if (recordRefs.isEmpty()) { logger.trace("No changed records provided. Skip notifying views."); return; } async.execute(() -> notifyRecordsChangedNow(recordRefs)); } @Override public void notifyRecordsChangedNow(@NonNull final TableRecordReferenceSet recordRefs) { if (recordRefs.isEmpty()) { logger.trace("No changed records provided. Skip notifying views."); return; } try (final IAutoCloseable ignored = ViewChangesCollector.currentOrNewThreadLocalCollector()) { for (final IViewsIndexStorage viewsIndexStorage : viewsIndexStorages.values()) { notifyRecordsChangedNow(recordRefs, viewsIndexStorage); }
notifyRecordsChangedNow(recordRefs, defaultViewsIndexStorage); } } private void notifyRecordsChangedNow( @NonNull final TableRecordReferenceSet recordRefs, @NonNull final IViewsIndexStorage viewsIndexStorage) { final ImmutableList<IView> views = viewsIndexStorage.getAllViews(); if (views.isEmpty()) { return; } final MutableInt notifiedCount = MutableInt.zero(); for (final IView view : views) { try { final boolean watchedByFrontend = isWatchedByFrontend(view.getViewId()); view.notifyRecordsChanged(recordRefs, watchedByFrontend); notifiedCount.incrementAndGet(); } catch (final Exception ex) { logger.warn("Failed calling notifyRecordsChanged on view={} with recordRefs={}. Ignored.", view, recordRefs, ex); } } logger.debug("Notified {} views in {} about changed records: {}", notifiedCount, viewsIndexStorage, recordRefs); } @lombok.Value(staticConstructor = "of") private static class ViewFactoryKey { WindowId windowId; JSONViewDataType viewType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewsRepository.java
1
请完成以下Java代码
public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer, MessageListenerContainer container, boolean batchListener) { stopContainer(container, thrownException); } @Override public void handleRemaining(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer, MessageListenerContainer container) { stopContainer(container, thrownException); } @Override public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { stopContainer(container, thrownException); } private void stopContainer(MessageListenerContainer container, Exception thrownException) {
this.executor.execute(() -> { if (this.stopContainerAbnormally) { container.stopAbnormally(() -> { }); } else { container.stop(() -> { }); } }); // isRunning is false before the container.stop() waits for listener thread try { ListenerUtils.stoppableSleep(container, 10_000); // NOSONAR } catch (InterruptedException e) { Thread.currentThread().interrupt(); } throw new KafkaException("Stopped container", getLogLevel(), thrownException); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonContainerStoppingErrorHandler.java
1
请完成以下Java代码
public static void main(String[] args) throws Exception { ApiClient client = Config.defaultClient(); // Optional, put helpful during tests: disable client timeout and enable // HTTP wire-level logs HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message)); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient newClient = client.getHttpClient() .newBuilder() .addInterceptor(interceptor) .readTimeout(0, TimeUnit.SECONDS) .build(); client.setHttpClient(newClient); CoreV1Api api = new CoreV1Api(client); String resourceVersion = null; while (true) { // Get a fresh list only we need to resync if ( resourceVersion == null ) { log.info("[I48] Creating initial POD list..."); V1PodList podList = api.listPodForAllNamespaces(true, null, null, null, null, "false", resourceVersion, null, null, null); resourceVersion = podList.getMetadata().getResourceVersion(); } while (true) { log.info("[I54] Creating watch: resourceVersion={}", resourceVersion); try (Watch<V1Pod> watch = Watch.createWatch( client, api.listPodForAllNamespacesCall(true, null, null, null, null, "false", resourceVersion, null, 10, true, null), new TypeToken<Response<V1Pod>>(){}.getType())) { log.info("[I60] Receiving events:");
for (Response<V1Pod> event : watch) { V1Pod pod = event.object; V1ObjectMeta meta = pod.getMetadata(); switch (event.type) { case "BOOKMARK": resourceVersion = meta.getResourceVersion(); log.info("[I67] event.type: {}, resourceVersion={}", event.type,resourceVersion); break; case "ADDED": case "MODIFIED": case "DELETED": log.info("event.type: {}, namespace={}, name={}", event.type, meta.getNamespace(), meta.getName()); break; default: log.warn("[W76] Unknown event type: {}", event.type); } } } catch (ApiException ex) { log.error("[E80] ApiError", ex); resourceVersion = null; } } } } }
repos\tutorials-master\kubernetes-modules\k8s-intro\src\main\java\com\baeldung\kubernetes\intro\WatchPodsUsingBookmarks.java
1
请完成以下Java代码
public abstract class RuleEngineComponentActor<T extends EntityId, P extends ComponentMsgProcessor<T>> extends ComponentActor<T, P> { public RuleEngineComponentActor(ActorSystemContext systemContext, TenantId tenantId, T id) { super(systemContext, tenantId, id); } @Override protected void logLifecycleEvent(ComponentLifecycleEvent event, Exception e) { super.logLifecycleEvent(event, e); if (e instanceof TbRuleNodeUpdateException || (event == ComponentLifecycleEvent.STARTED && e != null)) { return; } processNotificationRule(event, e); } @Override public void destroy(TbActorStopReason stopReason, Throwable cause) { super.destroy(stopReason, cause); if (stopReason == TbActorStopReason.INIT_FAILED && cause != null) { processNotificationRule(ComponentLifecycleEvent.STARTED, cause); } } private void processNotificationRule(ComponentLifecycleEvent event, Throwable e) { if (processor == null) { return; } systemContext.getNotificationRuleProcessor().process(RuleEngineComponentLifecycleEventTrigger.builder()
.tenantId(tenantId) .ruleChainId(getRuleChainId()) .ruleChainName(getRuleChainName()) .componentId(id) .componentName(processor.getComponentName()) .eventType(event) .error(e) .build()); } protected abstract RuleChainId getRuleChainId(); protected abstract String getRuleChainName(); }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\RuleEngineComponentActor.java
1
请完成以下Java代码
public String toString() { return "NullAttributeStorage []"; } @Override public BigDecimal getStorageQtyOrZERO() { // no storage quantity available; assume ZERO return BigDecimal.ZERO; } /** * @return <code>false</code>. */ @Override public boolean isVirtual() { return false; } @Override public boolean isNew(final I_M_Attribute attribute)
{ throw new AttributeNotFoundException(attribute, this); } /** * @return true, i.e. never disposed */ @Override public boolean assertNotDisposed() { return true; // not disposed } @Override public boolean assertNotDisposedTree() { return true; // not disposed } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\NullAttributeStorage.java
1
请完成以下Java代码
public void setA_Disposed_Reason (String A_Disposed_Reason) { set_Value (COLUMNNAME_A_Disposed_Reason, A_Disposed_Reason); } /** Get Disposed Reason Code. @return Disposed Reason Code */ public String getA_Disposed_Reason () { return (String)get_Value(COLUMNNAME_A_Disposed_Reason); } /** Set A_Proceeds. @param A_Proceeds A_Proceeds */ public void setA_Proceeds (BigDecimal A_Proceeds) { set_Value (COLUMNNAME_A_Proceeds, A_Proceeds); } /** Get A_Proceeds. @return A_Proceeds */ public BigDecimal getA_Proceeds () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Proceeds); if (bd == null) return Env.ZERO; return bd; } public I_C_Period getC_Period() throws RuntimeException { return (I_C_Period)MTable.get(getCtx(), I_C_Period.Table_Name) .getPO(getC_Period_ID(), get_TrxName()); } /** Set Period. @param C_Period_ID Period of the Calendar */ public void setC_Period_ID (int C_Period_ID) { if (C_Period_ID < 1) set_Value (COLUMNNAME_C_Period_ID, null); else set_Value (COLUMNNAME_C_Period_ID, Integer.valueOf(C_Period_ID)); } /** Get Period. @return Period of the Calendar */ public int getC_Period_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Period_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Account Date. @param DateAcct Accounting Date */ public void setDateAcct (Timestamp DateAcct) { set_Value (COLUMNNAME_DateAcct, DateAcct); } /** Get Account Date.
@return Accounting Date */ public Timestamp getDateAcct () { return (Timestamp)get_Value(COLUMNNAME_DateAcct); } /** Set Document Date. @param DateDoc Date of the Document */ public void setDateDoc (Timestamp DateDoc) { set_Value (COLUMNNAME_DateDoc, DateDoc); } /** Get Document Date. @return Date of the Document */ public Timestamp getDateDoc () { return (Timestamp)get_Value(COLUMNNAME_DateDoc); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Disposed.java
1
请完成以下Java代码
public void setEnableUpdatePassword(boolean enableUpdatePassword) { this.enableUpdatePassword = enableUpdatePassword; } private void validateUserDetails(UserDetails user) { Assert.hasText(user.getUsername(), "Username may not be empty or null"); validateAuthorities(user.getAuthorities()); } private void validateAuthorities(Collection<? extends GrantedAuthority> authorities) { Assert.notNull(authorities, "Authorities list must not be null"); for (GrantedAuthority authority : authorities) { Assert.notNull(authority, "Authorities list contains a null entry"); Assert.hasText(authority.getAuthority(), "getAuthority() method must return a non-empty string"); } } /**
* Conditionally updates password based on the setting from * {@link #setEnableUpdatePassword(boolean)}. {@inheritDoc} * @since 7.0 */ @Override public UserDetails updatePassword(UserDetails user, @Nullable String newPassword) { if (this.enableUpdatePassword) { // @formatter:off UserDetails updated = User.withUserDetails(user) .password(newPassword) .build(); // @formatter:on updateUser(updated); return updated; } return user; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\provisioning\JdbcUserDetailsManager.java
1
请完成以下Java代码
private static final String normalizeFilename(final String filename) { return filename.replaceAll("[^a-zA-Z0-9.-/\\\\]", "_"); } public String getLogDir() { return logDir; } public void setLogFilePrefix(final String logFilePrefix) { final String logFilePrefixNorm = normalizeLogDirPrefix(logFilePrefix); if (Objects.equals(this.logFilePrefix, logFilePrefixNorm)) { return; } this.logFilePrefix = logFilePrefixNorm; updateFileNamePattern(); } public String getLogFilePrefix() { return logFilePrefix; } public void setLogFileDatePattern(final String logFileDatePattern) { if (Objects.equals(this.logFileDatePattern, logFileDatePattern)) { return; } if (Check.isEmpty(logFileDatePattern, true)) { addError("Skip setting LogFileDatePattern to null"); return; } this.logFileDatePattern = logFileDatePattern; updateFileNamePattern(); } public String getLogFileDatePattern() { return logFileDatePattern; } private final void updateFileNamePattern() { final StringBuilder fileNamePatternBuilder = new StringBuilder(); final String logDir = getLogDir(); if (!Check.isEmpty(logDir, true)) { fileNamePatternBuilder.append(logDir); if (!logDir.endsWith("\\") && !logDir.endsWith("/")) { fileNamePatternBuilder.append(File.separator); } } final String logFilePrefix = getLogFilePrefix(); fileNamePatternBuilder.append(logFilePrefix); if (!Check.isEmpty(logFilePrefix)) { fileNamePatternBuilder.append("."); } fileNamePatternBuilder.append(getLogFileDatePattern()); fileNamePatternBuilder.append(logFileSuffix); final String fileNamePattern = fileNamePatternBuilder.toString(); super.setFileNamePattern(fileNamePattern); // System.out.println("Using FileNamePattern: " + fileNamePattern); } @Override public void setFileNamePattern(final String fnp) { throw new UnsupportedOperationException("Setting FileNamePattern directly is not allowed"); } public File getLogDirAsFile() {
if (logDir == null) { return null; } return new File(logDir); } public File getActiveFileOrNull() { try { final String filename = getActiveFileName(); if (filename == null) { return null; } final File file = new File(filename).getAbsoluteFile(); return file; } catch (Exception e) { addError("Failed fetching active file name", e); return null; } } public List<File> getLogFiles() { final File logDir = getLogDirAsFile(); if (logDir != null && logDir.isDirectory()) { final File[] logs = logDir.listFiles(logFileNameFilter); for (int i = 0; i < logs.length; i++) { try { logs[i] = logs[i].getCanonicalFile(); } catch (Exception e) { } } return ImmutableList.copyOf(logs); } return ImmutableList.of(); } public void flush() { // TODO } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshTimeBasedRollingPolicy.java
1
请在Spring Boot框架中完成以下Java代码
public void consume(Order order) throws IOException { log.info("Order received to process: {}", order); if (OrderStatus.INITIATION_SUCCESS.equals(order.getOrderStatus())) { orderRepository.findById(order.getId()) .map(o -> { orderProducer.sendMessage(o.setOrderStatus(OrderStatus.RESERVE_INVENTORY)); return o.setOrderStatus(order.getOrderStatus()) .setResponseMessage(order.getResponseMessage()); }) .flatMap(orderRepository::save) .subscribe(); } else if (OrderStatus.INVENTORY_SUCCESS.equals(order.getOrderStatus())) { orderRepository.findById(order.getId()) .map(o -> { orderProducer.sendMessage(o.setOrderStatus(OrderStatus.PREPARE_SHIPPING)); return o.setOrderStatus(order.getOrderStatus()) .setResponseMessage(order.getResponseMessage()); }) .flatMap(orderRepository::save) .subscribe(); } else if (OrderStatus.SHIPPING_FAILURE.equals(order.getOrderStatus())) {
orderRepository.findById(order.getId()) .map(o -> { orderProducer.sendMessage(o.setOrderStatus(OrderStatus.REVERT_INVENTORY)); return o.setOrderStatus(order.getOrderStatus()) .setResponseMessage(order.getResponseMessage()); }) .flatMap(orderRepository::save) .subscribe(); } else { orderRepository.findById(order.getId()) .map(o -> { return o.setOrderStatus(order.getOrderStatus()) .setResponseMessage(order.getResponseMessage()); }) .flatMap(orderRepository::save) .subscribe(); } } }
repos\tutorials-master\reactive-systems\order-service\src\main\java\com\baeldung\async\consumer\OrderConsumer.java
2
请完成以下Java代码
public void setName(String name) { this.name = name; } public void setMembers(List<User> members) { this.members = members; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; }
Group group = (Group) o; return Objects.equals(id, group.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } public String toString() { return "Group(id=" + this.getId() + ", name=" + this.getName() + ", members=" + this.getMembers() + ")"; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\eager\list\moderatedomain\Group.java
1
请在Spring Boot框架中完成以下Java代码
static class InitializrCacheConfiguration { @Bean JCacheManagerCustomizer initializrCacheManagerCustomizer() { return new InitializrJCacheManagerCustomizer(); } } @Order(0) private static final class InitializrJCacheManagerCustomizer implements JCacheManagerCustomizer { @Override public void customize(javax.cache.CacheManager cacheManager) { createMissingCache(cacheManager, "initializr.metadata", () -> config().setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES))); createMissingCache(cacheManager, "initializr.dependency-metadata", this::config); createMissingCache(cacheManager, "initializr.project-resources", this::config); createMissingCache(cacheManager, "initializr.templates", this::config); }
private void createMissingCache(javax.cache.CacheManager cacheManager, String cacheName, Supplier<MutableConfiguration<Object, Object>> config) { boolean cacheExist = StreamSupport.stream(cacheManager.getCacheNames().spliterator(), true) .anyMatch((name) -> name.equals(cacheName)); if (!cacheExist) { cacheManager.createCache(cacheName, config.get()); } } private MutableConfiguration<Object, Object> config() { return new MutableConfiguration<>().setStoreByValue(false) .setManagementEnabled(true) .setStatisticsEnabled(true); } } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\autoconfigure\InitializrAutoConfiguration.java
2
请完成以下Java代码
public void setIsPlaceBPAccountsOnCredit (final boolean IsPlaceBPAccountsOnCredit) { set_Value (COLUMNNAME_IsPlaceBPAccountsOnCredit, IsPlaceBPAccountsOnCredit); } @Override public boolean isPlaceBPAccountsOnCredit() { return get_ValueAsBoolean(COLUMNNAME_IsPlaceBPAccountsOnCredit); } /** * IsSOTrx AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISSOTRX_AD_Reference_ID=319; /** Yes = Y */ public static final String ISSOTRX_Yes = "Y"; /** No = N */ public static final String ISSOTRX_No = "N"; @Override public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public java.lang.String getIsSOTrx() { return get_ValueAsString(COLUMNNAME_IsSOTrx); } @Override public void setIsSwitchCreditMemo (final boolean IsSwitchCreditMemo) { set_Value (COLUMNNAME_IsSwitchCreditMemo, IsSwitchCreditMemo); }
@Override public boolean isSwitchCreditMemo() { return get_ValueAsBoolean(COLUMNNAME_IsSwitchCreditMemo); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_Export.java
1
请完成以下Java代码
public class Address { private String street; private String city; private String pin; public Address(String street, String city, String pin) { super(); this.street = street; this.city = city; this.pin = pin; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; }
public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPin() { return pin; } public void setPin(String pin) { this.pin = pin; } }
repos\tutorials-master\core-java-modules\core-java-17\src\main\java\com\baeldung\java8to17\Address.java
1
请在Spring Boot框架中完成以下Java代码
public class NoSupplyAdviceEvent implements MaterialEvent { public static final String TYPE = "NoSupplyAdviceEvent"; @NonNull SupplyRequiredDescriptor supplyRequiredDescriptor; public static NoSupplyAdviceEvent of(@NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor) { return NoSupplyAdviceEvent.builder().supplyRequiredDescriptor(supplyRequiredDescriptor).build(); } @JsonIgnore @Override public EventDescriptor getEventDescriptor() {
return supplyRequiredDescriptor.getEventDescriptor(); } @JsonIgnore public int getSupplyCandidateId() {return supplyRequiredDescriptor.getSupplyCandidateId();} @Nullable @Override public TableRecordReference getSourceTableReference() { return TableRecordReference.ofNullable(MD_CANDIDATE_TABLE_NAME, supplyRequiredDescriptor.getPpOrderCandidateId()); } @Override public String getEventName() {return TYPE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\supplyrequired\NoSupplyAdviceEvent.java
2
请完成以下Java代码
public void springBeanPointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Pointcut that matches all Spring beans in the application's main packages. */ @Pointcut("within(net.alanbinu.springboot2.springboot2jpacrudexample..*)"+ " || within(net.alanbinu.springboot2.springboot2jpacrudexample.service..*)"+ " || within(net.alanbinu.springboot2.springboot2jpacrudexample.controller..*)") public void applicationPackagePointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Advice that logs methods throwing exceptions. * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL"); } /** * Advice that logs when a method is entered and exited. * * @param joinPoint join point for advice * @return result * @throws Throwable throws IllegalArgumentException */ @Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); throw e; } } }
repos\Spring-Boot-Advanced-Projects-main\springboot2-springaop-example\src\main\java\net\alanbinu\springboot2\springboot2jpacrudexample\aspect\LoggingAspect.java
1
请完成以下Java代码
public JobQuery orderByJobDuedate() { return orderBy(JobQueryProperty.DUEDATE); } @Override public JobQuery orderByExecutionId() { return orderBy(JobQueryProperty.EXECUTION_ID); } @Override public JobQuery orderByJobId() { return orderBy(JobQueryProperty.JOB_ID); } @Override public JobQuery orderByProcessInstanceId() { return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID); } @Override public JobQuery orderByJobRetries() { return orderBy(JobQueryProperty.RETRIES); } @Override public JobQuery orderByTenantId() { return orderBy(JobQueryProperty.TENANT_ID); } // results ////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getJobEntityManager() .findJobCountByQueryCriteria(this); } @Override public List<Job> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getJobEntityManager() .findJobsByQueryCriteria(this, page); } // getters ////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public String getHandlerType() { return this.handlerType; } public boolean getRetriesLeft() { return retriesLeft; } public boolean getExecutable() { return executable; } public Date getNow() { return Context.getProcessEngineConfiguration().getClock().getCurrentTime(); }
public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public String getId() { return id; } public String getProcessDefinitionId() { return processDefinitionId; } public boolean isRetriesLeft() { return retriesLeft; } public boolean isExecutable() { return executable; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } public boolean isNoRetriesLeft() { return noRetriesLeft; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\JobQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
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
2
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_TaskInstance[") .append(get_ID()).append("]"); return sb.toString(); } /** Set OS Task. @param AD_Task_ID Operation System Task */ public void setAD_Task_ID (int AD_Task_ID) { if (AD_Task_ID < 1) set_Value (COLUMNNAME_AD_Task_ID, null); else set_Value (COLUMNNAME_AD_Task_ID, Integer.valueOf(AD_Task_ID)); } /** Get OS Task. @return Operation System Task */ public int getAD_Task_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Task_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Task Instance. @param AD_TaskInstance_ID Task Instance */ public void setAD_TaskInstance_ID (int AD_TaskInstance_ID) { if (AD_TaskInstance_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_TaskInstance_ID, null);
else set_ValueNoCheck (COLUMNNAME_AD_TaskInstance_ID, Integer.valueOf(AD_TaskInstance_ID)); } /** Get Task Instance. @return Task Instance */ public int getAD_TaskInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_TaskInstance_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getAD_TaskInstance_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_TaskInstance.java
1
请完成以下Java代码
public String getId() { return id; } public List<String> getIds() { return ids; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase; } public String getType() { return type; } public String getUserId() { return userId; } public List<String> getUserIds() { return userIds; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\GroupQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public TopicBuilder config(String configName, String configValue) { this.configs.put(configName, configValue); return this; } /** * Set the {@link TopicConfig#CLEANUP_POLICY_CONFIG} to * {@link TopicConfig#CLEANUP_POLICY_COMPACT}. * @return the builder. */ public TopicBuilder compact() { this.configs.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT); return this; } public NewTopic build() { NewTopic topic = this.replicasAssignments == null ? new NewTopic(this.name, this.partitions, this.replicas) : new NewTopic(this.name, this.replicasAssignments);
if (!this.configs.isEmpty()) { topic.configs(this.configs); } return topic; } /** * Create a TopicBuilder with the supplied name. * @param name the name. * @return the builder. */ public static TopicBuilder name(String name) { return new TopicBuilder(name); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\TopicBuilder.java
2
请完成以下Java代码
public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setOrgValue (java.lang.String OrgValue) { set_Value (COLUMNNAME_OrgValue, OrgValue); } @Override public java.lang.String getOrgValue() { return (java.lang.String)get_Value(COLUMNNAME_OrgValue); } @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setProductValue (java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } /** * ReplenishType AD_Reference_ID=164
* Reference name: M_Replenish Type */ public static final int REPLENISHTYPE_AD_Reference_ID=164; /** Maximalbestand beibehalten = 2 */ public static final String REPLENISHTYPE_MaximalbestandBeibehalten = "2"; /** Manuell = 0 */ public static final String REPLENISHTYPE_Manuell = "0"; /** Bei Unterschreitung Minimalbestand = 1 */ public static final String REPLENISHTYPE_BeiUnterschreitungMinimalbestand = "1"; /** Custom = 9 */ public static final String REPLENISHTYPE_Custom = "9"; /** Zuk?nftigen Bestand sichern = 7 */ public static final String REPLENISHTYPE_ZukNftigenBestandSichern = "7"; @Override public void setReplenishType (java.lang.String ReplenishType) { set_Value (COLUMNNAME_ReplenishType, ReplenishType); } @Override public java.lang.String getReplenishType() { return (java.lang.String)get_Value(COLUMNNAME_ReplenishType); } @Override public void setTimeToMarket (int TimeToMarket) { set_Value (COLUMNNAME_TimeToMarket, Integer.valueOf(TimeToMarket)); } @Override public int getTimeToMarket() { return get_ValueAsInt(COLUMNNAME_TimeToMarket); } @Override public void setWarehouseValue (java.lang.String WarehouseValue) { set_Value (COLUMNNAME_WarehouseValue, WarehouseValue); } @Override public java.lang.String getWarehouseValue() { return (java.lang.String)get_Value(COLUMNNAME_WarehouseValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Replenish.java
1
请完成以下Java代码
public String getDatabaseTablePrefix() { return dbSqlSession.getDbSqlSessionFactory().getDatabaseTablePrefix(); } @Override public boolean isTablePrefixIsSchema() { return dbSqlSession.getDbSqlSessionFactory().isTablePrefixIsSchema(); } @Override public String getDatabaseCatalog() { String catalog = dbSqlSession.getConnectionMetadataDefaultCatalog(); DbSqlSessionFactory dbSqlSessionFactory = dbSqlSession.getDbSqlSessionFactory(); if (dbSqlSessionFactory.getDatabaseCatalog() != null && dbSqlSessionFactory.getDatabaseCatalog().length() > 0) { catalog = dbSqlSessionFactory.getDatabaseCatalog(); } return catalog; } @Override
public String getDatabaseSchema() { String schema = dbSqlSession.getConnectionMetadataDefaultSchema(); DbSqlSessionFactory dbSqlSessionFactory = dbSqlSession.getDbSqlSessionFactory(); if (dbSqlSessionFactory.getDatabaseSchema() != null && dbSqlSessionFactory.getDatabaseSchema().length() > 0) { schema = dbSqlSessionFactory.getDatabaseSchema(); } else if (dbSqlSessionFactory.isTablePrefixIsSchema() && StringUtils.isNotEmpty(dbSqlSessionFactory.getDatabaseTablePrefix())) { schema = dbSqlSessionFactory.getDatabaseTablePrefix(); if (StringUtils.isNotEmpty(schema) && schema.endsWith(".")) { schema = schema.substring(0, schema.length() - 1); } } return schema; } @Override public Connection getConnection() { return dbSqlSession.getSqlSession().getConnection(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\DbSqlSessionSchemaManagerConfiguration.java
1
请完成以下Java代码
public class QueryOrderingProperty implements Serializable { public static final String RELATION_VARIABLE = "variable"; public static final String RELATION_PROCESS_DEFINITION = "process-definition"; public static final String RELATION_CASE_DEFINITION = "case-definition"; public static final String RELATION_DEPLOYMENT = "deployment"; protected static final long serialVersionUID = 1L; protected String relation; protected QueryProperty queryProperty; protected Direction direction; protected List<QueryEntityRelationCondition> relationConditions; public QueryOrderingProperty() { } public QueryOrderingProperty(QueryProperty queryProperty, Direction direction) { this.queryProperty = queryProperty; this.direction = direction; } public QueryOrderingProperty(String relation, QueryProperty queryProperty) { this.relation = relation; this.queryProperty = queryProperty; } public QueryProperty getQueryProperty() { return queryProperty; } public void setQueryProperty(QueryProperty queryProperty) { this.queryProperty = queryProperty; } public void setDirection(Direction direction) { this.direction = direction; } public Direction getDirection() { return direction; } public List<QueryEntityRelationCondition> getRelationConditions() { return relationConditions; } public void setRelationConditions(List<QueryEntityRelationCondition> relationConditions) { this.relationConditions = relationConditions; } public boolean hasRelationConditions() { return relationConditions != null && !relationConditions.isEmpty(); } public String getRelation() { return relation;
} public void setRelation(String relation) { this.relation = relation; } /** * @return whether this ordering property is contained in the default fields * of the base entity (e.g. task.NAME_ is a contained property; LOWER(task.NAME_) or * variable.TEXT_ (given a task query) is not contained) */ public boolean isContainedProperty() { return relation == null && queryProperty.getFunction() == null; } @Override public String toString() { return "QueryOrderingProperty[" + "relation=" + relation + ", queryProperty=" + queryProperty + ", direction=" + direction + ", relationConditions=" + getRelationConditionsString() + "]"; } public String getRelationConditionsString() { StringBuilder builder = new StringBuilder(); builder.append("["); if(relationConditions != null) { for (int i = 0; i < relationConditions.size(); i++) { if (i > 0) { builder.append(","); } builder.append(relationConditions.get(i)); } } builder.append("]"); return builder.toString(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\QueryOrderingProperty.java
1
请完成以下Java代码
public void updateAllocationLUForTU(final I_M_HU tuHU) { // Services final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); final IQueryBL queryBL = Services.get(IQueryBL.class); Check.assume(handlingUnitsBL.isTransportUnitOrVirtual(tuHU), "{} shall be a TU", tuHU); // // Get the LU final I_M_HU luHU = handlingUnitsBL.getLoadingUnitHU(tuHU); // // Retrieve allocations which are about our TU final List<I_M_ReceiptSchedule_Alloc> allocs = queryBL.createQueryBuilder(I_M_ReceiptSchedule_Alloc.class, tuHU) .addEqualsFilter(I_M_ReceiptSchedule_Alloc.COLUMNNAME_M_TU_HU_ID, tuHU.getM_HU_ID()) // Only those which are active .addOnlyActiveRecordsFilter() // Only those which were not received. // Those which were received we consider as "Processed" and we don't want to touch them .addEqualsFilter(de.metas.inoutcandidate.model.I_M_ReceiptSchedule_Alloc.COLUMNNAME_M_InOutLine_ID, null) // .create() .list(); // // Iterate all allocations and update M_LU_HU_ID for (final I_M_ReceiptSchedule_Alloc alloc : allocs) { // Update LU alloc.setM_LU_HU(luHU);
InterfaceWrapperHelper.save(alloc); } } @Override public I_M_ReceiptSchedule retrieveReceiptScheduleForVHU(final I_M_HU vhu) { // Services final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); final IQueryBL queryBL = Services.get(IQueryBL.class); // Validate Check.assume(handlingUnitsBL.isVirtual(vhu), "{} shall be VirtualHU", vhu); return queryBL.createQueryBuilder(I_M_ReceiptSchedule_Alloc.class, vhu) .addEqualsFilter(I_M_ReceiptSchedule_Alloc.COLUMNNAME_VHU_ID, vhu.getM_HU_ID()) // Only those which are active .addOnlyActiveRecordsFilter() // Only those which were not received. // Those which were received we consider as "Processed" and we don't want to touch them .addEqualsFilter(de.metas.inoutcandidate.model.I_M_ReceiptSchedule_Alloc.COLUMNNAME_M_InOutLine_ID, null) // // Collect the referenced Receipt schedule // NOTE: we assume it's only one because a VHU can be assigned to only one receipt schedule! .andCollect(de.metas.inoutcandidate.model.I_M_ReceiptSchedule_Alloc.COLUMN_M_ReceiptSchedule_ID) .create() .firstOnly(I_M_ReceiptSchedule.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\HUReceiptScheduleDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfiguration { @Autowired UserDetailsService userDetailsService; @Autowired private AuthEntryPointJwt unauthorizedHandler; private static final String[] WHITE_LIST_URL = { "/h2-console/**", "/signin", "/signup", "/user-dashboard" }; @Bean public AuthTokenFilter authenticationJwtTokenFilter() { return new AuthTokenFilter(); } @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(passwordEncoder()); return authProvider; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder();
} @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception { return authConfig.getAuthenticationManager(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { http.csrf(AbstractHttpConfigurer::disable) .cors(AbstractHttpConfigurer::disable) .authorizeHttpRequests(req -> req.requestMatchers(WHITE_LIST_URL) .permitAll() .anyRequest() .authenticated()) .exceptionHandling(ex -> ex.authenticationEntryPoint(unauthorizedHandler)) .sessionManagement(session -> session.sessionCreationPolicy(STATELESS)) .authenticationProvider(authenticationProvider()) .addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); return http.build(); } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\securityconfig\SecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class FreshQtyOnHandId implements RepoIdAware { int repoId; @JsonCreator public static FreshQtyOnHandId ofRepoId(final int repoId) { return new FreshQtyOnHandId(repoId); } @Nullable public static FreshQtyOnHandId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new FreshQtyOnHandId(repoId) : null; } @Nullable public static FreshQtyOnHandId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new FreshQtyOnHandId(repoId) : null; } public static int toRepoId(@Nullable final FreshQtyOnHandId freshQtyOnHandId) { return freshQtyOnHandId != null ? freshQtyOnHandId.getRepoId() : -1; } public static boolean equals(@Nullable final FreshQtyOnHandId o1, @Nullable final FreshQtyOnHandId o2)
{ return Objects.equals(o1, o2); } private FreshQtyOnHandId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "FreshQtyOnHandId"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\freshQtyOnHand\FreshQtyOnHandId.java
2
请完成以下Java代码
public class DunningEventDispatcher implements IDunningEventDispatcher { private final Map<String, List<IDunningCandidateListener>> dunningCandidateListeners = new HashMap<String, List<IDunningCandidateListener>>(); private final Map<DunningDocLineSourceEvent, List<IDunningDocLineSourceListener>> dunningDocLineSourceListeners = new HashMap<DunningDocLineSourceEvent, List<IDunningDocLineSourceListener>>(); @Override public boolean registerDunningCandidateListener(final String eventName, final IDunningCandidateListener listener) { Check.assumeNotNull(eventName, "eventName not null"); Check.assumeNotNull(listener, "listener not null"); List<IDunningCandidateListener> eventListeners = dunningCandidateListeners.get(eventName); if (eventListeners == null) { eventListeners = new ArrayList<IDunningCandidateListener>(); dunningCandidateListeners.put(eventName, eventListeners); } if (eventListeners.contains(listener)) { return false; } eventListeners.add(listener); return true; } @Override public void fireDunningCandidateEvent( @NonNull final String eventName, @NonNull final I_C_Dunning_Candidate candidate) { synchronized (dunningCandidateListeners) { final List<IDunningCandidateListener> listeners = dunningCandidateListeners.get(eventName); if (listeners == null) { return; } for (final IDunningCandidateListener listener : listeners) { listener.onEvent(eventName, candidate); } } } @Override public boolean registerDunningDocLineSourceListener(final DunningDocLineSourceEvent eventName, final IDunningDocLineSourceListener listener) { Check.assumeNotNull(eventName, "eventName not null"); Check.assumeNotNull(listener, "listener not null"); List<IDunningDocLineSourceListener> eventListeners = dunningDocLineSourceListeners.get(eventName); if (eventListeners == null) { eventListeners = new ArrayList<IDunningDocLineSourceListener>(); dunningDocLineSourceListeners.put(eventName, eventListeners); }
if (eventListeners.contains(listener)) { return false; } eventListeners.add(listener); return true; } @Override public void fireDunningDocLineSourceEvent(final DunningDocLineSourceEvent eventName, final I_C_DunningDoc_Line_Source source) { Check.assumeNotNull(eventName, "eventName not null"); Check.assumeNotNull(source, "source not null"); synchronized (dunningDocLineSourceListeners) { final List<IDunningDocLineSourceListener> listeners = dunningDocLineSourceListeners.get(eventName); if (listeners == null) { return; } for (final IDunningDocLineSourceListener listener : listeners) { listener.onEvent(eventName, source); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningEventDispatcher.java
1
请完成以下Java代码
private static boolean isDescriptionValid(String description) { // @formatter:off return description == null || description.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21) || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E)); // @formatter:on } private static boolean isErrorCodeValid(String errorCode) { // @formatter:off return errorCode.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21) || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E)); // @formatter:on } private static boolean isErrorUriValid(String errorUri) { return errorUri == null || errorUri.chars() .allMatch((c) -> c == 0x21 || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
} private static boolean isScopeValid(String scope) { // @formatter:off return scope == null || scope.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21) || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E)); // @formatter:on } private static boolean withinTheRangeOf(int c, int min, int max) { return c >= min && c <= max; } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\BearerTokenError.java
1
请完成以下Java代码
public static InternalName ofString(@NonNull final String str) { final String strNorm = normalizeString(str); if (str.isEmpty()) { throw new AdempiereException("Invalid internal name: " + str); } return new InternalName(strNorm); } /** * This is mostly for cypress and also to be in line with the html specification (https://www.w3.org/TR/html50/dom.html#the-id-attribute). * * There are some processes (actions) which have space in their #ID. * On the frontend side: that internalName field is used to create the JSON. * On the backend side: the process value is used to create the internalName. * * The simple solution is to replace spaces with underscores. */ @NonNull private static String normalizeString(@NonNull final String str) { return str.trim() .replace(" ", "_"); }
private final String stringValue; private InternalName(@NonNull final String stringValue) { this.stringValue = stringValue; } /** * @deprecated please use {@link #getAsString()} */ @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { return stringValue; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\InternalName.java
1
请完成以下Java代码
private void executeCallout( final IAttributeValueContext attributeValueContext, final IAttributeValueCallout callout, final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueOld, final Object valueNew) { if (calloutsActive.contains(callout)) { // Callout is already running, not finished yet. // We shall skip executing it again because otherwise we will end up in infinite recursion if (logger.isWarnEnabled()) { logger.warn("Skip executing callout " + callout + " because it's already running: " + calloutsActive); } return; } try {
calloutsActive.add(callout); callout.onValueChanged(attributeValueContext, attributeSet, attribute, valueOld, valueNew); } finally { calloutsActive.remove(callout); } } @Override public String toString() { return "AttributeSetCalloutExecutor [calloutsActive=" + calloutsActive + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeSetCalloutExecutor.java
1
请完成以下Java代码
public void addingMatrices() throws Exception { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2, 3}, {4, 5, 6} }); Matrix m2 = new DenseMatrix(new double[][]{ {3, 2, 1}, {6, 5, 4} }); Matrix m3 = m1.add(m2); log.info("Adding matrices: {}", m3); } public void multiplyMatrices() throws Exception { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2, 3}, {4, 5, 6} }); Matrix m2 = new DenseMatrix(new double[][]{ {1, 4}, {2, 5}, {3, 6} }); Matrix m3 = m1.multiply(m2); log.info("Multiplying matrices: {}", m3); } public void multiplyIncorrectMatrices() throws Exception { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2, 3}, {4, 5, 6} }); Matrix m2 = new DenseMatrix(new double[][]{ {3, 2, 1}, {6, 5, 4} }); Matrix m3 = m1.multiply(m2); log.info("Multiplying matrices: {}", m3); } public void inverseMatrix() { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2}, {3, 4} }); Inverse m2 = new Inverse(m1);
log.info("Inverting a matrix: {}", m2); log.info("Verifying a matrix inverse: {}", m1.multiply(m2)); } public Polynomial createPolynomial() { return new Polynomial(new double[]{3, -5, 1}); } public void evaluatePolynomial(Polynomial p) { // Evaluate using a real number log.info("Evaluating a polynomial using a real number: {}", p.evaluate(5)); // Evaluate using a complex number log.info("Evaluating a polynomial using a complex number: {}", p.evaluate(new Complex(1, 2))); } public void solvePolynomial() { Polynomial p = new Polynomial(new double[]{2, 2, -4}); PolyRootSolver solver = new PolyRoot(); List<? extends Number> roots = solver.solve(p); log.info("Finding polynomial roots: {}", roots); } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\suanshu\SuanShuMath.java
1
请完成以下Java代码
public void generateDirectMovements(@NonNull final I_DD_Order ddOrder) { final DDOrderMovePlan plan = ddOrderMoveScheduleService.createPlan(DDOrderMovePlanCreateRequest.builder() .ddOrder(ddOrder) .failIfNotFullAllocated(true) .build()); final ImmutableList<DDOrderMoveSchedule> schedules = ddOrderMoveScheduleService.savePlan(plan); DirectMovementsFromSchedulesGenerator.fromSchedules(schedules, this, ddOrderMoveScheduleService) .skipCompletingDDOrder() // because usually this code is calling on after complete... .generateDirectMovements(); } public boolean isCreateMovementOnComplete() { return sysConfigBL.getBooleanValue(SYSCONFIG_IsCreateMovementOnComplete, false); } public Quantity getQtyToShip(final I_DD_OrderLine_Or_Alternative ddOrderLineOrAlt) { return ddOrderLowLevelService.getQtyToShip(ddOrderLineOrAlt); } public void assignToResponsible(@NonNull final I_DD_Order ddOrder, @NonNull final UserId responsibleId) { final UserId currentResponsibleId = extractCurrentResponsibleId(ddOrder); if (currentResponsibleId == null) { ddOrder.setAD_User_Responsible_ID(responsibleId.getRepoId()); save(ddOrder); } else if (!UserId.equals(currentResponsibleId, responsibleId)) { throw new AdempiereException("DD Order already assigned to a different responsible"); } else { // already assigned to that responsible, // shall not happen but we can safely ignore the case logger.warn("Order {} already assigned to {}", ddOrder.getDD_Order_ID(), responsibleId); } }
@Nullable private static UserId extractCurrentResponsibleId(final I_DD_Order ddOrder) { return UserId.ofRepoIdOrNullIfSystem(ddOrder.getAD_User_Responsible_ID()); } public void unassignFromResponsible(final DDOrderId ddOrderId) { final I_DD_Order ddOrder = getById(ddOrderId); unassignFromResponsibleAndSave(ddOrder); } public void removeAllNotStartedSchedules(final DDOrderId ddOrderId) { ddOrderMoveScheduleService.removeNotStarted(ddOrderId); } private void unassignFromResponsibleAndSave(final I_DD_Order ddOrder) { ddOrder.setAD_User_Responsible_ID(-1); save(ddOrder); } public Set<ProductId> getProductIdsByDDOrderIds(final Collection<DDOrderId> ddOrderIds) { return ddOrderLowLevelDAO.getProductIdsByDDOrderIds(ddOrderIds); } public Stream<I_DD_OrderLine> streamLinesByDDOrderIds(@NonNull final Collection<DDOrderId> ddOrderIds) { return ddOrderLowLevelDAO.streamLinesByDDOrderIds(ddOrderIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\DDOrderService.java
1
请完成以下Java代码
public void run() { final int sleep = Services.get(ISysConfigBL.class).getIntValue("MENU_INFOUPDATER_SLEEP_MS", 60000, Env.getAD_Client_ID(Env.getCtx())); while (stop == false) { updateInfo(); try { synchronized (this) { this.wait(sleep); } } catch (InterruptedException ire) { } } } } private static AdTreeId retrieveMenuTreeId(final Properties ctx) { final IUserRolePermissions userRolePermissions = Env.getUserRolePermissions(ctx); if (!userRolePermissions.hasPermission(IUserRolePermissions.PERMISSION_MenuAvailable)) { return null; } return userRolePermissions.getMenuInfo().getAdTreeId(); } public FormFrame startForm(final int AD_Form_ID) { // metas: tsa: begin: US831: Open one window per session per user (2010101810000044) final Properties ctx = Env.getCtx(); final I_AD_Form form = InterfaceWrapperHelper.create(ctx, AD_Form_ID, I_AD_Form.class, ITrx.TRXNAME_None); if (form == null) { ADialog.warn(0, null, "Error", msgBL.parseTranslation(ctx, "@NotFound@ @AD_Form_ID@")); return null; } final WindowManager windowManager = getWindowManager(); // metas: tsa: end: US831: Open one window per session per user (2010101810000044) if (Ini.isPropertyBool(Ini.P_SINGLE_INSTANCE_PER_WINDOW) || form.isOneInstanceOnly()) // metas: tsa: us831
{ final FormFrame ffExisting = windowManager.findForm(AD_Form_ID); if (ffExisting != null) { AEnv.showWindow(ffExisting); // metas: tsa: use this method because toFront() is not working when window is minimized // ff.toFront(); // metas: tsa: commented original code return ffExisting; } } final FormFrame ff = new FormFrame(); final boolean ok = ff.openForm(form); // metas: tsa: us831 if (!ok) { ff.dispose(); return null; } windowManager.add(ff); // Center the window ff.showFormWindow(); return ff; } // startForm } // AMenu
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AMenu.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { return acceptIfEligibleOrder(context) .and(() -> acceptIfOrderLinesNotInGroup(context)); } @Override protected String doIt() { groupsRepo.prepareNewGroup() .groupTemplate(createNewGroupTemplate()) .createGroup(getSelectedOrderLineIds()); return MSG_OK; } private GroupTemplate createNewGroupTemplate() { String groupNameEffective = this.groupName;
if (Check.isEmpty(groupNameEffective, true) && productCategory != null) { groupNameEffective = productCategory.getName(); } if (Check.isEmpty(groupNameEffective, true)) { throw new FillMandatoryException("Name"); } return GroupTemplate.builder() .name(groupNameEffective) .productCategoryId(productCategory != null ? ProductCategoryId.ofRepoId(productCategory.getM_Product_Category_ID()) : null) .compensationLine(GroupTemplateCompensationLine.ofProductId(ProductId.ofRepoId(compensationProductId))) .regularLinesToAdd(ImmutableList.of()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\process\C_Order_CreateCompensationGroup.java
1
请在Spring Boot框架中完成以下Java代码
public File getSingleDocument(String apiKey, String id) throws ApiException { ApiResponse<File> resp = getSingleDocumentWithHttpInfo(apiKey, id); return resp.getData(); } /** * Einzelnes Dokument abrufen * Szenario - das WaWi fragt ein bestimmtes Dokument im PDF-Format an * @param apiKey (required) * @param id (required) * @return ApiResponse&lt;File&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<File> getSingleDocumentWithHttpInfo(String apiKey, String id) throws ApiException { com.squareup.okhttp.Call call = getSingleDocumentValidateBeforeCall(apiKey, id, null, null); Type localVarReturnType = new TypeToken<File>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Einzelnes Dokument abrufen (asynchronously) * Szenario - das WaWi fragt ein bestimmtes Dokument im PDF-Format an * @param apiKey (required) * @param id (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getSingleDocumentAsync(String apiKey, String id, final ApiCallback<File> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getSingleDocumentValidateBeforeCall(apiKey, id, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<File>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\api\DocumentApi.java
2
请完成以下Java代码
public String get_ValueAsString(String variableName) { return values.get(variableName); } public void setValue(String variableName, String value) { values.put(variableName, value); } public void setContextTableName(String contextTableName) { values.put(PARAMETER_ContextTableName, contextTableName); } @Override public String getTableName()
{ return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } @Override public String toString() { return String.format("PlainValidationContext [contextTableName=%s, tableName=%s, values=%s]", contextTableName, tableName, values); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\PlainValidationContext.java
1
请完成以下Java代码
public IntStream generateRandomLimitedIntStream(long streamSize) { Random random = new Random(); IntStream limitedIntStream = random.ints(streamSize); return limitedIntStream; } public IntStream generateRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) { Random random = new Random(); IntStream limitedIntStreamWithinARange = random.ints(streamSize, min, max); return limitedIntStreamWithinARange; } public Integer generateRandomWithThreadLocalRandom() { int randomWithThreadLocalRandom = ThreadLocalRandom.current() .nextInt(); return randomWithThreadLocalRandom; } public Integer generateRandomWithThreadLocalRandomInARange(int min, int max) { int randomWithThreadLocalRandomInARange = ThreadLocalRandom.current() .nextInt(min, max); return randomWithThreadLocalRandomInARange; } public Integer generateRandomWithThreadLocalRandomFromZero(int max) { int randomWithThreadLocalRandomFromZero = ThreadLocalRandom.current() .nextInt(max); return randomWithThreadLocalRandomFromZero; } public Integer generateRandomWithSplittableRandom(int min, int max) { SplittableRandom splittableRandom = new SplittableRandom(); int randomWithSplittableRandom = splittableRandom.nextInt(min, max);
return randomWithSplittableRandom; } public IntStream generateRandomWithSplittableRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) { SplittableRandom splittableRandom = new SplittableRandom(); IntStream limitedIntStreamWithinARangeWithSplittableRandom = splittableRandom.ints(streamSize, min, max); return limitedIntStreamWithinARangeWithSplittableRandom; } public Integer generateRandomWithSecureRandom() { SecureRandom secureRandom = new SecureRandom(); int randomWithSecureRandom = secureRandom.nextInt(); return randomWithSecureRandom; } public Integer generateRandomWithSecureRandomWithinARange(int min, int max) { SecureRandom secureRandom = new SecureRandom(); int randomWithSecureRandomWithinARange = secureRandom.nextInt(max - min) + min; return randomWithSecureRandomWithinARange; } public Integer generateRandomWithRandomDataGenerator(int min, int max) { RandomDataGenerator randomDataGenerator = new RandomDataGenerator(); int randomWithRandomDataGenerator = randomDataGenerator.nextInt(min, max); return randomWithRandomDataGenerator; } public Integer generateRandomWithXoRoShiRo128PlusRandom(int min, int max) { XoRoShiRo128PlusRandom xoroRandom = new XoRoShiRo128PlusRandom(); int randomWithXoRoShiRo128PlusRandom = xoroRandom.nextInt(max - min) + min; return randomWithXoRoShiRo128PlusRandom; } }
repos\tutorials-master\core-java-modules\core-java-numbers-3\src\main\java\com\baeldung\randomnumbers\RandomNumbersGenerator.java
1
请完成以下Java代码
public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName == null ? null : loginName.trim(); } public String getLoginPassword() { return loginPassword; } public void setLoginPassword(String loginPassword) { this.loginPassword = loginPassword == null ? null : loginPassword.trim(); } public String getAdminNickName() { return adminNickName; } public void setAdminNickName(String adminNickName) { this.adminNickName = adminNickName == null ? null : adminNickName.trim(); } public Byte getLocked() { return locked; } public void setLocked(Byte locked) { this.locked = locked;
} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", adminId=").append(adminId); sb.append(", loginName=").append(loginName); sb.append(", loginPassword=").append(loginPassword); sb.append(", adminNickName=").append(adminNickName); sb.append(", locked=").append(locked); sb.append("]"); return sb.toString(); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\Admin.java
1
请完成以下Java代码
public int getReportBottom_Logo_ID() { return get_ValueAsInt(COLUMNNAME_ReportBottom_Logo_ID); } @Override public void setReportPrefix (final java.lang.String ReportPrefix) { set_Value (COLUMNNAME_ReportPrefix, ReportPrefix); } @Override public java.lang.String getReportPrefix() { return get_ValueAsString(COLUMNNAME_ReportPrefix); } /** * StoreCreditCardData AD_Reference_ID=540197 * Reference name: StoreCreditCardData */ public static final int STORECREDITCARDDATA_AD_Reference_ID=540197; /** Speichern = STORE */ public static final String STORECREDITCARDDATA_Speichern = "STORE"; /** Nicht Speichern = DONT */ public static final String STORECREDITCARDDATA_NichtSpeichern = "DONT"; /** letzte 4 Stellen = LAST4 */ public static final String STORECREDITCARDDATA_Letzte4Stellen = "LAST4"; @Override public void setStoreCreditCardData (final java.lang.String StoreCreditCardData) { set_Value (COLUMNNAME_StoreCreditCardData, StoreCreditCardData); } @Override public java.lang.String getStoreCreditCardData() { return get_ValueAsString(COLUMNNAME_StoreCreditCardData); } @Override public void setSupervisor_ID (final int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Supervisor_ID); } @Override public int getSupervisor_ID() { return get_ValueAsInt(COLUMNNAME_Supervisor_ID); }
@Override public void setTimeZone (final @Nullable java.lang.String TimeZone) { set_Value (COLUMNNAME_TimeZone, TimeZone); } @Override public java.lang.String getTimeZone() { return get_ValueAsString(COLUMNNAME_TimeZone); } @Override public void setTransferBank_ID (final int TransferBank_ID) { if (TransferBank_ID < 1) set_Value (COLUMNNAME_TransferBank_ID, null); else set_Value (COLUMNNAME_TransferBank_ID, TransferBank_ID); } @Override public int getTransferBank_ID() { return get_ValueAsInt(COLUMNNAME_TransferBank_ID); } @Override public org.compiere.model.I_C_CashBook getTransferCashBook() { return get_ValueAsPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class); } @Override public void setTransferCashBook(final org.compiere.model.I_C_CashBook TransferCashBook) { set_ValueFromPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class, TransferCashBook); } @Override public void setTransferCashBook_ID (final int TransferCashBook_ID) { if (TransferCashBook_ID < 1) set_Value (COLUMNNAME_TransferCashBook_ID, null); else set_Value (COLUMNNAME_TransferCashBook_ID, TransferCashBook_ID); } @Override public int getTransferCashBook_ID() { return get_ValueAsInt(COLUMNNAME_TransferCashBook_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgInfo.java
1
请完成以下Java代码
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { if(propertyFileName.equals("")) propertyFileName = null; PROPERTY_FILE_NAME = propertyFileName; ServiceRegistry serviceRegistry = configureServiceRegistry(); return makeSessionFactory(serviceRegistry); } public static SessionFactory getSessionFactory(Strategy strategy) { return buildSessionFactory(strategy); } private static SessionFactory buildSessionFactory(Strategy strategy) { try { ServiceRegistry serviceRegistry = configureServiceRegistry(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); for (Class<?> entityClass : strategy.getEntityClasses()) { metadataSources.addAnnotatedClass(entityClass); } Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); } catch (IOException ex) { throw new ExceptionInInitializerError(ex); } } private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.pojo"); metadataSources.addAnnotatedClass(Animal.class); metadataSources.addAnnotatedClass(Bag.class); metadataSources.addAnnotatedClass(Laptop.class); metadataSources.addAnnotatedClass(Book.class); metadataSources.addAnnotatedClass(Car.class); metadataSources.addAnnotatedClass(MyEmployee.class); metadataSources.addAnnotatedClass(MyProduct.class); metadataSources.addAnnotatedClass(Pen.class); metadataSources.addAnnotatedClass(Pet.class); metadataSources.addAnnotatedClass(Vehicle.class); metadataSources.addAnnotatedClass(TemporalValues.class); Metadata metadata = metadataSources.getMetadataBuilder() .build();
return metadata.getSessionFactoryBuilder() .build(); } private static ServiceRegistry configureServiceRegistry() throws IOException { Properties properties = getProperties(); return new StandardServiceRegistryBuilder().applySettings(properties) .build(); } private static Properties getProperties() throws IOException { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } return properties; } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\HibernateUtil.java
1
请完成以下Java代码
public final class ConcurrentSessionControlServerAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler { private final ReactiveSessionRegistry sessionRegistry; private final ServerMaximumSessionsExceededHandler maximumSessionsExceededHandler; private SessionLimit sessionLimit = SessionLimit.of(1); public ConcurrentSessionControlServerAuthenticationSuccessHandler(ReactiveSessionRegistry sessionRegistry, ServerMaximumSessionsExceededHandler maximumSessionsExceededHandler) { Assert.notNull(sessionRegistry, "sessionRegistry cannot be null"); Assert.notNull(maximumSessionsExceededHandler, "maximumSessionsExceededHandler cannot be null"); this.sessionRegistry = sessionRegistry; this.maximumSessionsExceededHandler = maximumSessionsExceededHandler; } @Override public Mono<Void> onAuthenticationSuccess(WebFilterExchange exchange, Authentication authentication) { return this.sessionLimit.apply(authentication) .flatMap((maxSessions) -> handleConcurrency(exchange, authentication, maxSessions)); } private Mono<Void> handleConcurrency(WebFilterExchange exchange, Authentication authentication, Integer maximumSessions) { return this.sessionRegistry.getAllSessions(Objects.requireNonNull(authentication.getPrincipal())) .collectList() .flatMap((registeredSessions) -> exchange.getExchange() .getSession() .map((currentSession) -> Tuples.of(currentSession, registeredSessions))) .flatMap((sessionTuple) -> { WebSession currentSession = sessionTuple.getT1(); List<ReactiveSessionInformation> registeredSessions = sessionTuple.getT2(); int registeredSessionsCount = registeredSessions.size(); if (registeredSessionsCount < maximumSessions) { return Mono.empty(); } if (registeredSessionsCount == maximumSessions) {
for (ReactiveSessionInformation registeredSession : registeredSessions) { if (registeredSession.getSessionId().equals(currentSession.getId())) { return Mono.empty(); } } } return this.maximumSessionsExceededHandler.handle(new MaximumSessionsContext(authentication, registeredSessions, maximumSessions, currentSession)); }); } /** * Sets the strategy used to resolve the maximum number of sessions that are allowed * for a specific {@link Authentication}. By default, it returns {@code 1} for any * authentication. * @param sessionLimit the {@link SessionLimit} to use */ public void setSessionLimit(SessionLimit sessionLimit) { Assert.notNull(sessionLimit, "sessionLimit cannot be null"); this.sessionLimit = sessionLimit; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\ConcurrentSessionControlServerAuthenticationSuccessHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void setSaveMode(SaveMode saveMode) { Assert.notNull(saveMode, "saveMode must not be null"); this.saveMode = saveMode; } protected SaveMode getSaveMode() { return this.saveMode; } @Autowired public void setRedisConnectionFactory( @SpringSessionRedisConnectionFactory ObjectProvider<RedisConnectionFactory> springSessionRedisConnectionFactory, ObjectProvider<RedisConnectionFactory> redisConnectionFactory) { this.redisConnectionFactory = springSessionRedisConnectionFactory .getIfAvailable(redisConnectionFactory::getObject); } protected RedisConnectionFactory getRedisConnectionFactory() { return this.redisConnectionFactory; } @Autowired(required = false) @Qualifier("springSessionDefaultRedisSerializer") public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) { this.defaultRedisSerializer = defaultRedisSerializer; } protected RedisSerializer<Object> getDefaultRedisSerializer() { return this.defaultRedisSerializer; } @Autowired(required = false) public void setSessionRepositoryCustomizer( ObjectProvider<SessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) { this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList()); } protected List<SessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() { return this.sessionRepositoryCustomizers; }
@Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } protected RedisTemplate<String, Object> createRedisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(RedisSerializer.string()); redisTemplate.setHashKeySerializer(RedisSerializer.string()); if (getDefaultRedisSerializer() != null) { redisTemplate.setDefaultSerializer(getDefaultRedisSerializer()); } redisTemplate.setConnectionFactory(getRedisConnectionFactory()); redisTemplate.setBeanClassLoader(this.classLoader); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\AbstractRedisHttpSessionConfiguration.java
2
请完成以下Java代码
public List getAllTutorial() { try { FileInputStream fileIS = new FileInputStream(this.getFile()); DocumentBuilderFactory builderFactory = newSecureDocumentBuilderFactory(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document xmlDocument = builder.parse(fileIS); String expression = "/tutorials/tutorial"; XPath path = new DOMXPath(expression); List result = path.selectNodes(xmlDocument); return result;
} catch (SAXException | IOException | ParserConfigurationException | JaxenException e) { e.printStackTrace(); return null; } } public File getFile() { return file; } public void setFile(File file) { this.file = file; } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\JaxenDemo.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getAllowedMethods() { return this.allowedMethods; } public void setAllowedMethods(List<String> allowedMethods) { this.allowedMethods = allowedMethods; } public List<String> getAllowedHeaders() { return this.allowedHeaders; } public void setAllowedHeaders(List<String> allowedHeaders) { this.allowedHeaders = allowedHeaders; } public List<String> getExposedHeaders() { return this.exposedHeaders; } public void setExposedHeaders(List<String> exposedHeaders) { this.exposedHeaders = exposedHeaders; } public @Nullable Boolean getAllowCredentials() { return this.allowCredentials; } public void setAllowCredentials(@Nullable Boolean allowCredentials) {
this.allowCredentials = allowCredentials; } public Duration getMaxAge() { return this.maxAge; } public void setMaxAge(Duration maxAge) { this.maxAge = maxAge; } public @Nullable CorsConfiguration toCorsConfiguration() { if (CollectionUtils.isEmpty(this.allowedOrigins) && CollectionUtils.isEmpty(this.allowedOriginPatterns)) { return null; } PropertyMapper map = PropertyMapper.get(); CorsConfiguration configuration = new CorsConfiguration(); map.from(this::getAllowedOrigins).to(configuration::setAllowedOrigins); map.from(this::getAllowedOriginPatterns).to(configuration::setAllowedOriginPatterns); map.from(this::getAllowedHeaders).whenNot(CollectionUtils::isEmpty).to(configuration::setAllowedHeaders); map.from(this::getAllowedMethods).whenNot(CollectionUtils::isEmpty).to(configuration::setAllowedMethods); map.from(this::getExposedHeaders).whenNot(CollectionUtils::isEmpty).to(configuration::setExposedHeaders); map.from(this::getMaxAge).as(Duration::getSeconds).to(configuration::setMaxAge); map.from(this::getAllowCredentials).to(configuration::setAllowCredentials); return configuration; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\web\CorsEndpointProperties.java
2
请完成以下Java代码
public Origin getOrigin(String name) { return Origin.from(findConfigurationProperty(name)); } private ConfigurationProperty findConfigurationProperty(String name) { try { return findConfigurationProperty(ConfigurationPropertyName.of(name)); } catch (InvalidConfigurationPropertyNameException ex) { // simulate non-exposed version of ConfigurationPropertyName.of(name, nullIfInvalid) if(ex.getInvalidCharacters().size() == 1 && ex.getInvalidCharacters().get(0).equals('.')) { return null; } throw ex; } }
private ConfigurationProperty findConfigurationProperty(ConfigurationPropertyName name) { if (name == null) { return null; } for (ConfigurationPropertySource configurationPropertySource : getSource()) { if (!configurationPropertySource.getUnderlyingSource().getClass().equals(EncryptableConfigurationPropertySourcesPropertySource.class)) { ConfigurationProperty configurationProperty = configurationPropertySource.getConfigurationProperty(name); if (configurationProperty != null) { return configurationProperty; } } } return null; } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\wrapper\EncryptableConfigurationPropertySourcesPropertySource.java
1
请完成以下Java代码
public String getCamundaEvent() { return camundaEventAttribute.getValue(this); } public void setCamundaEvent(String camundaEvent) { camundaEventAttribute.setValue(this, camundaEvent); } public String getCamundaClass() { return camundaClassAttribute.getValue(this); } public void setCamundaClass(String camundaClass) { camundaClassAttribute.setValue(this, camundaClass); } public String getCamundaExpression() { return camundaExpressionAttribute.getValue(this); } public void setCamundaExpression(String camundaExpression) { camundaExpressionAttribute.setValue(this, camundaExpression); }
public String getCamundaDelegateExpression() { return camundaDelegateExpressionAttribute.getValue(this); } public void setCamundaDelegateExpression(String camundaDelegateExpression) { camundaDelegateExpressionAttribute.setValue(this, camundaDelegateExpression); } public Collection<CamundaField> getCamundaFields() { return camundaFieldCollection.get(this); } public CamundaScript getCamundaScript() { return camundaScriptChild.getChild(this); } public void setCamundaScript(CamundaScript camundaScript) { camundaScriptChild.setChild(this, camundaScript); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaExecutionListenerImpl.java
1
请完成以下Java代码
public String toString() { StringBuilder strb; if (isProcessInstanceType()) { strb = new StringBuilder("ProcessInstance[" + getId() + "] - definition '" + getProcessDefinitionId() + "'"); } else { strb = new StringBuilder(); if (isScope) { strb.append("Scoped execution[ id '").append(getId()); } else if (isMultiInstanceRoot) { strb.append("Multi instance root execution[ id '").append(getId()); } else { strb.append("Execution[ id '").append(getId()); } strb.append("' ]"); strb.append(" - definition '").append(getProcessDefinitionId()).append("'"); if (activityId != null) { strb.append(" - activity '").append(activityId).append("'");
} if (parentId != null) { strb.append(" - parent '").append(parentId).append("'"); } } if (StringUtils.isNotEmpty(tenantId)) { strb.append(" - tenantId '").append(tenantId).append("'"); } return strb.toString(); } @Override protected VariableServiceConfiguration getVariableServiceConfiguration() { return CommandContextUtil.getProcessEngineConfiguration().getVariableServiceConfiguration(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ExecutionEntityImpl.java
1
请完成以下Java代码
public int getEXP_Processor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Processor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Processor Parameter. @param EXP_ProcessorParameter_ID Processor Parameter */ public void setEXP_ProcessorParameter_ID (int EXP_ProcessorParameter_ID) { if (EXP_ProcessorParameter_ID < 1) set_ValueNoCheck (COLUMNNAME_EXP_ProcessorParameter_ID, null); else set_ValueNoCheck (COLUMNNAME_EXP_ProcessorParameter_ID, Integer.valueOf(EXP_ProcessorParameter_ID)); } /** Get Processor Parameter. @return Processor Parameter */ public int getEXP_ProcessorParameter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EXP_ProcessorParameter_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name
Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Parameter Value. @param ParameterValue Parameter Value */ public void setParameterValue (String ParameterValue) { set_Value (COLUMNNAME_ParameterValue, ParameterValue); } /** Get Parameter Value. @return Parameter Value */ public String getParameterValue () { return (String)get_Value(COLUMNNAME_ParameterValue); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_ProcessorParameter.java
1
请完成以下Java代码
protected DecisionDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { return getDecisionDefinitionManager().findDecisionDefinitionByDeploymentAndKey(deploymentId, definitionKey); } @Override protected DecisionDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) { return getDecisionDefinitionManager().findLatestDecisionDefinitionByKeyAndTenantId(definitionKey, tenantId); } @Override protected void persistDefinition(DecisionDefinitionEntity definition) { getDecisionDefinitionManager().insertDecisionDefinition(definition); } @Override protected void addDefinitionToDeploymentCache(DeploymentCache deploymentCache, DecisionDefinitionEntity definition) { deploymentCache.addDecisionDefinition(definition); }
// context /////////////////////////////////////////////////////////////////////////////////////////// protected DecisionDefinitionManager getDecisionDefinitionManager() { return getCommandContext().getDecisionDefinitionManager(); } // getters/setters /////////////////////////////////////////////////////////////////////////////////// public DmnTransformer getTransformer() { return transformer; } public void setTransformer(DmnTransformer transformer) { this.transformer = transformer; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\deployer\DecisionDefinitionDeployer.java
1
请完成以下Java代码
public String getSentryRef() { return sentryRef; } public void setSentryRef(String sentryRef) { this.sentryRef = sentryRef; } public Sentry getSentry() { return sentry; } public void setSentry(Sentry sentry) { this.sentry = sentry; } public String getAttachedToRefId() { return attachedToRefId; } public void setAttachedToRefId(String attachedToRefId) { this.attachedToRefId = attachedToRefId; } public boolean isEntryCriterion() { return isEntryCriterion; } public void setEntryCriterion(boolean isEntryCriterion) { this.isEntryCriterion = isEntryCriterion; } public boolean isExitCriterion() { return isExitCriterion; } public void setExitCriterion(boolean isExitCriterion) { this.isExitCriterion = isExitCriterion; } public String getExitType() { return exitType; } public void setExitType(String exitType) { this.exitType = exitType; } public String getExitEventType() { return exitEventType; } public void setExitEventType(String exitEventType) { this.exitEventType = exitEventType; } @Override public void addIncomingAssociation(Association association) { this.incomingAssociations.add(association); } @Override public List<Association> getIncomingAssociations() { return incomingAssociations; } @Override public void setIncomingAssociations(List<Association> incomingAssociations) { this.incomingAssociations = incomingAssociations;
} @Override public void addOutgoingAssociation(Association association) { this.outgoingAssociations.add(association); } @Override public List<Association> getOutgoingAssociations() { return outgoingAssociations; } @Override public void setOutgoingAssociations(List<Association> outgoingAssociations) { this.outgoingAssociations = outgoingAssociations; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); if (isEntryCriterion) { stringBuilder.append("Entry criterion"); } else { stringBuilder.append("Exit criterion"); } stringBuilder.append(" with id '").append(id).append("'"); return stringBuilder.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Criterion.java
1
请完成以下Java代码
public boolean isAddressSpecifiedByExistingLocationIdOnly() { return toAddress().isOnlyExistingLocationIdSet(); } public void addHandle(@NonNull final String handle) { handles.add(handle); } public boolean containsHandle(@NonNull final String handle) { return handles.contains(handle); } public BPartnerLocationAddressPart toAddress() { return BPartnerLocationAddressPart.builder() .existingLocationId(getExistingLocationId()) .address1(getAddress1()) .address2(getAddress2()) .address3(getAddress3()) .address4(getAddress4()) .poBox(getPoBox()) .postal(getPostal()) .city(getCity()) .region(getRegion()) .district(getDistrict()) .countryCode(getCountryCode()) .build(); } public void setFromAddress(@NonNull final BPartnerLocationAddressPart address) { setExistingLocationId(address.getExistingLocationId()); setAddress1(address.getAddress1());
setAddress2(address.getAddress2()); setAddress3(address.getAddress3()); setAddress4(address.getAddress4()); setCity(address.getCity()); setCountryCode(address.getCountryCode()); setPoBox(address.getPoBox()); setPostal(address.getPostal()); setRegion(address.getRegion()); setDistrict(address.getDistrict()); } @Nullable public LocationId getExistingLocationIdNotNull() { return Check.assumeNotNull(getExistingLocationId(), "existingLocationId not null: {}", this); } /** * Can be used if this instance's ID is known to be not null. */ @NonNull public BPartnerLocationId getIdNotNull() { return Check.assumeNotNull(id, "id may not be null at this point"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerLocation.java
1
请完成以下Java代码
public boolean hasLimitedInstanceCount() { return maxInstanceCount != null && maxInstanceCount > 0; } public Integer getMaxInstanceCount() { return maxInstanceCount; } public void setMaxInstanceCount(Integer maxInstanceCount) { this.maxInstanceCount = maxInstanceCount; } public VariableAggregationDefinitions getAggregations() { return aggregations; } public void setAggregations(VariableAggregationDefinitions aggregations) { this.aggregations = aggregations; } public void addAggregation(VariableAggregationDefinition aggregation) {
if (this.aggregations == null) { this.aggregations = new VariableAggregationDefinitions(); } this.aggregations.getAggregations().add(aggregation); } @Override public String toString() { return "RepetitionRule{" + " maxInstanceCount='" + (hasLimitedInstanceCount() ? maxInstanceCount : "unlimited") + "'" + " repetitionCounterVariableName='" + repetitionCounterVariableName + "'" + " collectionVariableName='" + collectionVariableName + "'" + " elementVariableName='" + elementVariableName + "'" + " elementIndexVariableName='" + elementIndexVariableName + "'" + " } " + super.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\RepetitionRule.java
1
请完成以下Java代码
public boolean isReceipt(@NonNull final I_PP_Order_Qty ppOrderQty) { return ppOrderQty.getPP_Order_BOMLine_ID() <= 0; } @Override public void updateDraftReceiptCandidate(@NonNull UpdateDraftReceiptCandidateRequest request) { final PPOrderId pickingOrderId = request.getPickingOrderId(); final HuId huId = request.getHuID(); final Quantity qtyToUpdate = request.getQtyReceived(); huPPOrderQtyDAO.retrieveOrderQtyForHu(pickingOrderId, huId) .filter(candidate -> !candidate.isProcessed() && isReceipt(candidate)) .ifPresent(candidate -> { I_M_HU hu = candidate.getM_HU(); candidate.setQty(qtyToUpdate.toBigDecimal()); huPPOrderQtyDAO.save(candidate); });
} @Override public Set<HuId> getFinishedGoodsReceivedHUIds(@NonNull final PPOrderId ppOrderId) { final HashSet<HuId> receivedHUIds = new HashSet<>(); huPPOrderQtyDAO.retrieveOrderQtyForFinishedGoodsReceive(ppOrderId) .stream() .filter(I_PP_Order_Qty::isProcessed) .forEach(processedCandidate -> { final HuId huId = HuId.ofRepoId(processedCandidate.getM_HU_ID()); receivedHUIds.add(huId); final I_M_HU parentHU = handlingUnitsBL.getTopLevelParent(huId); receivedHUIds.add(HuId.ofRepoId(parentHU.getM_HU_ID())); }); return receivedHUIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\HUPPOrderQtyBL.java
1
请完成以下Java代码
public IssueCountersByCategory getIssueCountersByCategory( @NonNull final TableRecordReference recordRef, final boolean onlyNotAcknowledged) { final ArrayList<Object> sqlParams = new ArrayList<>(); final StringBuilder sql = new StringBuilder("SELECT " + " " + I_AD_Issue.COLUMNNAME_IssueCategory + ", count(1) as count" + "\n FROM " + I_AD_Issue.Table_Name + "\n WHERE " + " " + I_AD_Issue.COLUMNNAME_IsActive + "=?" + " AND " + I_AD_Issue.COLUMNNAME_AD_Table_ID + "=?" + " AND " + I_AD_Issue.COLUMNNAME_Record_ID + "=?"); sqlParams.add(true); // IsActive sqlParams.add(recordRef.getAD_Table_ID()); sqlParams.add(recordRef.getRecord_ID()); if (onlyNotAcknowledged) { sql.append(" AND ").append(I_AD_Issue.COLUMNNAME_Processed).append("=?"); sqlParams.add(false); } sql.append("\n GROUP BY ").append(I_AD_Issue.COLUMNNAME_IssueCategory); PreparedStatement pstmt = null; ResultSet rs = null; try {
pstmt = DB.prepareStatement(sql.toString(), ITrx.TRXNAME_None); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); final HashMap<IssueCategory, Integer> counters = new HashMap<>(); while (rs.next()) { final IssueCategory issueCategory = IssueCategory.ofNullableCodeOrOther(rs.getString(I_AD_Issue.COLUMNNAME_IssueCategory)); final int count = rs.getInt("count"); counters.compute(issueCategory, (k, previousCounter) -> { return previousCounter != null ? previousCounter + count : count; }); } return IssueCountersByCategory.of(counters); } catch (final SQLException ex) { throw new DBException(ex, sql, sqlParams); } finally { DB.close(rs, pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\error\impl\ErrorManager.java
1
请完成以下Java代码
default ITranslatableString getTranslatableMsgText(@NonNull final String adMessage, @Nullable final Object... msgParameters) { return getTranslatableMsgText(AdMessageKey.of(adMessage), msgParameters); } default ITranslatableString getTranslatableMsgText(final AdMessageKey adMessage, final List<Object> msgParameters) { final Object[] msgParametersArr = msgParameters != null ? msgParameters.toArray() : new Object[] {}; return getTranslatableMsgText(adMessage, msgParametersArr); } @Deprecated default ITranslatableString getTranslatableMsgText(final String adMessage, final List<Object> msgParameters) { return getTranslatableMsgText(AdMessageKey.of(adMessage), msgParameters); } default ITranslatableString getTranslatableMsgText(final boolean booleanValue) { return getTranslatableMsgText(booleanValue ? MSG_Yes : MSG_No); } /** * Gets AD_Language/message map * * @param adLanguage language key * @param prefix prefix used to match the AD_Messages (keys) * @param removePrefix if true, the prefix will be cut out from the AD_Message keys that will be returned * @return a map of "AD_Message" (might be with the prefix removed) to "translated message" pairs */
Map<String, String> getMsgMap(String adLanguage, String prefix, boolean removePrefix); void cacheReset(); default AdMessagesTreeLoader.Builder messagesTree() { return AdMessagesTreeLoader.builder() .msgBL(this); } String getBaseLanguageMsg(@NonNull AdMessageKey adMessage, @Nullable Object... msgParameters); Optional<AdMessageId> getIdByAdMessage(@NonNull AdMessageKey value); boolean isMessageExists(AdMessageKey adMessage); Optional<AdMessageKey> getAdMessageKeyById(AdMessageId adMessageId); @Nullable String getErrorCode(@NonNull final AdMessageKey messageKey); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\IMsgBL.java
1
请在Spring Boot框架中完成以下Java代码
public FailedTimeBookingId save(@NonNull final FailedTimeBooking failedTimeBooking) { final Supplier<FailedTimeBookingId> failedIdByExternalIdAndSystemSupplier = () -> getOptionalByExternalIdAndSystem(failedTimeBooking.getExternalSystem(), failedTimeBooking.getExternalId()) .map(FailedTimeBooking::getFailedTimeBookingId) .orElse(null); final FailedTimeBookingId failedTimeBookingId = CoalesceUtil.coalesceSuppliers( failedTimeBooking::getFailedTimeBookingId, failedIdByExternalIdAndSystemSupplier); final I_S_FailedTimeBooking record = InterfaceWrapperHelper.loadOrNew(failedTimeBookingId, I_S_FailedTimeBooking.class); record.setExternalId(failedTimeBooking.getExternalId()); record.setExternalSystem_ID(failedTimeBooking.getExternalSystem().getId().getRepoId()); record.setJSONValue(failedTimeBooking.getJsonValue()); record.setImportErrorMsg(failedTimeBooking.getErrorMsg()); InterfaceWrapperHelper.saveRecord(record); return FailedTimeBookingId.ofRepoId(record.getS_FailedTimeBooking_ID()); } public void delete(@NonNull final FailedTimeBookingId failedTimeBookingId) { final I_S_FailedTimeBooking record = InterfaceWrapperHelper.load(failedTimeBookingId, I_S_FailedTimeBooking.class); InterfaceWrapperHelper.delete(record); } public Optional<FailedTimeBooking> getOptionalByExternalIdAndSystem(@NonNull final ExternalSystem externalSystem, @NonNull final String externalId) { return queryBL.createQueryBuilder(I_S_FailedTimeBooking.class) .addEqualsFilter(I_S_FailedTimeBooking.COLUMNNAME_ExternalSystem_ID, externalSystem.getId() ) .addEqualsFilter(I_S_FailedTimeBooking.COLUMNNAME_ExternalId, externalId) .create() .firstOnlyOptional(I_S_FailedTimeBooking.class) .map(this::buildFailedTimeBooking); } public ImmutableList<FailedTimeBooking> listBySystem(@NonNull final ExternalSystem externalSystem) { return queryBL.createQueryBuilder(I_S_FailedTimeBooking.class) .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_S_FailedTimeBooking.COLUMNNAME_ExternalSystem_ID, externalSystem.getId() ) .create() .list() .stream() .map(this::buildFailedTimeBooking) .collect(ImmutableList.toImmutableList()); } private FailedTimeBooking buildFailedTimeBooking(@NonNull final I_S_FailedTimeBooking record) { final ExternalSystem externalSystem = externalSystemRepository.getById(ExternalSystemId.ofRepoId(record.getExternalSystem_ID())); return FailedTimeBooking.builder() .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .failedTimeBookingId(FailedTimeBookingId.ofRepoId(record.getS_FailedTimeBooking_ID())) .externalId(record.getExternalId()) .externalSystem(externalSystem) .jsonValue(record.getJSONValue()) .errorMsg(record.getImportErrorMsg()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\importer\failed\FailedTimeBookingRepository.java
2
请完成以下Java代码
public void setIsPermissionGranted (boolean IsPermissionGranted) { set_ValueNoCheck (COLUMNNAME_IsPermissionGranted, Boolean.valueOf(IsPermissionGranted)); } /** Get Permission Granted. @return Permission Granted */ public boolean isPermissionGranted () { Object oo = get_Value(COLUMNNAME_IsPermissionGranted); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Read Write. @param IsReadWrite Field is read / write */ public void setIsReadWrite (boolean IsReadWrite) { set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite)); } /** Get Read Write. @return Field is read / write */ public boolean isReadWrite () { Object oo = get_Value(COLUMNNAME_IsReadWrite); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Revoke. @param RevokePermission Revoke Permission */ public void setRevokePermission (String RevokePermission) { set_Value (COLUMNNAME_RevokePermission, RevokePermission); } /** Get Revoke. @return Revoke Permission */ public String getRevokePermission () { return (String)get_Value(COLUMNNAME_RevokePermission); } @Override public void setDescription(String Description) { set_ValueNoCheck (COLUMNNAME_Description, Description); } @Override public String getDescription() { return (String)get_Value(COLUMNNAME_Description); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_PermRequest.java
1
请完成以下Java代码
public void setMSV3_BestellungAntwort_ID (int MSV3_BestellungAntwort_ID) { if (MSV3_BestellungAntwort_ID < 1) set_Value (COLUMNNAME_MSV3_BestellungAntwort_ID, null); else set_Value (COLUMNNAME_MSV3_BestellungAntwort_ID, Integer.valueOf(MSV3_BestellungAntwort_ID)); } /** Get MSV3_BestellungAntwort. @return MSV3_BestellungAntwort */ @Override public int getMSV3_BestellungAntwort_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAntwort_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_FaultInfo getMSV3_FaultInfo() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MSV3_FaultInfo_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_FaultInfo.class); } @Override public void setMSV3_FaultInfo(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_FaultInfo MSV3_FaultInfo) { set_ValueFromPO(COLUMNNAME_MSV3_FaultInfo_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_FaultInfo.class, MSV3_FaultInfo); } /** Set MSV3_FaultInfo. @param MSV3_FaultInfo_ID MSV3_FaultInfo */ @Override public void setMSV3_FaultInfo_ID (int MSV3_FaultInfo_ID) {
if (MSV3_FaultInfo_ID < 1) set_Value (COLUMNNAME_MSV3_FaultInfo_ID, null); else set_Value (COLUMNNAME_MSV3_FaultInfo_ID, Integer.valueOf(MSV3_FaultInfo_ID)); } /** Get MSV3_FaultInfo. @return MSV3_FaultInfo */ @Override public int getMSV3_FaultInfo_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_FaultInfo_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Bestellung_Transaction.java
1
请完成以下Spring Boot application配置
## 是否显示 SQL 语句 spring.jpa.show-sql=true ## DATA WEB 相关配置 {@link SpringDataWebProperties} ## 分页大小 默认为 20 spring.data.web.pageable.default-page-size=3 ## 当前页参数名 默认为 page spring.data.web.pageable.page-parameter=pageNumber ## 当前页参数名 默认为 size spring
.data.web.pageable.size-parameter=pageSize ## 字段排序参数名 默认为 sort spring.data.web.sort.sort-parameter=orderBy
repos\springboot-learning-example-master\chapter-5-spring-boot-paging-sorting\src\main\resources\application.properties
2
请完成以下Java代码
public static List<SizeUnitBinaryPrefixes> unitsInDescending() { List<SizeUnitBinaryPrefixes> list = Arrays.asList(values()); Collections.reverse(list); return list; } public Long getUnitBase() { return unitBase; } SizeUnitBinaryPrefixes(long unitBase) { this.unitBase = unitBase; } } enum SizeUnitSIPrefixes { Bytes(1L), KB(Bytes.unitBase * 1000), MB(KB.unitBase * 1000), GB(MB.unitBase * 1000), TB(GB.unitBase * 1000), PB(TB.unitBase * 1000), EB(PB.unitBase * 1000); private final Long unitBase;
public static List<SizeUnitSIPrefixes> unitsInDescending() { List<SizeUnitSIPrefixes> list = Arrays.asList(values()); Collections.reverse(list); return list; } public Long getUnitBase() { return unitBase; } SizeUnitSIPrefixes(long unitBase) { this.unitBase = unitBase; } } }
repos\tutorials-master\core-java-modules\core-java-numbers-4\src\main\java\com\baeldung\humanreadablebytes\FileSizeFormatUtil.java
1
请完成以下Java代码
protected Class<MobileAppBundleEntity> getEntityClass() { return MobileAppBundleEntity.class; } @Override protected JpaRepository<MobileAppBundleEntity, UUID> getRepository() { return mobileAppBundleRepository; } @Override public PageData<MobileAppBundleInfo> findInfosByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(mobileAppBundleRepository.findInfoByTenantId(tenantId.getId(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public MobileAppBundleInfo findInfoById(TenantId tenantId, MobileAppBundleId mobileAppBundleId) { return DaoUtil.getData(mobileAppBundleRepository.findInfoById(mobileAppBundleId.getId())); } @Override public List<MobileAppBundleOauth2Client> findOauth2ClientsByMobileAppBundleId(TenantId tenantId, MobileAppBundleId mobileAppBundleId) { return DaoUtil.convertDataList(mobileOauth2ProviderRepository.findAllByMobileAppBundleId(mobileAppBundleId.getId())); } @Override public void addOauth2Client(TenantId tenantId, MobileAppBundleOauth2Client mobileAppBundleOauth2Client) { mobileOauth2ProviderRepository.save(new MobileAppBundleOauth2ClientEntity(mobileAppBundleOauth2Client)); } @Override public void removeOauth2Client(TenantId tenantId, MobileAppBundleOauth2Client mobileAppBundleOauth2Client) { mobileOauth2ProviderRepository.deleteById(new MobileAppOauth2ClientCompositeKey(mobileAppBundleOauth2Client.getMobileAppBundleId().getId(),
mobileAppBundleOauth2Client.getOAuth2ClientId().getId())); } @Override public MobileAppBundle findByPkgNameAndPlatform(TenantId tenantId, String pkgName, PlatformType platform) { return DaoUtil.getData(mobileAppBundleRepository.findByPkgNameAndPlatformType(pkgName, platform)); } @Override public void deleteByTenantId(TenantId tenantId) { mobileAppBundleRepository.deleteByTenantId(tenantId.getId()); } @Override public EntityType getEntityType() { return EntityType.MOBILE_APP_BUNDLE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\mobile\JpaMobileAppBundleDao.java
1
请完成以下Java代码
protected void applyFilters(HistoricActivityStatisticsQuery query) { if (includeCanceled != null && includeCanceled) { query.includeCanceled(); } if (includeFinished != null && includeFinished) { query.includeFinished(); } if (includeCompleteScope != null && includeCompleteScope) { query.includeCompleteScope(); } if (includeIncidents !=null && includeIncidents) { query.includeIncidents(); } if (startedAfter != null) { query.startedAfter(startedAfter); } if (startedBefore != null) { query.startedBefore(startedBefore); }
if (finishedAfter != null) { query.finishedAfter(finishedAfter); } if (finishedBefore != null) { query.finishedBefore(finishedBefore); } if (processInstanceIdIn != null) { query.processInstanceIdIn(processInstanceIdIn); } } @Override protected void applySortBy(HistoricActivityStatisticsQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (SORT_ORDER_ACTIVITY_ID.equals(sortBy)) { query.orderByActivityId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricActivityStatisticsQueryDto.java
1
请完成以下Java代码
public static <E> List<E> convertToList(Set<E> set) { return new ArrayList<>(set); } public static <E> int getIndexByConversion(Set<E> set, E element) { List<E> list = new ArrayList<>(set); return list.indexOf(element); } public static <E> E getElementByIndex(Set<E> set, int index) { List<E> list = new ArrayList<>(set); if (index >= 0 && index < list.size()) { return list.get(index); } throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + list.size()); }
@SuppressWarnings("unchecked") public static <E> E[] convertToArray(Set<E> set, Class<E> clazz) { return set.toArray((E[]) java.lang.reflect.Array.newInstance(clazz, set.size())); } public static <E> int getIndexByArray(Set<E> set, E element, Class<E> clazz) { E[] array = convertToArray(set, clazz); for (int i = 0; i < array.length; i++) { if (array[i].equals(element)) { return i; } } return -1; } }
repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\linkedhashsetindexof\LinkedHashSetWithConversion.java
1
请完成以下Java代码
public class OAuth2AuthorizationCodeReactiveAuthenticationManager implements ReactiveAuthenticationManager { private static final String INVALID_STATE_PARAMETER_ERROR_CODE = "invalid_state_parameter"; private final ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient; public OAuth2AuthorizationCodeReactiveAuthenticationManager( ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient) { Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null"); this.accessTokenResponseClient = accessTokenResponseClient; } @Override public Mono<Authentication> authenticate(Authentication authentication) { return Mono.defer(() -> { OAuth2AuthorizationCodeAuthenticationToken token = (OAuth2AuthorizationCodeAuthenticationToken) authentication; OAuth2AuthorizationResponse authorizationResponse = token.getAuthorizationExchange() .getAuthorizationResponse(); if (authorizationResponse.statusError()) { return Mono.error(new OAuth2AuthorizationException(authorizationResponse.getError())); } OAuth2AuthorizationRequest authorizationRequest = token.getAuthorizationExchange() .getAuthorizationRequest(); if (!authorizationResponse.getState().equals(authorizationRequest.getState())) { OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
return Mono.error(new OAuth2AuthorizationException(oauth2Error)); } OAuth2AuthorizationCodeGrantRequest authzRequest = new OAuth2AuthorizationCodeGrantRequest( token.getClientRegistration(), token.getAuthorizationExchange()); return this.accessTokenResponseClient.getTokenResponse(authzRequest).map(onSuccess(token)); }); } private Function<OAuth2AccessTokenResponse, OAuth2AuthorizationCodeAuthenticationToken> onSuccess( OAuth2AuthorizationCodeAuthenticationToken token) { return (accessTokenResponse) -> { ClientRegistration registration = token.getClientRegistration(); OAuth2AuthorizationExchange exchange = token.getAuthorizationExchange(); OAuth2AccessToken accessToken = accessTokenResponse.getAccessToken(); OAuth2RefreshToken refreshToken = accessTokenResponse.getRefreshToken(); return new OAuth2AuthorizationCodeAuthenticationToken(registration, exchange, accessToken, refreshToken, accessTokenResponse.getAdditionalParameters()); }; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\authentication\OAuth2AuthorizationCodeReactiveAuthenticationManager.java
1
请在Spring Boot框架中完成以下Java代码
public class AcctSchema { @NonNull AcctSchemaId id; @NonNull ClientId clientId; @NonNull OrgId orgId; @NonNull String name; @NonNull CurrencyId currencyId; @NonNull CurrencyPrecision standardPrecision; @NonNull AcctSchemaCosting costing; @NonNull AcctSchemaValidCombinationOptions validCombinationOptions; @NonNull TaxCorrectionType taxCorrectionType; @NonNull @Default ImmutableSet<OrgId> postOnlyForOrgIds = ImmutableSet.of(); boolean accrual; boolean allowNegativePosting; boolean postTradeDiscount; boolean postServices; boolean postIfSameClearingAccounts; boolean isAllowMultiDebitAndCredit; boolean isAutoSetDebtoridAndCreditorid; int debtorIdPrefix; int creditorIdPrefix; @NonNull AcctSchemaGeneralLedger generalLedger; @NonNull AcctSchemaDefaultAccounts defaultAccounts; @NonNull AcctSchemaPeriodControl periodControl; @NonNull AcctSchemaElementsMap schemaElements; public boolean isPostOnlyForSomeOrgs() { return !postOnlyForOrgIds.isEmpty(); } public boolean isAllowPostingForOrg(@NonNull final OrgId orgId) { if (postOnlyForOrgIds.isEmpty()) { return true; } else { return postOnlyForOrgIds.contains(orgId); } }
public boolean isDisallowPostingForOrg(@NonNull final OrgId orgId) { return !isAllowPostingForOrg(orgId); } public boolean isElementEnabled(@NonNull final AcctSchemaElementType elementType) { return getSchemaElements().isElementEnabled(elementType); } public AcctSchemaElement getSchemaElementByType(@NonNull final AcctSchemaElementType elementType) { return getSchemaElements().getByElementType(elementType); } public ImmutableSet<AcctSchemaElementType> getSchemaElementTypes() { return getSchemaElements().getElementTypes(); } public ChartOfAccountsId getChartOfAccountsId() { return getSchemaElements().getChartOfAccountsId(); } public boolean isAccountingCurrency(@NonNull final CurrencyId currencyId) { return CurrencyId.equals(this.currencyId, currencyId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AcctSchema.java
2
请在Spring Boot框架中完成以下Java代码
public static ObjectMapper jsonObjectMapper() { // important to register the jackson-datatype-jsr310 module which we have in our pom and // which is needed to serialize/deserialize java.time.Instant //noinspection ConstantConditions assert com.fasterxml.jackson.datatype.jsr310.JavaTimeModule.class != null; // just to get a compile error if not present return new ObjectMapper() .findAndRegisterModules() .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) .enable(MapperFeature.USE_ANNOTATIONS); } /** * @return default task executor used by {@link Async} calls */ @Bean("asyncCallsTaskExecutor")
public TaskExecutor asyncCallsTaskExecutor() { final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(1); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); return executor; } @Bean public Docket docket() { return new Docket(DocumentationType.OAS_30) .select() .paths(PathSelectors.any()) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\Application.java
2
请在Spring Boot框架中完成以下Java代码
public Order toOrder() { List<OrderItem> orderItems = orderItemEntities.stream() .map(OrderItemEntity::toOrderItem) .collect(Collectors.toList()); List<Product> namelessProducts = orderItems.stream() .map(orderItem -> new Product(orderItem.getProductId(), orderItem.getPrice(), "")) .collect(Collectors.toList()); Order order = new Order(id, namelessProducts.remove(0)); namelessProducts.forEach(product -> order.addOrder(product)); if (status == OrderStatus.COMPLETED) { order.complete(); } return order; } public UUID getId() {
return id; } public OrderStatus getStatus() { return status; } public List<OrderItemEntity> getOrderItems() { return orderItemEntities; } public BigDecimal getPrice() { return price; } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddhexagonalspring\infrastracture\repository\cassandra\OrderEntity.java
2
请在Spring Boot框架中完成以下Java代码
public CmmnDeploymentBuilder addCmmnBytes(String resourceName, byte[] cmmnBytes) { if (cmmnBytes == null) { throw new FlowableException("cmmn bytes is null"); } CmmnResourceEntity resource = resourceEntityManager.create(); resource.setName(resourceName); resource.setBytes(cmmnBytes); deployment.addResource(resource); return this; } public CmmnDeploymentBuilder addCmmnModel(String resourceName, CmmnModel cmmnModel) { // TODO return null; } @Override public CmmnDeploymentBuilder name(String name) { deployment.setName(name); return this; } @Override public CmmnDeploymentBuilder category(String category) { deployment.setCategory(category); return this; } @Override public CmmnDeploymentBuilder key(String key) { deployment.setKey(key); return this; } @Override public CmmnDeploymentBuilder disableSchemaValidation() { this.isCmmn20XsdValidationEnabled = false; return this; } @Override public CmmnDeploymentBuilder tenantId(String tenantId) { deployment.setTenantId(tenantId); return this; } @Override public CmmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) { deployment.setParentDeploymentId(parentDeploymentId); return this;
} @Override public CmmnDeploymentBuilder enableDuplicateFiltering() { this.isDuplicateFilterEnabled = true; return this; } @Override public CmmnDeployment deploy() { return repositoryService.deploy(this); } public CmmnDeploymentEntity getDeployment() { return deployment; } public boolean isCmmnXsdValidationEnabled() { return isCmmn20XsdValidationEnabled; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CmmnDeploymentBuilderImpl.java
2
请完成以下Java代码
public void setDateInvoiced (java.sql.Timestamp DateInvoiced) { set_ValueNoCheck (COLUMNNAME_DateInvoiced, DateInvoiced); } /** Get Rechnungsdatum. @return Datum auf der Rechnung */ @Override public java.sql.Timestamp getDateInvoiced () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DateInvoiced); } /** Set Sales Transaction. @param IsSOTrx This is a Sales Transaction */ @Override public void setIsSOTrx (boolean IsSOTrx) { set_ValueNoCheck (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ @Override public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */
@Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Einzelpreis. @param PriceActual Effektiver Preis */ @Override public void setPriceActual (java.math.BigDecimal PriceActual) { set_ValueNoCheck (COLUMNNAME_PriceActual, PriceActual); } /** Get Einzelpreis. @return Effektiver Preis */ @Override public java.math.BigDecimal getPriceActual () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product_Stats_Invoice_Online_V.java
1
请完成以下Java代码
public Object invoke(InvocationContext ctx) throws Exception { try { Object result = ctx.proceed(); StartProcess startProcessAnnotation = ctx.getMethod().getAnnotation(StartProcess.class); String key = startProcessAnnotation.value(); Map<String, Object> variables = extractVariables(startProcessAnnotation, ctx); businessProcess.startProcessByKey(key, variables); return result; } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if(cause != null && cause instanceof Exception) { throw (Exception) cause; } else { throw e; } } catch (Exception e) { throw new ProcessEngineException("Error while starting process using @StartProcess on method '"+ctx.getMethod()+"': " + e.getMessage(), e); } } private Map<String, Object> extractVariables(StartProcess startProcessAnnotation, InvocationContext ctx) throws Exception { VariableMap variables = new VariableMapImpl(); for (Field field : ctx.getMethod().getDeclaringClass().getDeclaredFields()) { if (!field.isAnnotationPresent(ProcessVariable.class) && !field.isAnnotationPresent(ProcessVariableTyped.class)) {
continue; } field.setAccessible(true); String fieldName = null; ProcessVariable processStartVariable = field.getAnnotation(ProcessVariable.class); if (processStartVariable != null) { fieldName = processStartVariable.value(); } else { ProcessVariableTyped processStartVariableTyped = field.getAnnotation(ProcessVariableTyped.class); fieldName = processStartVariableTyped.value(); } if (fieldName == null || fieldName.length() == 0) { fieldName = field.getName(); } Object value = field.get(ctx.getTarget()); variables.put(fieldName, value); } return variables; } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\annotation\StartProcessInterceptor.java
1
请完成以下Java代码
public int getC_UOM_ID() { return shipmentSchedule.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { // we assume inoutLine's UOM is correct if (uomId > 0) { shipmentSchedule.setC_UOM_ID(uomId); } } @Override public void setQty(final BigDecimal qty) { shipmentSchedule.setQtyOrdered_Override(qty); } @Override public BigDecimal getQty() { // task 09005: make sure the correct qtyOrdered is taken from the shipmentSchedule final BigDecimal qtyOrdered = Services.get(IShipmentScheduleEffectiveBL.class).computeQtyOrdered(shipmentSchedule); return qtyOrdered; } @Override public int getM_HU_PI_Item_Product_ID() { return shipmentSchedule.getM_HU_PI_Item_Product_ID(); } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public BigDecimal getQtyTU() { return shipmentSchedule.getQtyOrdered_TU(); }
@Override public void setQtyTU(final BigDecimal qtyPacks) { shipmentSchedule.setQtyOrdered_TU(qtyPacks); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ShipmentScheduleHUPackingAware.java
1
请在Spring Boot框架中完成以下Java代码
public class StallWhileMasterdataFilesExistPolicy extends RoutePolicySupport { @NonNull private final LocalFileConfig fileEndpointConfig; @NonNull private final PInstanceLogger pInstanceLogger; private final AtomicBoolean stopWaitLoop = new AtomicBoolean(false); @Override public void onExchangeBegin(@NonNull final Route route, @NonNull final Exchange exchange) { stopWaitLoop.set(false); boolean masterDataFileExists = checkForMasterDataFiles(exchange); while (masterDataFileExists && !stopWaitLoop.get()) { LockSupport.parkNanos(fileEndpointConfig.getPollingFrequency().toNanos()); masterDataFileExists = checkForMasterDataFiles(exchange); } } private boolean checkForMasterDataFiles(@NonNull final Exchange exchange) { final FileSystem fileSystem = FileSystems.getDefault(); final PathMatcher bpartnerFileMatcher = fileSystem.getPathMatcher("glob:" + fileEndpointConfig.getFileNamePatternBPartner()); final PathMatcher warehouseFileMatcher = fileSystem.getPathMatcher("glob:" + fileEndpointConfig.getFileNamePatternWarehouse()); final PathMatcher productFileMatcher = fileSystem.getPathMatcher("glob:" + fileEndpointConfig.getFileNamePatternProduct()); final Path rootLocation = Paths.get(fileEndpointConfig.getRootLocation()); final EnumSet<FileVisitOption> options = EnumSet.noneOf(FileVisitOption.class); final Path[] existingMasterDataFile = new Path[1]; final SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(@NonNull final Path currentFile, final BasicFileAttributes attrs) { if (bpartnerFileMatcher.matches(currentFile.getFileName())) { existingMasterDataFile[0] = currentFile; return FileVisitResult.TERMINATE; } if (warehouseFileMatcher.matches(currentFile.getFileName())) {
existingMasterDataFile[0] = currentFile; return FileVisitResult.TERMINATE; } if (productFileMatcher.matches(currentFile.getFileName())) { existingMasterDataFile[0] = currentFile; return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } }; try { Files.walkFileTree(rootLocation, options, 1, visitor); // maxDepth=1 means to check the folder and its included files } catch (final IOException e) { throw new RuntimeCamelException("Caught exception while checking for existing master data files", e); } final boolean atLEastOneFileFound = existingMasterDataFile[0] != null; if (atLEastOneFileFound) { final String fileName = exchange.getIn().getBody(GenericFile.class).getFileName(); pInstanceLogger.logMessage("There is at least the masterdata file " + existingMasterDataFile[0].getFileName() + " which has to be processed first => stall the processing of orders file " + fileName + " for now"); } return atLEastOneFileFound; } @Override protected void doStop() { stopWaitLoop.set(true); } }
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\purchaseorder\StallWhileMasterdataFilesExistPolicy.java
2
请完成以下Java代码
public PPOrderRoutingActivity getPreviousActivityOrNull(@NonNull final PPOrderRoutingActivity activity) { final ImmutableSet<PPOrderRoutingActivityCode> previousActivityCodes = getPreviousActivityCodes(activity); if (previousActivityCodes.isEmpty()) { return null; } final PPOrderRoutingActivityCode previousActivityCode = previousActivityCodes.iterator().next(); return getActivityByCode(previousActivityCode); } private ImmutableSet<PPOrderRoutingActivityCode> getNextActivityCodes(final PPOrderRoutingActivity activity) { return codeToNextCodeMap.get(activity.getCode()); } private ImmutableSet<PPOrderRoutingActivityCode> getPreviousActivityCodes(final PPOrderRoutingActivity activity) { final ImmutableSetMultimap<PPOrderRoutingActivityCode, PPOrderRoutingActivityCode> codeToPreviousCodeMap = codeToNextCodeMap.inverse(); return codeToPreviousCodeMap.get(activity.getCode()); } public PPOrderRoutingActivity getLastActivity() { return getActivities() .stream() .filter(this::isFinalActivity) .findFirst() .orElseThrow(() -> new AdempiereException("No final activity found in " + this)); } private boolean isFinalActivity(final PPOrderRoutingActivity activity) { return getNextActivityCodes(activity).isEmpty(); } public ImmutableSet<ProductId> getProductIdsByActivityId(@NonNull final PPOrderRoutingActivityId activityId) { return getProducts() .stream() .filter(activityProduct -> activityProduct.getId() != null && PPOrderRoutingActivityId.equals(activityProduct.getId().getActivityId(), activityId)) .map(PPOrderRoutingProduct::getProductId)
.collect(ImmutableSet.toImmutableSet()); } public void voidIt() { getActivities().forEach(PPOrderRoutingActivity::voidIt); } public void reportProgress(final PPOrderActivityProcessReport report) { getActivityById(report.getActivityId()).reportProgress(report); } public void completeActivity(final PPOrderRoutingActivityId activityId) { getActivityById(activityId).completeIt(); } public void closeActivity(final PPOrderRoutingActivityId activityId) { getActivityById(activityId).closeIt(); } public void uncloseActivity(final PPOrderRoutingActivityId activityId) { getActivityById(activityId).uncloseIt(); } @NonNull public RawMaterialsIssueStrategy getIssueStrategyForRawMaterialsActivity() { return activities.stream() .filter(activity -> activity.getType() == PPRoutingActivityType.RawMaterialsIssue) .findFirst() .map(PPOrderRoutingActivity::getRawMaterialsIssueStrategy) .orElse(RawMaterialsIssueStrategy.DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderRouting.java
1