instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
@Override protected String doIt() throws Exception { final I_DD_OrderLine ddOrderLine = ddOrderService.getLineById(DDOrderLineId.ofRepoId(getRecord_ID())); final IView husToMove = createHUEditor(ddOrderLine); getResult().setWebuiViewToOpen(ProcessExecutionResult.WebuiViewToOpen.builder() .viewId(husToMove.getViewId().getViewId()) .profileId(WINDOW_ID_STRING) .target(ProcessExecutionResult.ViewOpenTarget.ModalOverlay) .build()); return MSG_OK; } private IView createHUEditor(final I_DD_OrderLine orderLine) { final IHUQueryBuilder huQuery = createHUQuery(orderLine); final CreateViewRequest request = CreateViewRequest.builder(WINDOW_ID, JSONViewDataType.includedView) .addStickyFilters(HUIdsFilterHelper.createFilter(huQuery)) .setParentViewId(getView().getViewId())
.setParentRowId(getSelectedRowIds().getSingleDocumentId()) .build(); return viewsRepo.createView(request); } private IHUQueryBuilder createHUQuery(final I_DD_OrderLine orderLine) { return handlingUnitsDAO .createHUQueryBuilder() .onlyNotLocked() // not already locked (NOTE: those which were enqueued to Transportation Order are locked) .addOnlyInLocatorId(orderLine.getM_Locator_ID()) .addOnlyWithProductId(ProductId.ofRepoId(orderLine.getM_Product_ID())) .setOnlyActiveHUs(true) .addHUStatusToInclude(X_M_HU.HUSTATUS_Active); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\ddorder\process\WEBUI_MoveHUs_HUEditor_Launcher.java
1
请完成以下Java代码
protected TaskEntity validateAndGet(String taskId, CommandContext context) { TaskManager taskManager = context.getTaskManager(); TaskEntity task = taskManager.findTaskById(taskId); ensureNotNull(NotFoundException.class, "Cannot find task with id " + taskId, "task", task); checkTaskAgainstContext(task, context); return task; } /** * Perform multi-tenancy & authorization checks on the given task against the given command context. * * @param task the given task * @param context the given command context to check against */ protected void checkTaskAgainstContext(TaskEntity task, CommandContext context) { for (CommandChecker checker : context.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkTaskAssign(task); } } /** * Returns the User Operation Log name that corresponds to this command. Meant to be implemented by concretions. * * @return the user operation log name */
protected abstract String getUserOperationLogName(); /** * Executes the set operation of the concrete command. * * @param task the task entity on which to set a property * @param value the value to se */ protected abstract void executeSetOperation(TaskEntity task, T value); /** * Ensures the value is not null and returns the value. * * @param value the value * @param <T> the type of the value * @return the value * @throws NullValueException in case the given value is null */ protected <T> T ensureNotNullAndGet(String variableName, T value) { ensureNotNull(variableName, value); return value; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetTaskPropertyCmd.java
1
请完成以下Java代码
public AttributeCode getWeightTareAttribute() { return Weightables.ATTR_WeightTare; } @Override public BigDecimal getWeightTareInitial() { return weightTareInitial; } @Override public BigDecimal getWeightTare() { return weightTare; } @Override public AttributeCode getWeightNetAttribute() { return Weightables.ATTR_WeightNet; } @Override public void setWeightNetNoPropagate(final BigDecimal weightNet) { this.weightNet = weightNet; } @Override public void setWeightNet(final BigDecimal weightNet) { setWeightNetNoPropagate(weightNet); } @Override public BigDecimal getWeightNetOrNull() { return getWeightNet(); } @Override public BigDecimal getWeightNet() { return weightNet; } @Override public I_C_UOM getWeightNetUOM() { return uom; } @Override public AttributeCode getWeightGrossAttribute() { return Weightables.ATTR_WeightGross; } @Override public void setWeightGross(final BigDecimal weightGross) { this.weightGross = weightGross; } @Override public BigDecimal getWeightGross() {
return weightGross; } @Override public Quantity getWeightGrossAsQuantity() { return Quantity.of(weightGross, uom); } @Override public boolean isWeightTareAdjustAttribute(final AttributeCode attribute) { return AttributeCode.equals(attribute, Weightables.ATTR_WeightTareAdjust); } @Override public boolean isWeightTareAttribute(final AttributeCode attribute) { return AttributeCode.equals(attribute, Weightables.ATTR_WeightTare); } @Override public boolean isWeightNetAttribute(final AttributeCode attribute) { return AttributeCode.equals(attribute, Weightables.ATTR_WeightNet); } @Override public boolean isWeightGrossAttribute(final AttributeCode attribute) { return AttributeCode.equals(attribute, Weightables.ATTR_WeightGross); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\weightable\PlainWeightable.java
1
请完成以下Java代码
public class SetExecutionVariablesCmd extends AbstractSetVariableCmd { private static final long serialVersionUID = 1L; protected boolean failIfNotExists = true; public SetExecutionVariablesCmd(String executionId, Map<String, ?> variables, boolean isLocal, boolean skipJavaSerializationFormatCheck) { super(executionId, variables, isLocal, skipJavaSerializationFormatCheck); } public SetExecutionVariablesCmd(String executionId, Map<String, ?> variables, boolean isLocal, boolean skipJavaSerializationFormatCheck, boolean failIfNotExists) { this(executionId, variables, isLocal, skipJavaSerializationFormatCheck); this.failIfNotExists = failIfNotExists; } public SetExecutionVariablesCmd(String executionId, Map<String, ? extends Object> variables, boolean isLocal) { super(executionId, variables, isLocal, false); } protected ExecutionEntity getEntity() { ensureNotNull("executionId", entityId); ExecutionEntity execution = commandContext .getExecutionManager()
.findExecutionById(entityId); if (failIfNotExists) { ensureNotNull("execution " + entityId + " doesn't exist", "execution", execution); } if(execution != null) { checkSetExecutionVariables(execution); } return execution; } @Override protected ExecutionEntity getContextExecution() { return getEntity(); } protected void logVariableOperation(AbstractVariableScope scope) { ExecutionEntity execution = (ExecutionEntity) scope; commandContext.getOperationLogManager().logVariableOperation(getLogEntryOperation(), execution.getId(), null, PropertyChange.EMPTY_CHANGE); } protected void checkSetExecutionVariables(ExecutionEntity execution) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateProcessInstanceVariables(execution); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetExecutionVariablesCmd.java
1
请完成以下Java代码
public static byte[] joinBytes(byte[] byteArray1, byte[] byteArray2) { final int finalLength = byteArray1.length + byteArray2.length; final byte[] result = new byte[finalLength]; System.arraycopy(byteArray1, 0, result, 0, byteArray1.length); System.arraycopy(byteArray2, 0, result, byteArray1.length, byteArray2.length); return result; } public static UUID generateType5UUID(String name) { try { final byte[] bytes = name.getBytes(StandardCharsets.UTF_8); final MessageDigest md = MessageDigest.getInstance("SHA-1"); final byte[] hash = md.digest(bytes); long msb = getLeastAndMostSignificantBitsVersion5(hash, 0); long lsb = getLeastAndMostSignificantBitsVersion5(hash, 8); // Set the version field msb &= ~(0xfL << 12);
msb |= 5L << 12; // Set the variant field to 2 lsb &= ~(0x3L << 62); lsb |= 2L << 62; return new UUID(msb, lsb); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } } private static long getLeastAndMostSignificantBitsVersion5(final byte[] src, final int offset) { long ans = 0; for (int i = offset + 7; i >= offset; i -= 1) { ans <<= 8; ans |= src[i] & 0xffL; } return ans; } }
repos\tutorials-master\core-java-modules\core-java-uuid-generation\src\main\java\com\baeldung\uuid\UUIDGenerator.java
1
请完成以下Java代码
public void addHandler(BpmnParseHandler bpmnParseHandler) { for (Class<? extends BaseElement> type : bpmnParseHandler.getHandledTypes()) { List<BpmnParseHandler> handlers = parseHandlers.get(type); if (handlers == null) { handlers = new ArrayList<>(); parseHandlers.put(type, handlers); } handlers.add(bpmnParseHandler); } } public void parseElement(BpmnParse bpmnParse, BaseElement element) { if (element instanceof DataObject) { // ignore DataObject elements because they are processed on Process and Sub process level return; }
if (element instanceof FlowElement) { bpmnParse.setCurrentFlowElement((FlowElement) element); } // Execute parse handlers List<BpmnParseHandler> handlers = parseHandlers.get(element.getClass()); if (handlers == null) { LOGGER.warn("Could not find matching parse handler for + {} this is likely a bug.", element.getId()); } else { for (BpmnParseHandler handler : handlers) { handler.parse(bpmnParse, element); } } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParseHandlers.java
1
请完成以下Java代码
public void setCalledProcessInstanceId(String calledProcessInstanceId) { this.calledProcessInstanceId = calledProcessInstanceId; } public String getCalledCaseInstanceId() { return calledCaseInstanceId; } public void setCalledCaseInstanceId(String calledCaseInstanceId) { this.calledCaseInstanceId = calledCaseInstanceId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Date getCreateTime() { return startTime; } public void setCreateTime(Date createTime) { setStartTime(createTime); } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public boolean isAvailable() { return caseActivityInstanceState == AVAILABLE.getStateCode(); } public boolean isEnabled() { return caseActivityInstanceState == ENABLED.getStateCode();
} public boolean isDisabled() { return caseActivityInstanceState == DISABLED.getStateCode(); } public boolean isActive() { return caseActivityInstanceState == ACTIVE.getStateCode(); } public boolean isSuspended() { return caseActivityInstanceState == SUSPENDED.getStateCode(); } public boolean isCompleted() { return caseActivityInstanceState == COMPLETED.getStateCode(); } public boolean isTerminated() { return caseActivityInstanceState == TERMINATED.getStateCode(); } public String toString() { return this.getClass().getSimpleName() + "[caseActivityId=" + caseActivityId + ", caseActivityName=" + caseActivityName + ", caseActivityInstanceId=" + id + ", caseActivityInstanceState=" + caseActivityInstanceState + ", parentCaseActivityInstanceId=" + parentCaseActivityInstanceId + ", taskId=" + taskId + ", calledProcessInstanceId=" + calledProcessInstanceId + ", calledCaseInstanceId=" + calledCaseInstanceId + ", durationInMillis=" + durationInMillis + ", createTime=" + startTime + ", endTime=" + endTime + ", eventType=" + eventType + ", caseExecutionId=" + caseExecutionId + ", caseDefinitionId=" + caseDefinitionId + ", caseInstanceId=" + caseInstanceId + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricCaseActivityInstanceEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class HelloWorldController { @Value("normal") private String normal; // Inject ordinary string @Value("#{systemProperties['os.name']}") private String systemPropertiesName; //Inject operating system properties @Value("#{ T(java.lang.Math).random() * 100.0 }") private double randomNumber; //Inject expression result @Value("#{beanInject.another}") private String fromAnotherBean; // Inject other Bean attributes: Inject the attribute another of the beanInject object. See the specific definition of the class below. @Value("classpath:config.txt") private Resource resourceFile; // Inject file resources @Value("http://www.baidu.com")
private Resource testUrl; // Inject URL resources @Value("#{'${server.name}'.split(',')}") private List<String> servers; @RequestMapping("/hello") public Map<String, Object> showHelloWorld(){ Map<String, Object> map = new HashMap<>(); map.put("normal", normal); map.put("systemPropertiesName", systemPropertiesName); map.put("randomNumber", randomNumber); map.put("fromAnotherBean", fromAnotherBean); // map.put("resourceFile", resourceFile); //map.put("testUrl", testUrl); map.put("servers", servers); return map; } }
repos\springboot-demo-master\SpEL\src\main\java\com\et\spel\controller\HelloWorldController.java
2
请在Spring Boot框架中完成以下Java代码
static class Base64Checker { private static final int[] values = genValueMapping(); Base64Checker() { } private static int[] genValueMapping() { byte[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .getBytes(StandardCharsets.ISO_8859_1); int[] values = new int[256]; Arrays.fill(values, -1); for (int i = 0; i < alphabet.length; i++) { values[alphabet[i] & 0xff] = i; } return values; } boolean isAcceptable(String s) { int goodChars = 0; int lastGoodCharVal = -1; // count number of characters from Base64 alphabet for (int i = 0; i < s.length(); i++) { int val = values[0xff & s.charAt(i)]; if (val != -1) { lastGoodCharVal = val;
goodChars++; } } // in cases of an incomplete final chunk, ensure the unused bits are zero switch (goodChars % 4) { case 0: return true; case 2: return (lastGoodCharVal & 0b1111) == 0; case 3: return (lastGoodCharVal & 0b11) == 0; default: return false; } } void checkAcceptable(String ins) { if (!isAcceptable(ins)) { throw new IllegalArgumentException("Failed to decode SAMLResponse"); } } } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\internal\Saml2Utils.java
2
请完成以下Java代码
public PPOrderCost subtractingAccumulatedAmountAndQty( @NonNull final CostAmount amt, @NonNull final Quantity qty, @NonNull final QuantityUOMConverter uomConverter) { return addingAccumulatedAmountAndQty(amt.negate(), qty.negate(), uomConverter); } public PPOrderCost withPrice(@NonNull final CostPrice newPrice) { if (this.getPrice().equals(newPrice)) { return this; } return toBuilder().price(newPrice).build(); } /* package */void setPostCalculationAmount(@NonNull final CostAmount postCalculationAmount)
{ this.postCalculationAmount = postCalculationAmount; } /* package */void setPostCalculationAmountAsAccumulatedAmt() { setPostCalculationAmount(getAccumulatedAmount()); } /* package */void setPostCalculationAmountAsZero() { setPostCalculationAmount(getPostCalculationAmount().toZero()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCost.java
1
请完成以下Java代码
public boolean isTaxIncluded(final I_C_Tax tax) { final I_C_Order order = getOriginalOrder(); if (order != null && order.getC_Order_ID() > 0) { return Services.get(IOrderBL.class).isTaxIncluded(order, TaxUtils.from(tax)); } return true; } /** * Get Process Message * @return clear text error message */ @Override public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible) * @return AD_User_ID */ @Override public int getDoc_User_ID() { return getSalesRep_ID(); } // getDoc_User_ID /** * Get Document Approval Amount * @return amount
*/ @Override public BigDecimal getApprovalAmt() { return getAmt(); } // getApprovalAmt /** * Document Status is Complete or Closed * @return true if CO, CL or RE */ public boolean isComplete() { String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } // isComplete } // MRMA
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRMA.java
1
请完成以下Java代码
public void setMSV3_BestellungAntwortAuftrag_ID (int MSV3_BestellungAntwortAuftrag_ID) { if (MSV3_BestellungAntwortAuftrag_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAntwortAuftrag_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAntwortAuftrag_ID, Integer.valueOf(MSV3_BestellungAntwortAuftrag_ID)); } /** Get MSV3_BestellungAntwortAuftrag. @return MSV3_BestellungAntwortAuftrag */ @Override public int getMSV3_BestellungAntwortAuftrag_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAntwortAuftrag_ID); if (ii == null) return 0; return ii.intValue(); } /** Set GebindeId. @param MSV3_GebindeId GebindeId */ @Override public void setMSV3_GebindeId (java.lang.String MSV3_GebindeId) { set_Value (COLUMNNAME_MSV3_GebindeId, MSV3_GebindeId); } /** Get GebindeId. @return GebindeId */ @Override public java.lang.String getMSV3_GebindeId ()
{ return (java.lang.String)get_Value(COLUMNNAME_MSV3_GebindeId); } /** Set Id. @param MSV3_Id Id */ @Override public void setMSV3_Id (java.lang.String MSV3_Id) { set_Value (COLUMNNAME_MSV3_Id, MSV3_Id); } /** Get Id. @return Id */ @Override public java.lang.String getMSV3_Id () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Id); } }
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_BestellungAntwortAuftrag.java
1
请完成以下Java代码
private static class FetchUsingSourceLinkColumn implements ModelCacheInvalidateRequestFactory { @NonNull private final String targetTableName; @NonNull private final String targetKeyColumnName; @NonNull private final String targetLinkColumnName; @NonNull private final String sourceLinkColumnName; private final boolean isTargetLinkColumnSameAsKeyColumn; @Nullable private final String sqlGetTargetRecordIdByLinkId; @Builder private FetchUsingSourceLinkColumn( @NonNull final String targetTableName, @NonNull final String targetKeyColumnName, @NonNull final String targetLinkColumnName, @NonNull final String sourceLinkColumnName) { this.targetTableName = targetTableName; this.targetKeyColumnName = targetKeyColumnName; this.targetLinkColumnName = targetLinkColumnName; this.sourceLinkColumnName = sourceLinkColumnName; if (targetLinkColumnName.equals(targetKeyColumnName)) { this.isTargetLinkColumnSameAsKeyColumn = true; this.sqlGetTargetRecordIdByLinkId = null; } else { this.isTargetLinkColumnSameAsKeyColumn = false; this.sqlGetTargetRecordIdByLinkId = "SELECT " + targetKeyColumnName + " FROM " + targetTableName + " WHERE " + targetLinkColumnName + "=?"; } } @Override public List<CacheInvalidateRequest> createRequestsFromModel(@NonNull final ICacheSourceModel sourceModel, final ModelCacheInvalidationTiming timing_NOTUSED) { final int linkId = sourceModel.getValueAsInt(sourceLinkColumnName, -1); return getTargetRecordIdsByLinkId(linkId) .stream() .map(targetRecordId -> CacheInvalidateRequest.rootRecord(targetTableName, targetRecordId)) .collect(ImmutableList.toImmutableList()); } private ImmutableSet<Integer> getTargetRecordIdsByLinkId(final int linkId) { if (linkId < 0) { return ImmutableSet.of(); }
if (isTargetLinkColumnSameAsKeyColumn) { return ImmutableSet.of(linkId); } final ImmutableSet.Builder<Integer> targetRecordIds = ImmutableSet.builder(); DB.forEachRow( Check.assumeNotNull(this.sqlGetTargetRecordIdByLinkId, "sqlGetTargetRecordIdByLinkId shall not be null"), ImmutableList.of(linkId), rs -> { final int targetRecordId = rs.getInt(1); if (targetRecordId > 0) { targetRecordIds.add(targetRecordId); } }); return targetRecordIds.build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\ColumnSqlCacheInvalidateRequestFactories.java
1
请完成以下Java代码
public void setPA_ReportLine_ID (int PA_ReportLine_ID) { if (PA_ReportLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, Integer.valueOf(PA_ReportLine_ID)); } /** Get Report Line. @return Report Line */ public int getPA_ReportLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLine_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_ReportLineSet getPA_ReportLineSet() throws RuntimeException { return (I_PA_ReportLineSet)MTable.get(getCtx(), I_PA_ReportLineSet.Table_Name) .getPO(getPA_ReportLineSet_ID(), get_TrxName()); } /** Set Report Line Set. @param PA_ReportLineSet_ID Report Line Set */ public void setPA_ReportLineSet_ID (int PA_ReportLineSet_ID) { if (PA_ReportLineSet_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, Integer.valueOf(PA_ReportLineSet_ID)); } /** Get Report Line Set. @return Report Line Set */ public int getPA_ReportLineSet_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLineSet_ID); if (ii == null) return 0; return ii.intValue(); } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E"; /** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportLine.java
1
请完成以下Java代码
public java.math.BigDecimal getDiscount () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Discount); if (bd == null) return BigDecimal.ZERO; return bd; } @Override public org.compiere.model.I_C_ValidCombination getPr() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Price, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPr(org.compiere.model.I_C_ValidCombination Pr) { set_ValueFromPO(COLUMNNAME_Price, org.compiere.model.I_C_ValidCombination.class, Pr); } /** Set Preis. @param Price Price */ @Override public void setPrice (int Price) { set_ValueNoCheck (COLUMNNAME_Price, Integer.valueOf(Price)); } /** Get Preis. @return Price */ @Override public int getPrice () { Integer ii = (Integer)get_Value(COLUMNNAME_Price); if (ii == null) return 0; return ii.intValue(); } /** Set Menge. @param Qty Quantity */ @Override public void setQty (java.math.BigDecimal Qty) {
set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Symbol. @param UOMSymbol Symbol for a Unit of Measure */ @Override public void setUOMSymbol (java.lang.String UOMSymbol) { set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol); } /** Get Symbol. @return Symbol for a Unit of Measure */ @Override public java.lang.String getUOMSymbol () { return (java.lang.String)get_Value(COLUMNNAME_UOMSymbol); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLineQty_v.java
1
请完成以下Java代码
public void setId(final long id) { this.id = id; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Employee employee = (Employee) o; if (id != employee.id) { return false; } if (!Objects.equals(lastName, employee.lastName)) { return false; } return Objects.equals(firstName, employee.firstName);
} @Override public int hashCode() { int result = lastName != null ? lastName.hashCode() : 0; result = 31 * result + (firstName != null ? firstName.hashCode() : 0); result = 31 * result + (int) (id ^ (id >>> 32)); return result; } @Override public String toString() { return "User{" + "lastName='" + lastName + '\'' + ", firstName='" + firstName + '\'' + ", id=" + id + '}'; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\jsonignore\nullfields\Employee.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; private final DeliverService deliverService; public BookstoreService(AuthorRepository authorRepository, DeliverService deliverService) { this.authorRepository = authorRepository; this.deliverService = deliverService; } public void persistAuthorWithBooks() { Author author = new Author(); author.setName("Alicia Tom"); author.setAge(38); author.setGenre("Anthology"); Book book = new Book(); book.setIsbn("001-AT"); book.setTitle("The book of swords");
Paperback paperback = new Paperback(); paperback.setIsbn("002-AT"); paperback.setTitle("The beatles anthology"); paperback.setSizeIn("7.5 x 1.3 x 9.2"); paperback.setWeightLbs("2.7"); Ebook ebook = new Ebook(); ebook.setIsbn("003-AT"); ebook.setTitle("Anthology myths"); ebook.setFormat("kindle"); // author.addBook(book); // use addBook() helper author.addBook(paperback); author.addBook(ebook); authorRepository.save(author); } public void applyDelivers() { deliverService.process(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinedAndStrategy\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
public <E extends HasName, I extends EntityId> void logEntityAction(User user, I entityId, E entity, CustomerId customerId, ActionType actionType, Exception e, Object... additionalInfo) { if (customerId == null || customerId.isNullUid()) { customerId = user.getCustomerId(); } if (e == null) { pushEntityActionToRuleEngine(entityId, entity, user.getTenantId(), customerId, actionType, user, additionalInfo); } auditLogService.logEntityAction(user.getTenantId(), customerId, user.getId(), user.getName(), entityId, entity, actionType, e, additionalInfo); } private <T> T extractParameter(Class<T> clazz, int index, Object... additionalInfo) { T result = null; if (additionalInfo != null && additionalInfo.length > index) { Object paramObject = additionalInfo[index]; if (clazz.isInstance(paramObject)) { result = clazz.cast(paramObject); } } return result; }
private void addTimeseries(ObjectNode entityNode, List<TsKvEntry> timeseries) { if (timeseries != null && !timeseries.isEmpty()) { ArrayNode result = entityNode.putArray("timeseries"); Map<Long, List<TsKvEntry>> groupedTelemetry = timeseries.stream() .collect(Collectors.groupingBy(TsKvEntry::getTs)); for (Map.Entry<Long, List<TsKvEntry>> entry : groupedTelemetry.entrySet()) { ObjectNode element = JacksonUtil.newObjectNode(); element.put("ts", entry.getKey()); ObjectNode values = element.putObject("values"); for (TsKvEntry tsKvEntry : entry.getValue()) { JacksonUtil.addKvEntry(values, tsKvEntry); } result.add(element); } } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\action\EntityActionService.java
2
请完成以下Java代码
public String getValueTableName() { return valueTableName; } @Override public String getValueColumnName() { return valueColumnName; } @Override public int getValueDisplayType() { return valueDisplayType; } @Override public String getKeyTableName() { return keyTableName; } @Override public String getKeyColumnName() { return keyColumnName; }
@Override public int getRecordId() { return recordId; } @Override public String toString() { return "TableColumnPath [valueTableName=" + valueTableName + ", valueColumnName=" + valueColumnName + ", keyTableName=" + keyTableName + ", keyColumnName=" + keyColumnName + ", recordId=" + recordId + ", elements=" + elements + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\model\TableColumnPath.java
1
请完成以下Java代码
public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Datensatz verarbeitet wurde. */ @Override 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 Referenznummer. @param ReferenceNo Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public void setReferenceNo (java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } /** Get Referenznummer. @return Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public java.lang.String getReferenceNo () {
return (java.lang.String)get_Value(COLUMNNAME_ReferenceNo); } /** Set Bewegungs-Betrag. @param TrxAmt Betrag einer Transaktion */ @Override public void setTrxAmt (java.math.BigDecimal TrxAmt) { set_Value (COLUMNNAME_TrxAmt, TrxAmt); } /** Get Bewegungs-Betrag. @return Betrag einer Transaktion */ @Override public java.math.BigDecimal getTrxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TrxAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_BankStatementLine_Ref.java
1
请在Spring Boot框架中完成以下Java代码
private void extractAndPropagateAdempiereException(final CompletableFuture completableFuture) { try { completableFuture.get(); } catch (final ExecutionException ex) { throw AdempiereException.wrapIfNeeded(ex.getCause()); } catch (final InterruptedException ex1) { throw AdempiereException.wrapIfNeeded(ex1); } } private void checkIfTheEffortCanBeBooked(@NonNull final ImportTimeBookingInfo importTimeBookingInfo, @NonNull final IssueEntity targetIssue) { if (!targetIssue.isProcessed() || targetIssue.getProcessedTimestamp() == null) { return;//nothing else to check ( issues that are not processed yet are used for booking effort ) } final LocalDate effortBookedDate = TimeUtil.asLocalDate(importTimeBookingInfo.getBookedDate()); final LocalDate processedIssueDate = TimeUtil.asLocalDate(targetIssue.getProcessedTimestamp()); final boolean effortWasBookedOnAProcessedIssue = effortBookedDate.isAfter(processedIssueDate); if (effortWasBookedOnAProcessedIssue) { final I_AD_User performingUser = userDAO.getById(importTimeBookingInfo.getPerformingUserId()); throw new AdempiereException("Time bookings cannot be added for already processed issues!")
.appendParametersToMessage() .setParameter("ImportTimeBookingInfo", importTimeBookingInfo) .setParameter("Performing user", performingUser.getName()) .setParameter("Note", "This FailedTimeBooking record will not be automatically deleted!"); } } private void storeFailed( @NonNull final OrgId orgId, @NonNull final ImportTimeBookingInfo importTimeBookingInfo, @NonNull final String errorMsg) { final FailedTimeBooking failedTimeBooking = FailedTimeBooking.builder() .orgId(orgId) .externalId(importTimeBookingInfo.getExternalTimeBookingId().getId()) .externalSystem(importTimeBookingInfo.getExternalTimeBookingId().getExternalSystem()) .errorMsg(errorMsg) .build(); failedTimeBookingRepository.save(failedTimeBooking); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\importer\TimeBookingsImporterService.java
2
请完成以下Java代码
private String buildMessage(final String adLanguage) { // // Build detail message final StringBuilder detailBuf = new StringBuilder(); if(!severity.isNotice()) { final String notificationSeverity = getSeverity().getNameTrl().translate(adLanguage); detailBuf.append(notificationSeverity).append(":"); } // Add plain detail if any if (!Check.isEmpty(detailPlain, true)) { detailBuf.append(detailPlain.trim()); } // Translate, parse and add detail (AD_Message). if (!Check.isEmpty(detailADMessage, true)) { final String detailTrl = Services.get(IMsgBL.class) .getTranslatableMsgText(detailADMessage) .translate(adLanguage); final String detailTrlParsed = UserNotificationDetailMessageFormat.newInstance() .setLeftBrace("{").setRightBrace("}") .setThrowExceptionIfKeyWasNotFound(false) .setArguments(detailADMessageParams) .format(detailTrl); if (!Check.isEmpty(detailTrlParsed, true)) { if (detailBuf.length() > 0) { detailBuf.append("\n"); } detailBuf.append(detailTrlParsed); } } return detailBuf.toString(); } public synchronized boolean isRead() { return read; }
public boolean isNotRead() { return !isRead(); } public synchronized boolean setRead(final boolean read) { final boolean readOld = this.read; this.read = read; return readOld; } @Nullable public String getTargetWindowIdAsString() { return targetWindowId != null ? String.valueOf(targetWindowId.getRepoId()) : null; } @Nullable public String getTargetDocumentId() { return targetRecord != null ? String.valueOf(targetRecord.getRecord_ID()) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\UserNotification.java
1
请完成以下Java代码
public void setHandOver_Location_Value_ID(final int HandOver_Location_Value_ID) { delegate.setHandOver_Location_Value_ID(HandOver_Location_Value_ID); } @Override public int getHandOver_User_ID() { return delegate.getHandOver_User_ID(); } @Override public void setHandOver_User_ID(final int HandOver_User_ID) { delegate.setHandOver_User_ID(HandOver_User_ID); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentHandOverLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentHandOverLocationAdapter.super.setRenderedAddress(from); }
@Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public HandOverLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new HandOverLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_OLCand.class)); } @Override public I_C_OLCand getWrappedRecord() { return delegate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\HandOverLocationAdapter.java
1
请完成以下Java代码
public class DynamicBeanPropertyELResolver extends ELResolver { protected Class<?> subject; protected String readMethodName; protected String writeMethodName; protected boolean readOnly; public DynamicBeanPropertyELResolver( boolean readOnly, Class<?> subject, String readMethodName, String writeMethodName ) { this.readOnly = readOnly; this.subject = subject; this.readMethodName = readMethodName; this.writeMethodName = writeMethodName; } public DynamicBeanPropertyELResolver(Class<?> subject, String readMethodName, String writeMethodName) { this(false, subject, readMethodName, writeMethodName); } @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { if (this.subject.isInstance(base)) { return Object.class; } else { return null; } } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { return null; } @Override public Class<?> getType(ELContext context, Object base, Object property) { if (base == null || this.getCommonPropertyType(context, base) == null) { return null; } context.setPropertyResolved(true); return Object.class; } @Override public Object getValue(ELContext context, Object base, Object property) { if (base == null || this.getCommonPropertyType(context, base) == null) { return null; } String propertyName = property.toString(); try {
Object value = ReflectUtil.invoke(base, this.readMethodName, new Object[] { propertyName }); context.setPropertyResolved(true); return value; } catch (Exception e) { throw new ELException(e); } } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return this.readOnly; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { if (base == null || this.getCommonPropertyType(context, base) == null) { return; } String propertyName = property.toString(); try { ReflectUtil.invoke(base, this.writeMethodName, new Object[] { propertyName, value }); context.setPropertyResolved(true); } catch (Exception e) { throw new ELException(e); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\DynamicBeanPropertyELResolver.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public int getSuspensionState() {
return suspensionState; } public void setSuspensionState(int suspensionState) { this.suspensionState = suspensionState; } public Integer getInstances() { return instances; } public void setInstances(Integer instances) { this.instances = instances; } public Integer getIncidents() { return incidents; } public void setIncidents(Integer incidents) { this.incidents = incidents; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\ProcessDefinitionStatisticsDto.java
1
请完成以下Java代码
public String getSwingActionMapName() { return swingActionMapName; } public String getAD_Message() { return adMessage; } public KeyStroke getKeyStroke() { return keyStroke; } } /** * Execute cut/copy/paste action of given type. * * @param actionType */ void executeCopyPasteAction(final CopyPasteActionType actionType); /** * Gets the copy/paste {@link Action} associated with given type. * * @param actionType * @return action or <code>null</code> */ Action getCopyPasteAction(final CopyPasteActionType actionType);
/** * Associate given action with given action type. * * @param actionType * @param action * @param keyStroke optional key stroke to be binded to given action. */ void putCopyPasteAction(final CopyPasteActionType actionType, final Action action, final KeyStroke keyStroke); /** * @param actionType * @return true if given action can be performed */ boolean isCopyPasteActionAllowed(final CopyPasteActionType actionType); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\ICopyPasteSupportEditor.java
1
请在Spring Boot框架中完成以下Java代码
public void download(List<QuartzJob> quartzJobs, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (QuartzJob quartzJob : quartzJobs) { Map<String,Object> map = new LinkedHashMap<>(); map.put("任务名称", quartzJob.getJobName()); map.put("Bean名称", quartzJob.getBeanName()); map.put("执行方法", quartzJob.getMethodName()); map.put("参数", quartzJob.getParams()); map.put("表达式", quartzJob.getCronExpression()); map.put("状态", quartzJob.getIsPause() ? "暂停中" : "运行中"); map.put("描述", quartzJob.getDescription()); map.put("创建日期", quartzJob.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } @Override public void downloadLog(List<QuartzLog> queryAllLog, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (QuartzLog quartzLog : queryAllLog) {
Map<String,Object> map = new LinkedHashMap<>(); map.put("任务名称", quartzLog.getJobName()); map.put("Bean名称", quartzLog.getBeanName()); map.put("执行方法", quartzLog.getMethodName()); map.put("参数", quartzLog.getParams()); map.put("表达式", quartzLog.getCronExpression()); map.put("异常详情", quartzLog.getExceptionDetail()); map.put("耗时/毫秒", quartzLog.getTime()); map.put("状态", quartzLog.getIsSuccess() ? "成功" : "失败"); map.put("创建日期", quartzLog.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\quartz\service\impl\QuartzJobServiceImpl.java
2
请完成以下Java代码
public boolean isAllNotNulls(final Object... values) { for (final Object value : values) { if (value == null) { return false; } } return true; } public int countNotNulls(@Nullable final Object... values) { if (values == null || values.length == 0) { return 0; } int count = 0; for (final Object value : values) { if (value != null) { count++; } } return count;
} @NonNull public BigDecimal firstPositiveOrZero(final BigDecimal... values) { if (values == null) { return BigDecimal.ZERO; } for (final BigDecimal value : values) { if (value != null && value.signum() > 0) { return value; } } return BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\CoalesceUtil.java
1
请在Spring Boot框架中完成以下Java代码
PropertiesOtlpLoggingConnectionDetails openTelemetryLoggingConnectionDetails(OtlpLoggingProperties properties) { return new PropertiesOtlpLoggingConnectionDetails(properties); } /** * Adapts {@link OtlpLoggingProperties} to {@link OtlpLoggingConnectionDetails}. */ static class PropertiesOtlpLoggingConnectionDetails implements OtlpLoggingConnectionDetails { private final OtlpLoggingProperties properties; PropertiesOtlpLoggingConnectionDetails(OtlpLoggingProperties properties) { this.properties = properties; } @Override public String getUrl(Transport transport) { Assert.state(transport == this.properties.getTransport(), "Requested transport %s doesn't match configured transport %s".formatted(transport, this.properties.getTransport())); String endpoint = this.properties.getEndpoint(); Assert.state(endpoint != null, "'endpoint' must not be null"); return endpoint; } } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(OtlpHttpLogRecordExporter.class) @ConditionalOnMissingBean({ OtlpGrpcLogRecordExporter.class, OtlpHttpLogRecordExporter.class }) @ConditionalOnBean(OtlpLoggingConnectionDetails.class) @ConditionalOnEnabledLoggingExport("otlp") static class Exporters { @Bean @ConditionalOnProperty(name = "management.opentelemetry.logging.export.otlp.transport", havingValue = "http", matchIfMissing = true) OtlpHttpLogRecordExporter otlpHttpLogRecordExporter(OtlpLoggingProperties properties, OtlpLoggingConnectionDetails connectionDetails, ObjectProvider<MeterProvider> meterProvider) { OtlpHttpLogRecordExporterBuilder builder = OtlpHttpLogRecordExporter.builder() .setEndpoint(connectionDetails.getUrl(Transport.HTTP))
.setTimeout(properties.getTimeout()) .setConnectTimeout(properties.getConnectTimeout()) .setCompression(properties.getCompression().name().toLowerCase(Locale.US)); properties.getHeaders().forEach(builder::addHeader); meterProvider.ifAvailable(builder::setMeterProvider); return builder.build(); } @Bean @ConditionalOnProperty(name = "management.opentelemetry.logging.export.otlp.transport", havingValue = "grpc") OtlpGrpcLogRecordExporter otlpGrpcLogRecordExporter(OtlpLoggingProperties properties, OtlpLoggingConnectionDetails connectionDetails, ObjectProvider<MeterProvider> meterProvider) { OtlpGrpcLogRecordExporterBuilder builder = OtlpGrpcLogRecordExporter.builder() .setEndpoint(connectionDetails.getUrl(Transport.GRPC)) .setTimeout(properties.getTimeout()) .setConnectTimeout(properties.getConnectTimeout()) .setCompression(properties.getCompression().name().toLowerCase(Locale.US)); properties.getHeaders().forEach(builder::addHeader); meterProvider.ifAvailable(builder::setMeterProvider); return builder.build(); } } }
repos\spring-boot-4.0.1\module\spring-boot-opentelemetry\src\main\java\org\springframework\boot\opentelemetry\autoconfigure\logging\otlp\OtlpLoggingConfigurations.java
2
请完成以下Java代码
static UriComponents oidc(String issuer) { UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build(); // @formatter:off return UriComponentsBuilder.newInstance().uriComponents(uri) .replacePath(uri.getPath() + OIDC_METADATA_PATH) .build(); // @formatter:on } static UriComponents oidcRfc8414(String issuer) { UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build(); // @formatter:off return UriComponentsBuilder.newInstance().uriComponents(uri) .replacePath(OIDC_METADATA_PATH + uri.getPath()) .build(); // @formatter:on } static UriComponents oauth(String issuer) { UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build(); // @formatter:off return UriComponentsBuilder.newInstance().uriComponents(uri) .replacePath(OAUTH_METADATA_PATH + uri.getPath()) .build(); // @formatter:on } private static Mono<Map<String, Object>> getConfiguration(String issuer, WebClient web, UriComponents... uris) { String errorMessage = "Unable to resolve the Configuration with the provided Issuer of " + "\"" + issuer + "\""; return Flux.just(uris) .concatMap((uri) -> web.get().uri(uri.toUriString()).retrieve().bodyToMono(STRING_OBJECT_MAP))
.flatMap((configuration) -> { if (configuration.get("jwks_uri") == null) { return Mono.error(() -> new IllegalArgumentException("The public JWK set URI must not be null")); } return Mono.just(configuration); }) .onErrorContinue((ex) -> ex instanceof WebClientResponseException && ((WebClientResponseException) ex).getStatusCode().is4xxClientError(), (ex, object) -> { }) .onErrorMap(RuntimeException.class, (ex) -> (ex instanceof IllegalArgumentException) ? ex : new IllegalArgumentException(errorMessage, ex)) .next() .switchIfEmpty(Mono.error(() -> new IllegalArgumentException(errorMessage))); } private ReactiveJwtDecoderProviderConfigurationUtils() { } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\ReactiveJwtDecoderProviderConfigurationUtils.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof Language) { final Language other = (Language)obj; return Objects.equals(this.m_AD_Language, other.m_AD_Language); } return false; } // equals private static int timeStyleDefault = DateFormat.MEDIUM; /** * Sets default time style to be used when getting DateTime format or Time format. * * @param timeStyle one of {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM}, {@link DateFormat#LONG}. */ public static void setDefaultTimeStyle(final int timeStyle) { timeStyleDefault = timeStyle; } public static int getDefaultTimeStyle() { return timeStyleDefault; } public int getTimeStyle() {
return getDefaultTimeStyle(); } private boolean matchesLangInfo(final String langInfo) { if (langInfo == null || langInfo.isEmpty()) { return false; } return langInfo.equals(getName()) || langInfo.equals(getAD_Language()) || langInfo.equals(getLanguageCode()); } } // Language
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\Language.java
1
请完成以下Java代码
public boolean isCalculated() { return result.isCalculated(); } // isCalculated /** * Convenience method to get priceStd with the discount already subtracted. Note that the result matches the former behavior of {@link #getPriceStd()}. */ public BigDecimal mkPriceStdMinusDiscount() { calculatePrice(false); return result.getDiscount().subtractFromBase(result.getPriceStd(), result.getPrecision().toInt()); } @Override public String toString() { return "MProductPricing [" + pricingCtx + ", " + result + "]"; } public void setConvertPriceToContextUOM(boolean convertPriceToContextUOM) { pricingCtx.setConvertPriceToContextUOM(convertPriceToContextUOM); }
public void setReferencedObject(Object referencedObject) { pricingCtx.setReferencedObject(referencedObject); } // metas: end public int getC_TaxCategory_ID() { return TaxCategoryId.toRepoId(result.getTaxCategoryId()); } public boolean isManualPrice() { return pricingCtx.getManualPriceEnabled().isTrue(); } public void setManualPrice(boolean manualPrice) { pricingCtx.setManualPriceEnabled(manualPrice); } public void throwProductNotOnPriceListException() { throw new ProductNotOnPriceListException(pricingCtx); } } // MProductPrice
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProductPricing.java
1
请完成以下Java代码
public Permission getPermission() { return this.permission; } @Override public Sid getSid() { return this.sid; } @Override public boolean isAuditFailure() { return this.auditFailure; } @Override public boolean isAuditSuccess() { return this.auditSuccess; } @Override public boolean isGranting() { return this.granting; } void setAuditFailure(boolean auditFailure) { this.auditFailure = auditFailure; } void setAuditSuccess(boolean auditSuccess) { this.auditSuccess = auditSuccess; } void setPermission(Permission permission) { Assert.notNull(permission, "Permission required"); this.permission = permission; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AccessControlEntryImpl["); sb.append("id: ").append(this.id).append("; "); sb.append("granting: ").append(this.granting).append("; "); sb.append("sid: ").append(this.sid).append("; "); sb.append("permission: ").append(this.permission).append("; "); sb.append("auditSuccess: ").append(this.auditSuccess).append("; "); sb.append("auditFailure: ").append(this.auditFailure); sb.append("]"); return sb.toString(); } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\AccessControlEntryImpl.java
1
请完成以下Java代码
public ChangeTenantIdBuilder definitionTenantId(String definitionTenantId) { if (definitionTenantId == null) { throw new FlowableIllegalArgumentException("definitionTenantId must not be null"); } this.definitionTenantId = definitionTenantId; return this; } @Override public ChangeTenantIdResult simulate() { return changeTenantIdManager.simulate(this); } @Override public ChangeTenantIdResult complete() {
return changeTenantIdManager.complete(this); } public String getSourceTenantId() { return sourceTenantId; } public String getTargetTenantId() { return targetTenantId; } public String getDefinitionTenantId() { return definitionTenantId; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\tenant\ChangeTenantIdBuilderImpl.java
1
请完成以下Java代码
public void writeAvroToFile(Schema schema, List<Point> records, File writeLocation) { try { // Delete file if it exists if (writeLocation.exists()) { if (!writeLocation.delete()) { System.err.println("Failed to delete existing file."); return; } } // Create the Avro file writer GenericDatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter); dataFileWriter.create(schema, writeLocation); // Write each record as a GenericRecord for (Point record : records) { GenericRecord genericRecord = new GenericData.Record(schema); genericRecord.put("x", record.getX()); genericRecord.put("y", record.getY()); dataFileWriter.append(genericRecord); } dataFileWriter.close(); } catch (IOException e) { e.printStackTrace(); System.out.println("Error writing Avro file."); } }
// Method to read Avro file and convert to JSON public void readAvroFromFileToJsonFile(File readLocation, File jsonFilePath) { DatumReader<GenericRecord> reader = new GenericDatumReader<>(); try { DataFileReader<GenericRecord> dataFileReader = new DataFileReader<>(readLocation, reader); DatumWriter<GenericRecord> jsonWriter = new GenericDatumWriter<>(dataFileReader.getSchema()); Schema schema = dataFileReader.getSchema(); // Read each Avro record and write as JSON OutputStream fos = new FileOutputStream(jsonFilePath); JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(schema, fos); while (dataFileReader.hasNext()) { GenericRecord record = dataFileReader.next(); System.out.println(record.toString()); jsonWriter.write(record, jsonEncoder); jsonEncoder.flush(); } dataFileReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\avrotojson\AvroFileToJsonFile.java
1
请在Spring Boot框架中完成以下Java代码
public KieSession getKieSession() throws IOException { LOGGER.info("Session created..."); KieSession kieSession = getKieContainer().newKieSession(); kieSession.setGlobal("showResults", new OutputDisplay()); kieSession.setGlobal("sh", new OutputDisplay()); kieSession.addEventListener(new RuleRuntimeEventListener() { @Override public void objectInserted(ObjectInsertedEvent event) { System.out.println("Object inserted \n " + event.getObject().toString()); } @Override public void objectUpdated(ObjectUpdatedEvent event) { System.out.println("Object was updated \n" + "New Content \n" + event.getObject().toString()); } @Override public void objectDeleted(ObjectDeletedEvent event) { System.out.println("Object retracted \n" + event.getOldObject().toString()); } }); return kieSession; } @Bean
public KieContainer getKieContainer() throws IOException { LOGGER.info("Container created..."); getKieRepository(); KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem()); kb.buildAll(); KieModule kieModule = kb.getKieModule(); return kieServices.newKieContainer(kieModule.getReleaseId()); } private void getKieRepository() { final KieRepository kieRepository = kieServices.getRepository(); kieRepository.addKieModule(new KieModule() { @Override public ReleaseId getReleaseId() { return kieRepository.getDefaultReleaseId(); } }); } private KieFileSystem getKieFileSystem() throws IOException { KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); kieFileSystem.write(ResourceFactory.newClassPathResource("order.drl")); return kieFileSystem; } }
repos\springboot-demo-master\drools\src\main\java\com\et\drools\DroolsConfig.java
2
请在Spring Boot框架中完成以下Java代码
public static SecurityObservationSettings noObservations() { return new SecurityObservationSettings(false, false, false); } /** * Begin the configuration of a {@link SecurityObservationSettings} * @return a {@link Builder} where filter chain observations are off and authn/authz * observations are on */ public static Builder withDefaults() { return new Builder(false, true, true); } public boolean shouldObserveRequests() { return this.observeRequests; } public boolean shouldObserveAuthentications() { return this.observeAuthentications; } public boolean shouldObserveAuthorizations() { return this.observeAuthorizations; } /** * A builder for configuring a {@link SecurityObservationSettings} */ public static final class Builder { private boolean observeRequests; private boolean observeAuthentications;
private boolean observeAuthorizations; Builder(boolean observeRequests, boolean observeAuthentications, boolean observeAuthorizations) { this.observeRequests = observeRequests; this.observeAuthentications = observeAuthentications; this.observeAuthorizations = observeAuthorizations; } public Builder shouldObserveRequests(boolean excludeFilters) { this.observeRequests = excludeFilters; return this; } public Builder shouldObserveAuthentications(boolean excludeAuthentications) { this.observeAuthentications = excludeAuthentications; return this; } public Builder shouldObserveAuthorizations(boolean excludeAuthorizations) { this.observeAuthorizations = excludeAuthorizations; return this; } public SecurityObservationSettings build() { return new SecurityObservationSettings(this.observeRequests, this.observeAuthentications, this.observeAuthorizations); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\observation\SecurityObservationSettings.java
2
请完成以下Java代码
public void setType(String value) { this.type = value; } /** * Gets the value of the storno property. * * @return * possible object is * {@link Boolean } * */ public boolean isStorno() { if (storno == null) { return false; } else { return storno; } } /** * Sets the value of the storno property. * * @param value * allowed object is * {@link Boolean } * */ public void setStorno(Boolean value) { this.storno = value; } /** * Gets the value of the copy property. * * @return * possible object is * {@link Boolean } * */ public boolean isCopy() { if (copy == null) { return false; } else { return copy; } } /**
* Sets the value of the copy property. * * @param value * allowed object is * {@link Boolean } * */ public void setCopy(Boolean value) { this.copy = value; } /** * Gets the value of the creditAdvice property. * * @return * possible object is * {@link Boolean } * */ public boolean isCreditAdvice() { if (creditAdvice == null) { return false; } else { return creditAdvice; } } /** * Sets the value of the creditAdvice property. * * @param value * allowed object is * {@link Boolean } * */ public void setCreditAdvice(Boolean value) { this.creditAdvice = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\PayloadType.java
1
请在Spring Boot框架中完成以下Java代码
public class MKTG_ContactPerson_ProcessBase { private final UserRepository userRepository; private final CampaignService campaignService; public MKTG_ContactPerson_ProcessBase(@NonNull final UserRepository userRepository, @NonNull final CampaignService campaignService) { this.userRepository = userRepository; this.campaignService = campaignService; } public void createContactPersonsForUser(final IQueryFilter<I_AD_User> currentSelectionFilter, final CampaignId campaignId, final DefaultAddressType defaultAddressType) { final IQueryBL queryBL = Services.get(IQueryBL.class); final IQuery<I_MKTG_Campaign_ContactPerson> linkTableQuery = queryBL.createQueryBuilder(I_MKTG_Campaign_ContactPerson.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_MKTG_Campaign_ContactPerson.COLUMN_MKTG_Campaign_ID, campaignId) .create(); final Stream<User> usersToAdd = queryBL .createQueryBuilder(I_AD_User.class) .addOnlyActiveRecordsFilter() .filter(currentSelectionFilter) .addNotInSubQueryFilter(I_AD_User.COLUMN_AD_User_ID, I_MKTG_Campaign_ContactPerson.COLUMN_AD_User_ID, linkTableQuery) .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, false) .setOption(IQuery.OPTION_IteratorBufferSize, 1000) .iterateAndStream() .map(userRepository::ofRecord); campaignService.addAsContactPersonsToCampaign( usersToAdd, campaignId, defaultAddressType); }
public void createContactPersonsForPartner(final MKTG_ContactPerson_ProcessParams params) { final IQueryBL queryBL = Services.get(IQueryBL.class); final CampaignId campaignId = params.getCampaignId(); if (params.isRemoveAllExistingContactsFromCampaign()) { campaignService.removeContactPersonsFromCampaign(campaignId); } final IQuery<I_MKTG_Campaign_ContactPerson> linkTableQuery = queryBL.createQueryBuilder(I_MKTG_Campaign_ContactPerson.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_MKTG_Campaign_ContactPerson.COLUMN_MKTG_Campaign_ID, campaignId) .create(); final Stream<User> usersToAdd = queryBL .createQueryBuilder(I_C_BPartner.class) .addOnlyActiveRecordsFilter() .filter(params.getSelectionFilter()) .andCollectChildren(I_AD_User.COLUMNNAME_C_BPartner_ID, I_AD_User.class) .addNotInSubQueryFilter(I_AD_User.COLUMNNAME_AD_User_ID, I_MKTG_Campaign_ContactPerson.COLUMNNAME_AD_User_ID, linkTableQuery) .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .setOption(IQuery.OPTION_IteratorBufferSize, 1000) .iterateAndStream() .map(userRepository::ofRecord); campaignService.addAsContactPersonsToCampaign( usersToAdd, campaignId, params.getAddresType()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\process\MKTG_ContactPerson_ProcessBase.java
2
请在Spring Boot框架中完成以下Java代码
public class PaymentAllocationId implements RepoIdAware { @JsonCreator public static PaymentAllocationId ofRepoId(final int repoId) { return new PaymentAllocationId(repoId); } public static PaymentAllocationId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PaymentAllocationId(repoId) : null; } int repoId; private PaymentAllocationId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "C_AllocationHdr_ID"); } @JsonValue @Override public int getRepoId() { return repoId; } public static int toRepoId(final PaymentAllocationId PaymentAllocationId) { return PaymentAllocationId != null ? PaymentAllocationId.getRepoId() : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\PaymentAllocationId.java
2
请完成以下Java代码
public ProcessDefaultParametersUpdater onDefaultValue(@NonNull final BiConsumer<IProcessDefaultParameter, Object> defaultValueConsumer) { this.defaultValueConsumer = defaultValueConsumer; return this; } /** * Asks this updater to fetch the default value for given parameter and forward it to default value consumer configured by {@link #onDefaultValue(BiConsumer)}. * * @param parameter */ public void updateDefaultValue(@NonNull final IProcessDefaultParameter parameter) { for (final IProcessDefaultParametersProvider provider : defaultParametersProviders) { // // Ask provider for default value Object value = null; try { value = provider.getParameterDefaultValue(parameter); } catch (final Exception e) { // ignore the error, but log it final String parameterName = parameter.getColumnName(); logger.error("Failed retrieving the parameters default value from defaults provider: ParameterName={}, Provider={}", parameterName, provider, e); continue; } // If the provider cannot provide a default value, we are skipping it and we will ask the next provider if any. if (value == IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE) { continue; } // We got a default value from provider. // Set it and stop here. defaultValueConsumer.accept(parameter, Null.unbox(value)); break; } } /** * Asks this updater to * <ul> * <li>iterate given <code>parameterObjs</code> collection * <li>convert the parameter object to {@link IProcessDefaultParameter} using given <code>processDefaultParameterConverter</code> * <li>fetch the default value for each parameter * <li>forward the default value to default value consumer configured by {@link #onDefaultValue(BiConsumer)}. * </ul>
* * @param parameterObjs * @param processDefaultParameterConverter */ public <T> void updateDefaultValue(final Collection<T> parameterObjs, final Function<T, IProcessDefaultParameter> processDefaultParameterConverter) { if(defaultParametersProviders.isEmpty()) { return; } if (parameterObjs == null || parameterObjs.isEmpty()) { return; } parameterObjs.stream() // stream parameter objects .map(processDefaultParameterConverter) // convert parameter object to IProcessDefaultParameter .forEach(this::updateDefaultValue) // update the default value if available ; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessDefaultParametersUpdater.java
1
请完成以下Java代码
public List<I_PP_Cost_Collector> getCompletedOrClosedByOrderId(@NonNull final PPOrderId orderId) { return queryBL.createQueryBuilder(I_PP_Cost_Collector.class) .addEqualsFilter(I_PP_Cost_Collector.COLUMN_PP_Order_ID, orderId) .addInArrayFilter(I_PP_Cost_Collector.COLUMN_DocStatus, IDocument.STATUS_Completed, IDocument.STATUS_Closed) .orderBy(I_PP_Cost_Collector.COLUMN_PP_Cost_Collector_ID) .create() .list(); } @Override public BigDecimal getQtyUsageVariance(@NonNull final PPOrderBOMLineId orderBOMLineId) { final BigDecimal qtyUsageVariance = queryBL.createQueryBuilder(I_PP_Cost_Collector.class) .addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_BOMLine_ID, orderBOMLineId) .addInArrayFilter(I_PP_Cost_Collector.COLUMNNAME_DocStatus, X_PP_Cost_Collector.DOCSTATUS_Completed, X_PP_Cost_Collector.DOCSTATUS_Closed) .addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_CostCollectorType, CostCollectorType.UsageVariance.getCode()) .addOnlyActiveRecordsFilter() .create() .aggregate(I_PP_Cost_Collector.COLUMNNAME_MovementQty, Aggregate.MAX, BigDecimal.class); return qtyUsageVariance != null ? qtyUsageVariance : BigDecimal.ZERO; } @Override public Duration getTotalSetupTimeReal(@NonNull final PPOrderRoutingActivity activity, @NonNull final CostCollectorType costCollectorType) { return computeDuration(activity, costCollectorType, I_PP_Cost_Collector.COLUMNNAME_SetupTimeReal); } @Override public Duration getDurationReal(@NonNull final PPOrderRoutingActivity activity, @NonNull final CostCollectorType costCollectorType) { return computeDuration(activity, costCollectorType, I_PP_Cost_Collector.COLUMNNAME_DurationReal); } private Duration computeDuration(final PPOrderRoutingActivity activity, final CostCollectorType costCollectorType, final String durationColumnName) { BigDecimal duration = queryBL.createQueryBuilder(I_PP_Cost_Collector.class) .addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_ID, activity.getOrderId()) .addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_Node_ID, activity.getId())
.addInArrayFilter(I_PP_Cost_Collector.COLUMNNAME_DocStatus, X_PP_Cost_Collector.DOCSTATUS_Completed, X_PP_Cost_Collector.DOCSTATUS_Closed) .addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_CostCollectorType, costCollectorType.getCode()) .create() .aggregate(durationColumnName, Aggregate.SUM, BigDecimal.class); if (duration == null) { duration = BigDecimal.ZERO; } final int durationInt = duration.setScale(0, RoundingMode.UP).intValueExact(); return Duration.of(durationInt, activity.getDurationUnit().getTemporalUnit()); } @Override public void save(@NonNull final I_PP_Cost_Collector cc) { saveRecord(cc); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\impl\PPCostCollectorDAO.java
1
请完成以下Java代码
public AddTemplateResponse addTemplate(String shortTemplateId) { LOG.debug("添加模版......"); BeanUtil.requireNonNull(shortTemplateId, "短模版id必填"); String url = BASE_API_URL + "cgi-bin/template/api_add_template?access_token=" + apiConfig.getAccessToken(); ; Map<String, String> params = new HashMap<String, String>(); params.put("template_id_short", shortTemplateId); BaseResponse r = executePost(url, JSON.toJSONString(params)); String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString(); return JSON.parseObject(resultJson, AddTemplateResponse.class); } /** * 发送模版消息 * * @param msg 消息 * @return 发送结果 */
public SendTemplateResponse send(TemplateMsg msg) { LOG.debug("发送模版消息......"); BeanUtil.requireNonNull(msg.getTouser(), "openid is null"); BeanUtil.requireNonNull(msg.getTemplateId(), "template_id is null"); BeanUtil.requireNonNull(msg.getData(), "data is null"); // BeanUtil.requireNonNull(msg.getTopcolor(), "top color is null"); // BeanUtil.requireNonNull(msg.getUrl(), "url is null"); String url = BASE_API_URL + "cgi-bin/message/template/send?access_token=" + apiConfig.getAccessToken(); ; BaseResponse r = executePost(url, msg.toJsonString()); String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString(); SendTemplateResponse result = JSON.parseObject(resultJson, SendTemplateResponse.class); return result; } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\TemplateMsgApi.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof User)) { return false; } return id != null && id.equals(((User) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); }
// prettier-ignore @Override public String toString() { return "User{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated='" + activated + '\'' + ", langKey='" + langKey + '\'' + ", activationKey='" + activationKey + '\'' + "}"; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java
2
请在Spring Boot框架中完成以下Java代码
private void setPrintingResult(@NonNull final Exchange exchange) { final Object printingDataCandidate = exchange.getIn().getBody(); if (!(printingDataCandidate instanceof JsonPrintingDataResponse)) { throw new RuntimeCamelException("API Request " + MF_PRINT_V2_BASE + "getPrintingData/" + "{" + HEADER_PRINTING_QUEUE_ID + "}" + "expected result to be instanceof JsonPrintingDataResponse." + " However, it is " + (printingDataCandidate == null ? "null" : printingDataCandidate.getClass().getName())); } final JsonPrintingDataResponse request = (JsonPrintingDataResponse) printingDataCandidate; final PrintingClientContext context = exchange.getProperty(PrintingClientConstants.PRINTING_CLIENT_CONTEXT, PrintingClientContext.class); try { printingClientPDFFileStorer.storeInFileSystem(request, context.getTargetDirectory());
} catch (final PrintingException e) { final JsonPrintingResultRequest response = JsonPrintingResultRequest.builder() .processed(false) .errorMsg("ERROR: " + e.getMessage()) .build(); exchange.getIn().setBody(response); return; } final JsonPrintingResultRequest response = JsonPrintingResultRequest.builder() .processed(true) .build(); exchange.getIn().setBody(response); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-printingclient\src\main\java\de\metas\camel\externalsystems\PrintingClientCamelRoute.java
2
请完成以下Java代码
public final class Null { /** Singleton */ public static final Null NULL = new Null(); /** * @return true if given object is <code>null</code> or {@link #NULL}. */ public static final boolean isNull(final Object obj) { return obj == NULL || obj == null; } /** * Unbox {@value #NULL} object * * @param obj * @return <code>obj</code> or <code>null</code> */ public static final Object unbox(final Object obj) { return obj == NULL ? null : obj; } /** * Box <code>null</code> to {@link #NULL}. * * @param obj
* @return <code>obj</code> or {@link #NULL} if the <code>obj</code> was <code>null</code>; this method never returns <code>null</code>. */ @NonNull public static final Object box(@Nullable final Object obj) { return obj == null ? NULL : obj; } private Null() { } /** * @return the string {@code "NULL"}. */ @Override public String toString() { return "NULL"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Null.java
1
请完成以下Java代码
public class PurchaseCandidateCreatedEvent extends PurchaseCandidateEvent { public static PurchaseCandidateCreatedEvent cast(@NonNull final PurchaseCandidateEvent event) { return (PurchaseCandidateCreatedEvent)event; } public static final String TYPE = "PurchaseCandidateCreatedEvent"; /** * If the purchase candidate is created according a {@link PurchaseCandidateRequestedEvent}, then this is the ID of the supply candidate the new purchase candidate belongs to; * Otherwise its value is <= 1. */ private final int supplyCandidateRepoId; private final SupplyRequiredDescriptor supplyRequiredDescriptor; @JsonCreator @Builder public PurchaseCandidateCreatedEvent( @JsonProperty("eventDescriptor") @NonNull final EventDescriptor eventDescriptor,
@JsonProperty("purchaseCandidateRepoId") final int purchaseCandidateRepoId, @JsonProperty("purchaseMaterialDescriptor") @NonNull final MaterialDescriptor purchaseMaterialDescriptor, @JsonProperty("supplyRequiredDescriptor") @Nullable final SupplyRequiredDescriptor supplyRequiredDescriptor, @JsonProperty("supplyCandidateRepoId") final int supplyCandidateRepoId, @JsonProperty("vendorId") final int vendorId) { super(purchaseMaterialDescriptor, null, eventDescriptor, purchaseCandidateRepoId, vendorId); this.supplyCandidateRepoId = supplyCandidateRepoId; this.supplyRequiredDescriptor = supplyRequiredDescriptor; } @Override public String getEventName() {return TYPE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\purchase\PurchaseCandidateCreatedEvent.java
1
请在Spring Boot框架中完成以下Java代码
public class ResponseStatusRestController { @GetMapping("/teapot") @ResponseStatus(HttpStatus.I_AM_A_TEAPOT) public void teaPot() { } @GetMapping("empty") @ResponseStatus(HttpStatus.NO_CONTENT) public void emptyResponse() { } @GetMapping("empty-no-responsestatus") public void emptyResponseWithoutResponseStatus() { } @PostMapping("create") @ResponseStatus(HttpStatus.CREATED)
public Book createEntity() { // here we would create and persist an entity int randomInt = ThreadLocalRandom.current() .nextInt(1, 100); Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); return entity; } @PostMapping("create-no-responsestatus") public Book createEntityWithoutResponseStatus() { // here we would create and persist an entity int randomInt = ThreadLocalRandom.current() .nextInt(1, 100); Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); return entity; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\web\controller\ResponseStatusRestController.java
2
请完成以下Java代码
public class SwitchingToStreamingResponses { public static void main(String[] args) { var client = Client.getClient(); List<ChatMessage> history = new ArrayList<>(); history.add(SystemMessage.of( "You are a helpful travel assistant. Answer in at least 150 words." )); try (Scanner scanner = new Scanner(System.in)) { while (true) { System.out.print("\nYou: "); String input = scanner.nextLine(); if (input == null || input.isBlank()) { continue; } if ("exit".equalsIgnoreCase(input.trim())) { break; } history.add(UserMessage.of(input)); ChatRequest.ChatRequestBuilder chatRequestBuilder = ChatRequest.builder().model(Client.CHAT_MODEL); for (ChatMessage message : history) { chatRequestBuilder.message(message); } ChatRequest chatRequest = chatRequestBuilder.build(); CompletableFuture<Stream<Chat>> chatStreamFuture =
client.chatCompletions().createStream(chatRequest); Stream<Chat> chatStream = chatStreamFuture.join(); StringBuilder replyBuilder = new StringBuilder(); chatStream.forEach(chunk -> { String content = chunk.firstContent(); replyBuilder.append(content); System.out.print(content); }); String reply = replyBuilder.toString(); history.add(AssistantMessage.of(reply)); } } } }
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\simpleopenai\SwitchingToStreamingResponses.java
1
请完成以下Java代码
public static boolean equals(@Nullable AttributesIncludedTabDataField field1, @Nullable AttributesIncludedTabDataField field2) { return Objects.equals(field1, field2); } public AttributesIncludedTabDataField withDateValue(@Nullable LocalDate valueDate) { Check.assumeEquals(valueType, AttributeValueType.DATE, "Expected DATE type: {}", this); return toBuilder().clearValues().valueDate(valueDate).build(); } public AttributesIncludedTabDataField withListValue(@Nullable String valueString, @Nullable AttributeValueId valueItemId) { Check.assumeEquals(valueType, AttributeValueType.LIST, "Expected list type: {}", this); return toBuilder().clearValues().valueString(valueString).valueItemId(valueItemId).build(); } public AttributesIncludedTabDataField withNumberValue(@Nullable Integer valueInt)
{ return withNumberValue(valueInt != null ? BigDecimal.valueOf(valueInt) : null); } public AttributesIncludedTabDataField withNumberValue(@Nullable BigDecimal valueNumber) { Check.assumeEquals(valueType, AttributeValueType.NUMBER, "Expected NUMBER type: {}", this); return toBuilder().clearValues().valueNumber(valueNumber).build(); } public AttributesIncludedTabDataField withStringValue(@Nullable String valueString) { Check.assumeEquals(valueType, AttributeValueType.STRING, "Expected STRING type: {}", this); return toBuilder().clearValues().valueString(valueString).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\attributes_included_tab\data\AttributesIncludedTabDataField.java
1
请完成以下Java代码
public class SecurityTools { public static final String ALGORITHM = "AES/ECB/PKCS5Padding"; public static SecurityResp valid(SecurityReq req) { SecurityResp resp=new SecurityResp(); String pubKey=req.getPubKey(); String aesKey=req.getAesKey(); String data=req.getData(); String signData=req.getSignData(); RSA rsa=new RSA(null, Base64Decoder.decode(pubKey)); Sign sign= new Sign(SignAlgorithm.SHA1withRSA,null,pubKey); byte[] decryptAes = rsa.decrypt(aesKey, KeyType.PublicKey); //log.info("rsa解密后的秘钥"+ Base64Encoder.encode(decryptAes)); AES aes = SecureUtil.aes(decryptAes); String dencrptValue =aes.decryptStr(data); //log.info("解密后报文"+dencrptValue); resp.setData(JSONObject.parseObject(dencrptValue)); boolean verify = sign.verify(dencrptValue.getBytes(), Base64Decoder.decode(signData)); resp.setSuccess(verify); return resp; } public static SecuritySignResp sign(SecuritySignReq req) { SecretKey secretKey = SecureUtil.generateKey(ALGORITHM); byte[] key= secretKey.getEncoded(); String prikey=req.getPrikey();
String data=req.getData(); AES aes = SecureUtil.aes(key); aes.getSecretKey().getEncoded(); String encrptData =aes.encryptBase64(data); RSA rsa=new RSA(prikey,null); byte[] encryptAesKey = rsa.encrypt(secretKey.getEncoded(), KeyType.PrivateKey); //log.info(("rsa加密过的秘钥=="+Base64Encoder.encode(encryptAesKey)); Sign sign= new Sign(SignAlgorithm.SHA1withRSA,prikey,null); byte[] signed = sign.sign(data.getBytes()); //log.info(("签名数据===》》"+Base64Encoder.encode(signed)); SecuritySignResp resp=new SecuritySignResp(); resp.setAesKey(Base64Encoder.encode(encryptAesKey)); resp.setData(encrptData); resp.setSignData(Base64Encoder.encode(signed)); return resp; } public static MyKeyPair generateKeyPair(){ KeyPair keyPair= SecureUtil.generateKeyPair(SignAlgorithm.SHA1withRSA.getValue(),2048); String priKey= Base64Encoder.encode(keyPair.getPrivate().getEncoded()); String pubkey= Base64Encoder.encode(keyPair.getPublic().getEncoded()); MyKeyPair resp=new MyKeyPair(); resp.setPriKey(priKey); resp.setPubKey(pubkey); return resp; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\security\SecurityTools.java
1
请在Spring Boot框架中完成以下Java代码
Queue messagesQueue() { return QueueBuilder.durable(QUEUE_MESSAGES) .withArgument("x-dead-letter-exchange", DLX_EXCHANGE_MESSAGES) .build(); } @Bean FanoutExchange deadLetterExchange() { return new FanoutExchange(DLX_EXCHANGE_MESSAGES); } @Bean Queue deadLetterQueue() { return QueueBuilder.durable(QUEUE_MESSAGES_DLQ).build(); }
@Bean Binding deadLetterBinding() { return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()); } @Bean DirectExchange messagesExchange() { return new DirectExchange(EXCHANGE_MESSAGES); } @Bean Binding bindingMessages() { return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES); } }
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\errorhandling\configuration\DLXCustomAmqpConfiguration.java
2
请完成以下Java代码
private Group getSingleGroup() { if (groups.size() > 1) { throw new AdempiereException("Not a single group: " + this); } return groups.get(0); } public Quantity getSingleQuantity() { return getSingleGroup().getQty(); } @Value public static class Group { public enum Type { ATTRIBUTE_SET, OTHER_STORAGE_KEYS, ALL_STORAGE_KEYS } ProductId productId; Quantity qty; Type type;
ImmutableAttributeSet attributes; @Builder public Group( @NonNull final Group.Type type, @NonNull final ProductId productId, @NonNull final Quantity qty, @Nullable final ImmutableAttributeSet attributes) { this.type = type; this.productId = productId; this.qty = qty; this.attributes = CoalesceUtil.coalesce(attributes, ImmutableAttributeSet.EMPTY); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\adapter\AvailabilityInfoResultForWebui.java
1
请完成以下Java代码
private BPartnerId getVendorIdOrNull(@Nullable final BPartnerId vendorId) { if (vendorId == null) { return null; } final I_C_BPartner bp = bpartnerDAO.getById(vendorId); //As per field validation rule, only allow active BPs marked as vendor final boolean isValidVendor = bp.isActive() && !bp.isSummary() && bp.isVendor(); if (!isValidVendor) { throw new AdempiereException("@NotFound@ @C_BP_Vendor_ID@"); } return vendorId; } @Nullable private UserId getSalesRepIdOrNull(@Nullable final UserId salesRepId) { if (salesRepId == null) { return null; } final I_AD_User user = userDAO.getById(salesRepId); //As per field validation rule, only allow AD_User.IsSystemUser = 'Y' as sales rep final boolean isValidSalesRep = user.isActive() && user.isSystemUser(); if (!isValidSalesRep) { throw new AdempiereException("@NotFound@ @SalesRep_ID@"); } return salesRepId; } @Nullable private ProductId resolveProductIdOrNull(final @Nullable ExternalIdentifier productIdentifier, @NonNull final OrgId orgId) { if (productIdentifier == null) { return null; } final ProductMasterDataProvider.ProductInfo productInfo = productMasterDataProvider.getProductInfo(productIdentifier, orgId); if (productInfo == null)
{ throw new AdempiereException("@NotFound@ @M_Product_ID@"); } return productInfo.getProductId(); } @Nullable private UserId resolveUserIdOrNull(final @Nullable ExternalIdentifier userIdentifier, @NonNull final OrgId orgId, @NonNull final String fieldName) { if (userIdentifier == null) { return null; } return bPartnerMasterdataProvider.resolveUserExternalIdentifier(orgId, userIdentifier) .orElseThrow(() -> new AdempiereException("@NotFound@ @" + fieldName + "@")); } @Nullable private BPartnerId resolveBPartnerIdOrNull(final @Nullable ExternalIdentifier bpartnerIdentifier, @NonNull final OrgId orgId, @NonNull final String fieldName) { if (bpartnerIdentifier == null) { return null; } return bPartnerMasterdataProvider.resolveBPartnerExternalIdentifier(orgId, bpartnerIdentifier) .orElseThrow(() -> new AdempiereException("@NotFound@ @" + fieldName + "@")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\request\RequestRestService.java
1
请完成以下Java代码
protected void doCommit(DefaultTransactionStatus status) { @SuppressWarnings(UNCHECKED) KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) status.getTransaction(); KafkaResourceHolder<K, V> resourceHolder = txObject.getResourceHolder(); if (resourceHolder != null) { resourceHolder.commit(); } } @Override protected void doRollback(DefaultTransactionStatus status) { @SuppressWarnings(UNCHECKED) KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) status.getTransaction(); KafkaResourceHolder<K, V> resourceHolder = txObject.getResourceHolder(); if (resourceHolder != null) { resourceHolder.rollback(); } } @Override protected void doSetRollbackOnly(DefaultTransactionStatus status) { @SuppressWarnings(UNCHECKED) KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) status.getTransaction(); KafkaResourceHolder<K, V> kafkaResourceHolder = txObject.getResourceHolder(); if (kafkaResourceHolder != null) { kafkaResourceHolder.setRollbackOnly(); } } @Override protected void doCleanupAfterCompletion(Object transaction) { @SuppressWarnings(UNCHECKED) KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) transaction; TransactionSynchronizationManager.unbindResource(getProducerFactory()); KafkaResourceHolder<K, V> kafkaResourceHolder = txObject.getResourceHolder(); if (kafkaResourceHolder != null) { kafkaResourceHolder.close(); kafkaResourceHolder.clear(); } } /** * Kafka transaction object, representing a KafkaResourceHolder. Used as transaction object by * KafkaTransactionManager. * @see KafkaResourceHolder */ private static class KafkaTransactionObject<K, V> implements SmartTransactionObject {
private @Nullable KafkaResourceHolder<K, V> resourceHolder; KafkaTransactionObject() { } public void setResourceHolder(@Nullable KafkaResourceHolder<K, V> resourceHolder) { this.resourceHolder = resourceHolder; } public @Nullable KafkaResourceHolder<K, V> getResourceHolder() { return this.resourceHolder; } @Override public boolean isRollbackOnly() { return this.resourceHolder != null && this.resourceHolder.isRollbackOnly(); } @Override public void flush() { // no-op } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\transaction\KafkaTransactionManager.java
1
请完成以下Java代码
public static ConsistentHashExchangeBuilder consistentHashExchange(String name) { return new ConsistentHashExchangeBuilder(name); } /** * An {@link ExchangeBuilder} extension for the {@link ConsistentHashExchange}. * * @since 3.2 */ public static final class ConsistentHashExchangeBuilder extends BaseExchangeBuilder<ConsistentHashExchangeBuilder> { /** * Construct an instance of the builder for {@link ConsistentHashExchange}. * * @param name the exchange name * @see ExchangeTypes */ public ConsistentHashExchangeBuilder(String name) { super(name, ExchangeTypes.CONSISTENT_HASH); }
public ConsistentHashExchangeBuilder hashHeader(String headerName) { withArgument("hash-header", headerName); return this; } public ConsistentHashExchangeBuilder hashProperty(String propertyName) { withArgument("hash-property", propertyName); return this; } @Override @SuppressWarnings("unchecked") public ConsistentHashExchange build() { return configureExchange( new ConsistentHashExchange(this.name, this.durable, this.autoDelete, getArguments())); } } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\ExchangeBuilder.java
1
请完成以下Java代码
private void init() { statsFactory.createGauge("edqsMapGauges", "stringPoolSize", TbStringPool.getPool(), Map::size); statsFactory.createGauge("edqsMapGauges", "bytePoolSize", TbBytePool.getPool(), Map::size); statsFactory.createGauge("edqsMapGauges", "tenantReposSize", DefaultEdqsRepository.getRepos(), Map::size); } @Override public void reportAdded(ObjectType objectType) { getObjectGauge(objectType).incrementAndGet(); } @Override public void reportRemoved(ObjectType objectType) { getObjectGauge(objectType).decrementAndGet(); } @Override public void reportEntityDataQuery(TenantId tenantId, EntityDataQuery query, long timingNanos) { checkTiming(tenantId, query, timingNanos); getTimer("entityDataQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS); } @Override public void reportEntityCountQuery(TenantId tenantId, EntityCountQuery query, long timingNanos) { checkTiming(tenantId, query, timingNanos); getTimer("entityCountQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS); } @Override public void reportEdqsDataQuery(TenantId tenantId, EntityDataQuery query, long timingNanos) { checkTiming(tenantId, query, timingNanos); getTimer("edqsDataQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS); } @Override public void reportEdqsCountQuery(TenantId tenantId, EntityCountQuery query, long timingNanos) { checkTiming(tenantId, query, timingNanos); getTimer("edqsCountQueryTimer").record(timingNanos, TimeUnit.NANOSECONDS); } @Override public void reportStringCompressed() { getCounter("stringsCompressed").increment(); } @Override
public void reportStringUncompressed() { getCounter("stringsUncompressed").increment(); } private void checkTiming(TenantId tenantId, EntityCountQuery query, long timingNanos) { double timingMs = timingNanos / 1000_000.0; String queryType = query instanceof EntityDataQuery ? "data" : "count"; if (timingMs < slowQueryThreshold) { log.debug("[{}] Executed " + queryType + " query in {} ms: {}", tenantId, timingMs, query); } else { log.warn("[{}] Executed slow " + queryType + " query in {} ms: {}", tenantId, timingMs, query); } } private StatsTimer getTimer(String name) { return timers.computeIfAbsent(name, __ -> statsFactory.createStatsTimer("edqsTimers", name)); } private StatsCounter getCounter(String name) { return counters.computeIfAbsent(name, __ -> statsFactory.createStatsCounter("edqsCounters", name)); } private AtomicInteger getObjectGauge(ObjectType objectType) { return objectCounters.computeIfAbsent(objectType, type -> statsFactory.createGauge("edqsGauges", "objectsCount", new AtomicInteger(), "objectType", type.name())); } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\stats\DefaultEdqsStatsService.java
1
请在Spring Boot框架中完成以下Java代码
public class EventBusMonitoringService { @NonNull private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); @NonNull private final PerformanceMonitoringService perfMonService; public boolean isMonitorIncomingEvents() { return sysConfigBL.getBooleanValue("de.metas.event.MonitorIncomingEvents", false); } public void addInfosAndMonitorSpan( @NonNull final Event event, @NonNull final Topic topic, @NonNull final Consumer<Event> enqueueEvent) { final Event.Builder eventToSendBuilder = event.toBuilder(); final PerformanceMonitoringService.Metadata request = PerformanceMonitoringService.Metadata.builder() .type(de.metas.monitoring.adapter.PerformanceMonitoringService.Type.EVENTBUS_REMOTE_ENDPOINT) .className("EventBus") .functionName("enqueueEvent") .label("de.metas.event.distributed-event.senderId", event.getSenderId()) .label("de.metas.event.distributed-event.topicName", topic.getName()) .build();
perfMonService.monitor( () -> enqueueEvent.accept(eventToSendBuilder.build()), request); } public void extractInfosAndMonitor( @NonNull final Event event, @NonNull final Topic topic, @NonNull final Runnable processEvent) { final PerformanceMonitoringService.Metadata metadata = PerformanceMonitoringService.Metadata.builder() .className("RabbitMQEventBusRemoteEndpoint") .functionName("onEvent") .type(de.metas.monitoring.adapter.PerformanceMonitoringService.Type.EVENTBUS_REMOTE_ENDPOINT) .label("de.metas.event.remote-event.senderId", event.getSenderId()) .label("de.metas.event.remote-event.topicName", topic.getName()) .build(); perfMonService.monitor( processEvent, metadata); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\EventBusMonitoringService.java
2
请完成以下Java代码
public static void main (String[] args) { Adempiere.startupEnvironment(true); JFrame frame = new JFrame("test"); frame.setVisible(true); String text = "<html><p>this is a line<br>with <b>bold</> info</html>"; int i = 0; while (true) { HTMLEditor ed = new HTMLEditor (frame, "heading " + ++i, text, true); text = ed.getHtmlText(); } } // main // metas: begin public HTMLEditor (Frame owner, String title, String htmlText, boolean editable, GridField gridField) { super (owner, title == null ? Msg.getMsg(Env.getCtx(), "Editor") : title, true); BoilerPlateMenu.createFieldMenu(editorPane, null, gridField); init(owner, htmlText, editable); } // metas: end } // HTMLEditor /****************************************************************************** * HTML Editor Menu Action */ class HTMLEditor_MenuAction { public HTMLEditor_MenuAction(String name, HTMLEditor_MenuAction[] subMenus) { m_name = name; m_subMenus = subMenus; } public HTMLEditor_MenuAction(String name, String actionName) { m_name = name; m_actionName = actionName; } public HTMLEditor_MenuAction(String name, Action action) { m_name = name; m_action = action; } private String m_name; private String m_actionName; private Action m_action; private HTMLEditor_MenuAction[] m_subMenus;
public boolean isSubMenu() { return m_subMenus != null; } public boolean isAction() { return m_action != null; } public String getName() { return m_name; } public HTMLEditor_MenuAction[] getSubMenus() { return m_subMenus; } public String getActionName() { return m_actionName; } public Action getAction() { return m_action; } } // MenuAction
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\HTMLEditor.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override @RunOutOfTrx // each invoice is processed in its own transaction protected String doIt() throws Exception { final IQueryFilter<I_C_Invoice_Candidate> selectedICsFilter = getProcessInfo().getQueryFilterOrElseFalse(); logger.debug("selectedICsFilter={}", selectedICsFilter); Loggables.withLogger(logger, Level.DEBUG).addLog("Processing sales order InvoiceCandidates"); final Iterator<InvoiceCandidateId> salesOrderIcIds = createInvoiceCandidateIdIterator(selectedICsFilter); final Result result = processInvoiceCandidates(salesOrderIcIds); Loggables.withLogger(logger, Level.DEBUG).addLog("Processed {} InvoiceCandidates; anyException={}", result.getCounter(), result.isAnyException()); return MSG_OK; } private Iterator<InvoiceCandidateId> createInvoiceCandidateIdIterator(@NonNull final IQueryFilter<I_C_Invoice_Candidate> selectedICsFilter) { final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder = queryBL .createQueryBuilder(I_C_Invoice_Candidate.class) .addOnlyActiveRecordsFilter() .filter(selectedICsFilter); final Iterator<InvoiceCandidateId> icIds = queryBuilder .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .setOption(IQuery.OPTION_IteratorBufferSize, 1000) .iterateIds(InvoiceCandidateId::ofRepoId); return icIds; } private Result processInvoiceCandidates(@NonNull final Iterator<InvoiceCandidateId> invoiceCandidateIds) { int counter = 0; boolean anyException = false; while (invoiceCandidateIds.hasNext()) { final InvoiceCandidateId invoiceCandidateId = invoiceCandidateIds.next(); try (final MDCCloseable ignore = TableRecordMDC.putTableRecordReference(I_C_Invoice_Candidate.Table_Name, invoiceCandidateId)) { trxManager.runInNewTrx(() -> { logger.debug("Processing invoiceCandidate");
final I_C_Invoice_Candidate invoiceCandidateRecord = invoiceCandDAO.getById(invoiceCandidateId); invoiceCandidateFacadeService.syncICToCommissionInstance(invoiceCandidateRecord, false/* candidateDeleted */); }); counter++; } catch (final RuntimeException e) { anyException = true; final AdIssueId adIssueId = errorManager.createIssue(e); Loggables.withLogger(logger, Level.DEBUG) .addLog("C_Invoice_Candidate_ID={}: Caught {} and created AD_Issue_ID={}; exception-message={}", invoiceCandidateId.getRepoId(), e.getClass(), adIssueId.getRepoId(), e.getLocalizedMessage()); } } return new Result(counter, anyException); } @Value private static class Result { int counter; boolean anyException; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\process\C_Invoice_Candidate_CreateOrUpdateCommissionInstance.java
1
请完成以下Java代码
private void doResume(Transaction tx) { if (tx != null) { try { transactionManager.resume(tx); } catch (SystemException e) { throw new TransactionException("Unable to resume transaction", e); } catch (InvalidTransactionException e) { throw new TransactionException("Unable to resume transaction", e); } } } private void doCommit() { try { transactionManager.commit(); } catch (HeuristicMixedException e) { throw new TransactionException("Unable to commit transaction", e); } catch (HeuristicRollbackException e) { throw new TransactionException("Unable to commit transaction", e); } catch (RollbackException e) { throw new TransactionException("Unable to commit transaction", e); } catch (SystemException e) { throw new TransactionException("Unable to commit transaction", e); } catch (RuntimeException e) { doRollback(true, e); throw e; } catch (Error e) { doRollback(true, e); throw e; } } private void doRollback(boolean isNew, Throwable originalException) { Throwable rollbackEx = null; try { if (isNew) { transactionManager.rollback(); } else { transactionManager.setRollbackOnly(); } } catch (SystemException e) { LOGGER.debug("Error when rolling back transaction", e); } catch (RuntimeException e) { rollbackEx = e; throw e; } catch (Error e) { rollbackEx = e; throw e; } finally { if (rollbackEx != null && originalException != null) { LOGGER.error("Error when rolling back transaction, original exception was:", originalException);
} } } private static class TransactionException extends RuntimeException { private static final long serialVersionUID = 1L; private TransactionException() {} private TransactionException(String s) { super(s); } private TransactionException(String s, Throwable throwable) { super(s, throwable); } private TransactionException(Throwable throwable) { super(throwable); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\JtaTransactionInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public class User { private String firstName; private String lastName; private int age; @Id private int id; public User() { } public User(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public User(String firstName, String lastName, int age, int id) { this(firstName, lastName, age); this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName;
} public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query-3\src\main\java\com\baeldung\spring\data\jpa\collectionsvsstream\User.java
2
请完成以下Java代码
public static RemoteToLocalSyncResult noChanges(@NonNull final DataRecord dataRecord) { return RemoteToLocalSyncResult.builder() .synchedDataRecord(dataRecord) .remoteToLocalStatus(RemoteToLocalStatus.NO_CHANGES) .build(); } public static RemoteToLocalSyncResult error(@NonNull final DataRecord datarecord, String errorMessage) { return RemoteToLocalSyncResult.builder() .synchedDataRecord(datarecord) .remoteToLocalStatus(RemoteToLocalStatus.ERROR) .errorMessage(errorMessage) .build(); } public enum RemoteToLocalStatus { /** See {@link RemoteToLocalSyncResult#deletedOnRemotePlatform(DataRecord)}. */ DELETED_ON_REMOTE_PLATFORM, /** See {@link RemoteToLocalSyncResult#notYetAddedToRemotePlatform(DataRecord)}. */ NOT_YET_ADDED_TO_REMOTE_PLATFORM, /** See {@link RemoteToLocalSyncResult#obtainedRemoteId(DataRecord)}. */ OBTAINED_REMOTE_ID,
/** See {@link RemoteToLocalSyncResult#obtainedRemoteEmail(DataRecord)}. */ OBTAINED_REMOTE_EMAIL, /** See {@link RemoteToLocalSyncResult#obtainedEmailBounceInfo(DataRecord)}. */ OBTAINED_EMAIL_BOUNCE_INFO, OBTAINED_NEW_CONTACT_PERSON, NO_CHANGES, OBTAINED_OTHER_REMOTE_DATA, ERROR; } RemoteToLocalStatus remoteToLocalStatus; String errorMessage; DataRecord synchedDataRecord; @Builder private RemoteToLocalSyncResult( @NonNull final DataRecord synchedDataRecord, @Nullable final RemoteToLocalStatus remoteToLocalStatus, @Nullable final String errorMessage) { this.synchedDataRecord = synchedDataRecord; this.remoteToLocalStatus = remoteToLocalStatus; this.errorMessage = errorMessage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\RemoteToLocalSyncResult.java
1
请在Spring Boot框架中完成以下Java代码
public class MainApplication { // Running the application should result in // org.springframework.orm.ObjectOptimisticLockingFailureException private final InventoryService inventoryService; public MainApplication(InventoryService inventoryService) { this.inventoryService = inventoryService; } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() { return args -> {
System.out.println("Triggering the first transaction ..."); Inventory firstInventory = inventoryService.firstTransactionFetchesAndReturn(); System.out.println("First transaction committed successfully ..."); System.out.println("Triggering the second transaction ..."); inventoryService.secondTransactionFetchesAndReturn(); System.out.println("Second transaction committed successfully ..."); // AT THIS POINT, THE firstInventory IS DETACHED firstInventory.setQuantity(firstInventory.getQuantity() - 1); System.out.println("Triggering the third transaction ..."); inventoryService.thirdTransactionMergesAndUpdates(firstInventory); System.out.println("Third transaction committed successfully ..."); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootVersionedOptimisticLockingAndDettachedEntity\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } @Override public String getState() { return null; } @Override public Date getInProgressStartTime() { return null; } @Override public String getInProgressStartedBy() { return null; } @Override public Date getClaimTime() { return null; } @Override public String getClaimedBy() { return null; }
@Override public Date getSuspendedTime() { return null; } @Override public String getSuspendedBy() { return null; } @Override public Date getInProgressStartDueDate() { return null; } @Override public void setInProgressStartDueDate(Date inProgressStartDueDate) { // nothing } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntity.java
1
请在Spring Boot框架中完成以下Java代码
public void setDesc(String desc) { this.desc = desc; } public static Map<String, Map<String, Object>> toMap() { TradeStatusEnum[] ary = TradeStatusEnum.values(); Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>(); for (int num = 0; num < ary.length; num++) { Map<String, Object> map = new HashMap<String, Object>(); String key = ary[num].name(); map.put("desc", ary[num].getDesc()); enumMap.put(key, map); } return enumMap; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static List toList() { TradeStatusEnum[] ary = TradeStatusEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("desc", ary[i].getDesc()); map.put("name", ary[i].name()); list.add(map); } return list; } public static TradeStatusEnum getEnum(String name) {
TradeStatusEnum[] arry = TradeStatusEnum.values(); for (int i = 0; i < arry.length; i++) { if (arry[i].name().equalsIgnoreCase(name)) { return arry[i]; } } return null; } /** * 取枚举的json字符串 * * @return */ public static String getJsonStr() { TradeStatusEnum[] enums = TradeStatusEnum.values(); StringBuffer jsonStr = new StringBuffer("["); for (TradeStatusEnum senum : enums) { if (!"[".equals(jsonStr.toString())) { jsonStr.append(","); } jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}"); } jsonStr.append("]"); return jsonStr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\enums\TradeStatusEnum.java
2
请完成以下Java代码
public ProcessInstanceMigrationValidationResult validateMigrationForProcessInstancesOfProcessDefinition(String processDefinitionId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { return commandExecutor.execute(new ProcessInstanceMigrationValidationCmd(processInstanceMigrationDocument, processDefinitionId)); } @Override public ProcessInstanceMigrationValidationResult validateMigrationForProcessInstancesOfProcessDefinition(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { return commandExecutor.execute(new ProcessInstanceMigrationValidationCmd(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, processInstanceMigrationDocument)); } @Override public void migrateProcessInstance(String processInstanceId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { commandExecutor.execute(new ProcessInstanceMigrationCmd(processInstanceId, processInstanceMigrationDocument)); } @Override public void migrateProcessInstancesOfProcessDefinition(String processDefinitionId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { commandExecutor.execute(new ProcessInstanceMigrationCmd(processInstanceMigrationDocument, processDefinitionId)); } @Override public void migrateProcessInstancesOfProcessDefinition(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { commandExecutor.execute(new ProcessInstanceMigrationCmd(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, processInstanceMigrationDocument)); } @Override
public Batch batchMigrateProcessInstancesOfProcessDefinition(String processDefinitionId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { return commandExecutor.execute(new ProcessInstanceMigrationBatchCmd(processDefinitionId, processInstanceMigrationDocument)); } @Override public Batch batchMigrateProcessInstancesOfProcessDefinition(String processDefinitionKey, int processDefinitionVersion, String processDefinitionTenantId, ProcessInstanceMigrationDocument processInstanceMigrationDocument) { return commandExecutor.execute(new ProcessInstanceMigrationBatchCmd(processDefinitionKey, processDefinitionVersion, processDefinitionTenantId, processInstanceMigrationDocument)); } @Override public ProcessInstanceBatchMigrationResult getResultsOfBatchProcessInstanceMigration(String migrationBatchId) { return commandExecutor.execute(new GetProcessInstanceMigrationBatchResultCmd(migrationBatchId)); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessMigrationServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ConsumerService { private final ReactiveKafkaConsumerTemplate<String, String> reactiveKafkaConsumerTemplate; @PostConstruct public Flux<String> consumeRecord() { return reactiveKafkaConsumerTemplate.receive() .map(ReceiverRecord::value) .doOnNext(msg -> log.info("Received: {}", msg)); } public Flux<String> consumeAsABatch() { return reactiveKafkaConsumerTemplate.receive() .buffer(2) .flatMap(messages -> Flux.fromStream(messages.stream() .map(ReceiverRecord::value)));
} public Flux<String> consumeWithLimit() { return reactiveKafkaConsumerTemplate.receive() .limitRate(2) .map(ReceiverRecord::value); } public Flux<String> consumeWithRetryWithBackOff(AtomicInteger attempts) { return reactiveKafkaConsumerTemplate.receive() .flatMap(msg -> attempts.incrementAndGet() < 3 ? Flux.error(new RuntimeException("Failure")) : Flux.just(msg)) .retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(1))) .map(ReceiverRecord::value); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-kafka\src\main\java\com\baeldung\consumer\ConsumerService.java
2
请完成以下Java代码
public @Nullable Exception getBindingsFailedException() { return this.bindingsFailedException; } @Override public void start() { this.lock.lock(); try { if (!this.running) { if (this.stopInvoked) { // redeclare auto-delete queue this.stopInvoked = false; onCreate(null); } if (this.ownContainer) { this.container.start(); } this.running = true; } } finally { this.lock.unlock(); } } @Override public void stop() { this.lock.lock(); try { if (this.running) { if (this.ownContainer) { this.container.stop(); } this.running = false; this.stopInvoked = true; } } finally { this.lock.unlock(); } } @Override public boolean isRunning() { this.lock.lock(); try { return this.running; } finally { this.lock.unlock(); } } @Override public int getPhase() { return this.phase; }
public void setPhase(int phase) { this.phase = phase; } @Override public boolean isAutoStartup() { return this.autoStartup; } public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; } @Override public void onMessage(Message message) { if (this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent(new BrokerEvent(this, message.getMessageProperties())); } else { if (logger.isWarnEnabled()) { logger.warn("No event publisher available for " + message + "; if the BrokerEventListener " + "is not defined as a bean, you must provide an ApplicationEventPublisher"); } } } @Override public void onCreate(@Nullable Connection connection) { this.bindingsFailedException = null; TopicExchange exchange = new TopicExchange("amq.rabbitmq.event"); try { this.admin.declareQueue(this.eventQueue); Arrays.stream(this.eventKeys).forEach(k -> { Binding binding = BindingBuilder.bind(this.eventQueue).to(exchange).with(k); this.admin.declareBinding(binding); }); } catch (Exception e) { logger.error("failed to declare event queue/bindings - is the plugin enabled?", e); this.bindingsFailedException = e; } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\core\BrokerEventListener.java
1
请完成以下Java代码
public JSONLookupValuesList getTemplates() { userSession.assertLoggedIn(); return MADBoilerPlate.streamAllReadable(userSession.getUserRolePermissions()) .map(adBoilerPlate -> JSONLookupValue.of(adBoilerPlate.getAD_BoilerPlate_ID(), adBoilerPlate.getName())) .collect(JSONLookupValuesList.collect()); } private void applyTemplate(final WebuiEmail email, final WebuiEmailBuilder newEmailBuilder, final LookupValue templateId) { final Properties ctx = Env.getCtx(); final MADBoilerPlate boilerPlate = MADBoilerPlate.get(ctx, templateId.getIdAsInt()); if (boilerPlate == null) { throw new AdempiereException("No template found for " + templateId);
} // // Attributes final BoilerPlateContext attributes = documentCollection.createBoilerPlateContext(email.getContextDocumentPath()); // // Subject final String subject = MADBoilerPlate.parseText(ctx, boilerPlate.getSubject(), true, attributes, ITrx.TRXNAME_None); newEmailBuilder.subject(subject); // Message newEmailBuilder.message(boilerPlate.getTextSnippetParsed(attributes)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\MailRestController.java
1
请完成以下Java代码
public <V extends Enum<V>> AttributeBuilder<V> enumAttribute(String attributeName, Class<V> enumType) { EnumAttributeBuilder<V> builder = new EnumAttributeBuilder<V>(attributeName, modelType, enumType); modelBuildOperations.add(builder); return builder; } public <V extends Enum<V>> AttributeBuilder<V> namedEnumAttribute(String attributeName, Class<V> enumType) { NamedEnumAttributeBuilder<V> builder = new NamedEnumAttributeBuilder<V>(attributeName, modelType, enumType); modelBuildOperations.add(builder); return builder; } public ModelElementType build() { model.registerType(modelType, instanceType); return modelType; } public ModelElementTypeBuilder abstractType() { modelType.setAbstract(true); return this; } public SequenceBuilder sequence() { SequenceBuilderImpl builder = new SequenceBuilderImpl(modelType); modelBuildOperations.add(builder); return builder; } public void buildTypeHierarchy(Model model) { // build type hierarchy
if(extendedType != null) { ModelElementTypeImpl extendedModelElementType = (ModelElementTypeImpl) model.getType(extendedType); if(extendedModelElementType == null) { throw new ModelException("Type "+modelType+" is defined to extend "+extendedType+" but no such type is defined."); } else { modelType.setBaseType(extendedModelElementType); extendedModelElementType.registerExtendingType(modelType); } } } public void performModelBuild(Model model) { for (ModelBuildOperation operation : modelBuildOperations) { operation.performModelBuild(model); } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\ModelElementTypeBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { private final UserRepository userRepository = new UserRepository(); @Operation(summary = "Get all users", description = "Retrieve a list of all users") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "List of users", content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))), @ApiResponse(responseCode = "500", description = "Internal server error") }) @GetMapping public ResponseEntity<List<User>> getAllUsers() { return ResponseEntity.ok() .body(userRepository.getAllUsers()); } @Operation(summary = "Create a new user", description = "Add a new user to the system") @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "User created", content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
@ApiResponse(responseCode = "400", description = "Invalid input") }) @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<User> createUser( @RequestBody(description = "User data", required = true, content = @Content(schema = @Schema(implementation = NewUser.class))) NewUser user) { return new ResponseEntity<>(userRepository.createUser(user), HttpStatus.CREATED); } @Operation(summary = "Get user by ID", description = "Retrieve a user by their unique ID") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "User found", content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))), @ApiResponse(responseCode = "404", description = "User not found") }) @GetMapping("/{id}") public ResponseEntity<User> getUserById(@PathVariable Integer id) { return ResponseEntity.ok() .body(userRepository.getUserById(id)); } }
repos\tutorials-master\spring-web-modules\spring-boot-rest-2\src\main\java\com\baeldung\hateoasvsswagger\UserController.java
2
请完成以下Java代码
public final ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } return ProcessPreconditionsResolution.accept(); } protected final void grantAccessToRecord() { userGroupRecordAccessService.grantAccess(RecordAccessGrantRequest.builder() .recordRef(getRecordRef()) .principal(getPrincipal()) .permissions(getPermissionsToGrant()) .issuer(PermissionIssuer.MANUAL) .requestedBy(getUserId()) .build()); } protected final void revokeAccessFromRecord() { final boolean revokeAllPermissions; final List<Access> permissionsToRevoke; final Access permission = getPermissionOrNull(); if (permission == null) { revokeAllPermissions = true; permissionsToRevoke = ImmutableList.of(); } else { revokeAllPermissions = false; permissionsToRevoke = ImmutableList.of(permission); } userGroupRecordAccessService.revokeAccess(RecordAccessRevokeRequest.builder() .recordRef(getRecordRef()) .principal(getPrincipal()) .revokeAllPermissions(revokeAllPermissions) .permissions(permissionsToRevoke) .issuer(PermissionIssuer.MANUAL) .requestedBy(getUserId()) .build()); } private Principal getPrincipal() { final PrincipalType principalType = PrincipalType.ofCode(principalTypeCode); if (PrincipalType.USER.equals(principalType)) { return Principal.userId(userId); } else if (PrincipalType.USER_GROUP.equals(principalType)) { return Principal.userGroupId(userGroupId); } else { throw new AdempiereException("@Unknown@ @PrincipalType@: " + principalType); } }
private Set<Access> getPermissionsToGrant() { final Access permission = getPermissionOrNull(); if (permission == null) { throw new FillMandatoryException(PARAM_PermissionCode); } if (Access.WRITE.equals(permission)) { return ImmutableSet.of(Access.READ, Access.WRITE); } else { return ImmutableSet.of(permission); } } private Access getPermissionOrNull() { if (Check.isEmpty(permissionCode)) { return null; } else { return Access.ofCode(permissionCode); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\process\UserGroupRecordAccess_Base.java
1
请完成以下Java代码
public VPanelFormFieldBuilder setHeader(String header) { this.header = header; return this; } private String getColumnName() { Check.assumeNotEmpty(columnName, "columnName not empty"); return columnName; } /** * @param columnName Will be the name of the GridField. */ public VPanelFormFieldBuilder setColumnName(String columnName) { this.columnName = columnName; return this; } private boolean isSameLine() { return sameLine; } /** * Default: {@link #DEFAULT_SameLine} * * @param sameLine If true, the new Field will be added in the same line. */ public VPanelFormFieldBuilder setSameLine(boolean sameLine) { this.sameLine = sameLine; return this; } private boolean isMandatory() { return mandatory; } /** * Default: {@link #DEFAULT_Mandatory} * * @param mandatory true if this field shall be marked as mandatory */ public VPanelFormFieldBuilder setMandatory(boolean mandatory) { this.mandatory = mandatory; return this; } private boolean isAutocomplete() { if (autocomplete != null) { return autocomplete; } // if Search, always auto-complete if (DisplayType.Search == displayType) { return true; } return false; } public VPanelFormFieldBuilder setAutocomplete(boolean autocomplete) { this.autocomplete = autocomplete; return this; } private int getAD_Column_ID()
{ // not set is allowed return AD_Column_ID; } /** * @param AD_Column_ID Column for lookups. */ public VPanelFormFieldBuilder setAD_Column_ID(int AD_Column_ID) { this.AD_Column_ID = AD_Column_ID; return this; } public VPanelFormFieldBuilder setAD_Column_ID(final String tableName, final String columnName) { return setAD_Column_ID(Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName).getAD_Column_ID()); } private EventListener getEditorListener() { // null allowed return editorListener; } /** * @param listener VetoableChangeListener that gets called if the field is changed. */ public VPanelFormFieldBuilder setEditorListener(EventListener listener) { this.editorListener = listener; return this; } public VPanelFormFieldBuilder setBindEditorToModel(boolean bindEditorToModel) { this.bindEditorToModel = bindEditorToModel; return this; } public VPanelFormFieldBuilder setReadOnly(boolean readOnly) { this.readOnly = readOnly; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFormFieldBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public Dept getDept(Long id) { return deptService.getById(id); } @Override @GetMapping(API_PREFIX + "/getDeptName") public String getDeptName(Long id) { return deptService.getById(id).getDeptName(); } @Override public String getDeptIds(String tenantId, String deptNames) { return deptService.getDeptIds(tenantId, deptNames); } @Override public List<String> getDeptNames(String deptIds) { return deptService.getDeptNames(deptIds); } @Override public String getPostIds(String tenantId, String postNames) { return postService.getPostIds(tenantId, postNames); } @Override public List<String> getPostNames(String postIds) { return postService.getPostNames(postIds); } @Override @GetMapping(API_PREFIX + "/getRole") public Role getRole(Long id) { return roleService.getById(id); } @Override public String getRoleIds(String tenantId, String roleNames) { return roleService.getRoleIds(tenantId, roleNames); } @Override @GetMapping(API_PREFIX + "/getRoleName") public String getRoleName(Long id) {
return roleService.getById(id).getRoleName(); } @Override public List<String> getRoleNames(String roleIds) { return roleService.getRoleNames(roleIds); } @Override @GetMapping(API_PREFIX + "/getRoleAlias") public String getRoleAlias(Long id) { return roleService.getById(id).getRoleAlias(); } @Override @GetMapping(API_PREFIX + "/tenant") public R<Tenant> getTenant(Long id) { return R.data(tenantService.getById(id)); } @Override @GetMapping(API_PREFIX + "/tenant-id") public R<Tenant> getTenant(String tenantId) { return R.data(tenantService.getByTenantId(tenantId)); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\feign\SysClient.java
2
请在Spring Boot框架中完成以下Java代码
public class Employee { @Id private int id; private String firstName; private String lastName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() {
return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
repos\tutorials-master\persistence-modules\hibernate-exceptions-2\src\main\java\com\baeldung\hibernate\noargumentforordinalparameter\Employee.java
2
请完成以下Java代码
public class FormPropertyImpl implements FormProperty { protected String id; protected String name; protected FormType type; protected boolean isRequired; protected boolean isReadable; protected boolean isWritable; protected String value; public FormPropertyImpl(FormPropertyHandler formPropertyHandler) { this.id = formPropertyHandler.getId(); this.name = formPropertyHandler.getName(); this.type = formPropertyHandler.getType(); this.isRequired = formPropertyHandler.isRequired(); this.isReadable = formPropertyHandler.isReadable(); this.isWritable = formPropertyHandler.isWritable(); } @Override public String getId() { return id; } @Override public String getName() { return name; } @Override public FormType getType() { return type; } @Override public String getValue() { return value; }
@Override public boolean isRequired() { return isRequired; } @Override public boolean isReadable() { return isReadable; } public void setValue(String value) { this.value = value; } @Override public boolean isWritable() { return isWritable; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\FormPropertyImpl.java
1
请完成以下Java代码
final class PackageableRowsIndex { public static PackageableRowsIndex of(final Collection<PackageableRow> rows) { return new PackageableRowsIndex(rows); } private final ImmutableMap<DocumentId, PackageableRow> rowsById; private final ImmutableListMultimap<ShipmentScheduleId, PackageableRow> rowsByShipmentScheduleId; private PackageableRowsIndex(final Collection<PackageableRow> rows) { rowsById = Maps.uniqueIndex(rows, PackageableRow::getId); rowsByShipmentScheduleId = rows.stream() .flatMap(row -> row.getShipmentScheduleIds() .stream() .map(shipmentScheduleId -> GuavaCollectors.entry(shipmentScheduleId, row))) .collect(GuavaCollectors.toImmutableListMultimap()); } public ImmutableMap<DocumentId, PackageableRow> getRowsIndexedById()
{ return rowsById; } private ImmutableList<PackageableRow> getRowsByShipmentScheduleId(@NonNull final ShipmentScheduleId shipmentScheduleId) { return rowsByShipmentScheduleId.get(shipmentScheduleId); } public ImmutableSet<DocumentId> getRowIdsByShipmentScheduleId(@NonNull final ShipmentScheduleId shipmentScheduleId) { return getRowsByShipmentScheduleId(shipmentScheduleId) .stream() .map(PackageableRow::getId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\PackageableRowsIndex.java
1
请完成以下Java代码
public char[] getPassword() { return null; } } private static final class CallbackHandlerImpl implements CallbackHandler { private final String userPrincipal; private final String password; private CallbackHandlerImpl(String userPrincipal, String password) { super(); this.userPrincipal = userPrincipal; this.password = password; } @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { if (callback instanceof NameCallback) {
NameCallback nc = (NameCallback) callback; nc.setName(this.userPrincipal); } else if (callback instanceof PasswordCallback) { PasswordCallback pc = (PasswordCallback) callback; pc.setPassword(this.password.toCharArray()); } else { throw new UnsupportedCallbackException(callback, "Unknown Callback"); } } } } }
repos\spring-security-main\kerberos\kerberos-client\src\main\java\org\springframework\security\kerberos\client\KerberosRestTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public String sendInlineMail() { MimeMessage message = null; try { message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo("888888@qq.com"); // 接收地址 helper.setSubject("一封带静态资源的邮件"); // 标题 helper.setText("<html><body>博客图:<img src='cid:img'/></body></html>", true); // 内容 // 传入附件 FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/img/sunshine.png")); helper.addInline("img", file); jms.send(message); return "发送成功"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } @RequestMapping("sendTemplateEmail") public String sendTemplateEmail(String code) { MimeMessage message = null;
try { message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo("888888@qq.com"); // 接收地址 helper.setSubject("邮件摸板测试"); // 标题 // 处理邮件模板 Context context = new Context(); context.setVariable("code", code); String template = templateEngine.process("emailTemplate", context); helper.setText(template, true); jms.send(message); return "发送成功"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } }
repos\SpringAll-master\22.Spring-Boot-Email\src\main\java\com\springboot\demo\controller\EmailController.java
2
请完成以下Java代码
public boolean isHorizontal() { return isHorizontalAttribute.getValue(this); } public void setHorizontal(boolean isHorizontal) { isHorizontalAttribute.setValue(this, isHorizontal); } public boolean isExpanded() { return isExpandedAttribute.getValue(this); } public void setExpanded(boolean isExpanded) { isExpandedAttribute.setValue(this, isExpanded); } public boolean isMarkerVisible() { return isMarkerVisibleAttribute.getValue(this); } public void setMarkerVisible(boolean isMarkerVisible) { isMarkerVisibleAttribute.setValue(this, isMarkerVisible); } public boolean isMessageVisible() { return isMessageVisibleAttribute.getValue(this); }
public void setMessageVisible(boolean isMessageVisible) { isMessageVisibleAttribute.setValue(this, isMessageVisible); } public ParticipantBandKind getParticipantBandKind() { return participantBandKindAttribute.getValue(this); } public void setParticipantBandKind(ParticipantBandKind participantBandKind) { participantBandKindAttribute.setValue(this, participantBandKind); } public BpmnShape getChoreographyActivityShape() { return choreographyActivityShapeAttribute.getReferenceTargetElement(this); } public void setChoreographyActivityShape(BpmnShape choreographyActivityShape) { choreographyActivityShapeAttribute.setReferenceTargetElement(this, choreographyActivityShape); } public BpmnLabel getBpmnLabel() { return bpmnLabelChild.getChild(this); } public void setBpmnLabel(BpmnLabel bpmnLabel) { bpmnLabelChild.setChild(this, bpmnLabel); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\bpmndi\BpmnShapeImpl.java
1
请完成以下Java代码
public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); } /** Get Rolle. @return Responsibility Role */ @Override public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Included Role. @param AD_Role_Included_ID Included Role */ @Override public void setAD_Role_Included_ID (int AD_Role_Included_ID) { if (AD_Role_Included_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Role_Included_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_Included_ID, Integer.valueOf(AD_Role_Included_ID)); } /** Get Included Role. @return Included Role */ @Override public int getAD_Role_Included_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_Included_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Role getIncluded_Role() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Included_Role_ID, org.compiere.model.I_AD_Role.class); } @Override public void setIncluded_Role(org.compiere.model.I_AD_Role Included_Role) { set_ValueFromPO(COLUMNNAME_Included_Role_ID, org.compiere.model.I_AD_Role.class, Included_Role); } /** Set Included Role. @param Included_Role_ID Included Role */ @Override public void setIncluded_Role_ID (int Included_Role_ID) {
if (Included_Role_ID < 1) set_ValueNoCheck (COLUMNNAME_Included_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_Included_Role_ID, Integer.valueOf(Included_Role_ID)); } /** Get Included Role. @return Included Role */ @Override public int getIncluded_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Included_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_Included.java
1
请在Spring Boot框架中完成以下Java代码
public SingleConnectionFactory singleConnectionFactory(@Qualifier("pooledConnectionFactory") PooledConnectionFactory pooledConnectionFactory) { SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory(); singleConnectionFactory.setTargetConnectionFactory(pooledConnectionFactory); return singleConnectionFactory; } /** * ActiveMQ为我们提供了一个PooledConnectionFactory,通过往里面注入一个ActiveMQConnectionFactory * 可以用来将Connection、Session和MessageProducer池化,这样可以大大的减少我们的资源消耗。 * 要依赖于 activemq-pool包 * * @param activeMQConnectionFactory 目标连接工厂 * @return Pooled连接工厂 */ @Bean(name = "pooledConnectionFactory") public PooledConnectionFactory pooledConnectionFactory(@Qualifier("targetConnectionFactory") ActiveMQConnectionFactory activeMQConnectionFactory) { PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(); pooledConnectionFactory.setConnectionFactory(activeMQConnectionFactory); pooledConnectionFactory.setMaxConnections(maxConnections); return pooledConnectionFactory; } /** * 商户通知队列模板 * * @param singleConnectionFactory 连接工厂 * @return 商户通知队列模板 */ @Bean(name = "notifyJmsTemplate") public JmsTemplate notifyJmsTemplate(@Qualifier("connectionFactory") SingleConnectionFactory singleConnectionFactory) { JmsTemplate notifyJmsTemplate = new JmsTemplate(); notifyJmsTemplate.setConnectionFactory(singleConnectionFactory); notifyJmsTemplate.setDefaultDestinationName(tradeQueueDestinationName); return notifyJmsTemplate; }
/** * 队列模板 * * @param singleConnectionFactory 连接工厂 * @return 队列模板 */ @Bean(name = "jmsTemplate") public JmsTemplate jmsTemplate(@Qualifier("connectionFactory") SingleConnectionFactory singleConnectionFactory) { JmsTemplate notifyJmsTemplate = new JmsTemplate(); notifyJmsTemplate.setConnectionFactory(singleConnectionFactory); notifyJmsTemplate.setDefaultDestinationName(orderQueryDestinationName); return notifyJmsTemplate; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\config\ActiveMqConfig.java
2
请完成以下Java代码
public void setInsertGroupMemberSql(String insertGroupMemberSql) { Assert.hasText(insertGroupMemberSql, "insertGroupMemberSql should have text"); this.insertGroupMemberSql = insertGroupMemberSql; } public void setDeleteGroupMemberSql(String deleteGroupMemberSql) { Assert.hasText(deleteGroupMemberSql, "deleteGroupMemberSql should have text"); this.deleteGroupMemberSql = deleteGroupMemberSql; } public void setGroupAuthoritiesSql(String groupAuthoritiesSql) { Assert.hasText(groupAuthoritiesSql, "groupAuthoritiesSql should have text"); this.groupAuthoritiesSql = groupAuthoritiesSql; } public void setDeleteGroupAuthoritySql(String deleteGroupAuthoritySql) { Assert.hasText(deleteGroupAuthoritySql, "deleteGroupAuthoritySql should have text"); this.deleteGroupAuthoritySql = deleteGroupAuthoritySql; } /** * Optionally sets the UserCache if one is in use in the application. This allows the * user to be removed from the cache after updates have taken place to avoid stale * data. * @param userCache the cache used by the AuthenticationManager. */ public void setUserCache(UserCache userCache) { Assert.notNull(userCache, "userCache cannot be null"); this.userCache = userCache; } /** * Sets whether the {@link #updatePassword(UserDetails, String)} method should * actually update the password. * <p> * Defaults to {@code false} to prevent accidental password updates that might produce * passwords that are too large for the current database schema. Users must explicitly * set this to {@code true} to enable password updates. * @param enableUpdatePassword {@code true} to enable password updates, {@code false} * otherwise. * @since 7.0 */ 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
请在Spring Boot框架中完成以下Java代码
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration { private static final Logger logger = LogManager.getLogger(ElasticsearchConfig.class); private static final String PROP_host = "metasfresh.elasticsearch.host"; private static final PropertyValueWithOrigin DEFAULT_host = PropertyValueWithOrigin.builder() .propertyName(PROP_host) .propertyValue("search:9200") .origin("default specified by " + ElasticsearchConfig.class) .build(); private final Environment environment; public ElasticsearchConfig(final Environment environment) {this.environment = environment;} @Override @Bean public @NonNull RestHighLevelClient elasticsearchClient() { PropertyValueWithOrigin host = getPropertyValueWithOrigin(PROP_host, environment); if (host.isBlankValue()) { host = DEFAULT_host; } logger.info("Config: {}", host); final ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo(host.getPropertyValue()) .build(); return RestClients.create(clientConfiguration).rest(); } @SuppressWarnings("SameParameterValue") private static PropertyValueWithOrigin getPropertyValueWithOrigin(final String propertyName, final Environment environment) { final String value = environment.getProperty(propertyName); final String origin = getPropertySourceName(propertyName, environment).orElse("?"); return PropertyValueWithOrigin.builder() .propertyName(propertyName) .propertyValue(value) .origin(origin) .build(); } private static Optional<String> getPropertySourceName(final String propertyName, final Environment environment) { if (environment instanceof AbstractEnvironment) { final MutablePropertySources propertySources = ((AbstractEnvironment)environment).getPropertySources(); for (final PropertySource<?> propertySource : propertySources) { final Object propertyValue = propertySource.getProperty(propertyName); if (propertyValue != null) { if (propertySource instanceof OriginLookup) { @SuppressWarnings({ "unchecked", "rawtypes" }) final Origin origin = ((OriginLookup)propertySource).getOrigin(propertyName); return Optional.of(origin.toString()); }
else { return Optional.of(propertySource.getName()); } } } } return Optional.empty(); } @Value @Builder private static class PropertyValueWithOrigin { @NonNull String propertyName; String propertyValue; String origin; @Override public String toString() { return propertyName + " = " + (propertyValue != null ? "'" + propertyValue + "'" : "null") + " (origin: " + origin + ")"; } public boolean isBlankValue() { return propertyValue == null || Check.isBlank(propertyValue); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\elasticsearch\ElasticsearchConfig.java
2
请完成以下Java代码
static ECKey.Builder signingWithEc(ECPublicKey pub, ECPrivateKey key) throws JOSEException { Date issued = new Date(); Curve curve = Curve.forECParameterSpec(pub.getParams()); JWSAlgorithm algorithm = computeAlgorithm(curve); return new ECKey.Builder(curve, pub).privateKey(key) .keyOperations(Set.of(KeyOperation.SIGN)) .keyUse(KeyUse.SIGNATURE) .algorithm(algorithm) .keyIDFromThumbprint() .issueTime(issued) .notBeforeTime(issued); } private static JWSAlgorithm computeAlgorithm(Curve curve) { try { return ECDSA.resolveAlgorithm(curve); } catch (JOSEException ex) { throw new IllegalArgumentException(ex);
} } static RSAKey.Builder signingWithRsa(RSAPublicKey pub, RSAPrivateKey key) throws JOSEException { Date issued = new Date(); return new RSAKey.Builder(pub).privateKey(key) .keyUse(KeyUse.SIGNATURE) .keyOperations(Set.of(KeyOperation.SIGN)) .algorithm(JWSAlgorithm.RS256) .keyIDFromThumbprint() .issueTime(issued) .notBeforeTime(issued); } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JWKS.java
1
请在Spring Boot框架中完成以下Java代码
class InOutCostsViewDataService { @NonNull private final OrderCostService orderCostService; @NonNull private final MoneyService moneyService; @NonNull final LookupDataSource bpartnerLookup; @NonNull final LookupDataSource orderLookup; @NonNull final LookupDataSource inoutLookup; @NonNull final LookupDataSource costTypeLookup; @Builder private InOutCostsViewDataService( final @NonNull OrderCostService orderCostService, final @NonNull MoneyService moneyService, final @NonNull LookupDataSourceFactory lookupDataSourceFactory) { this.orderCostService = orderCostService; this.moneyService = moneyService; this.bpartnerLookup = lookupDataSourceFactory.searchInTableLookup(I_C_BPartner.Table_Name); this.orderLookup = lookupDataSourceFactory.searchInTableLookup(I_C_Order.Table_Name); this.inoutLookup = lookupDataSourceFactory.searchInTableLookup(I_M_InOut.Table_Name); this.costTypeLookup = lookupDataSourceFactory.searchInTableLookup(I_C_Cost_Type.Table_Name); } public InOutCostsViewData getData( @NonNull final SOTrx soTrx, @NonNull final InvoiceAndLineId invoiceAndLineId, @Nullable final DocumentFilter filter) { return InOutCostsViewData.builder() .viewDataService(this) .soTrx(soTrx) .invoiceAndLineId(invoiceAndLineId) .filter(filter) .build(); } ImmutableList<InOutCostRow> retrieveRows( @NonNull final SOTrx soTrx, @Nullable final DocumentFilter filter) { final ImmutableList<InOutCost> inoutCosts = orderCostService .stream(InOutCostsViewFilterHelper.toInOutCostQuery(soTrx, filter)) .collect(ImmutableList.toImmutableList());
return newLoader().loadRows(inoutCosts); } private InOutCostRowsLoader newLoader() { return InOutCostRowsLoader.builder() .moneyService(moneyService) .bpartnerLookup(bpartnerLookup) .orderLookup(orderLookup) .inoutLookup(inoutLookup) .costTypeLookup(costTypeLookup) .build(); } public Amount getInvoiceLineOpenAmount(final InvoiceAndLineId invoiceAndLineId) { final Money invoiceLineOpenAmt = orderCostService.getInvoiceLineOpenAmt(invoiceAndLineId); return moneyService.toAmount(invoiceLineOpenAmt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsViewDataService.java
2
请完成以下Java代码
public boolean save(DataOutputStream out) { return false; } @Override public boolean load(ByteArray byteArray, V[] value) { return false; } @Override public V get(char[] key) { return get(new String(key)); } public V get(String key) { int id = exactMatchSearch(key); if (id == -1) return null; return valueArray[id]; } @Override public V[] getValueArray(V[] a) { return valueArray; } /** * 前缀查询 * @param key * @param offset * @param maxResults * @return */ public ArrayList<Pair<String, V>> commonPrefixSearch(String key, int offset, int maxResults) { byte[] keyBytes = key.getBytes(utf8); List<Pair<Integer, Integer>> pairList = commonPrefixSearch(keyBytes, offset, maxResults); ArrayList<Pair<String, V>> resultList = new ArrayList<Pair<String, V>>(pairList.size()); for (Pair<Integer, Integer> pair : pairList) { resultList.add(new Pair<String, V>(new String(keyBytes, 0, pair.first), valueArray[pair.second])); } return resultList; } public ArrayList<Pair<String, V>> commonPrefixSearch(String key) { return commonPrefixSearch(key, 0, Integer.MAX_VALUE); }
@Override public V put(String key, V value) { throw new UnsupportedOperationException("双数组不支持增量式插入"); } @Override public V remove(Object key) { throw new UnsupportedOperationException("双数组不支持删除"); } @Override public void putAll(Map<? extends String, ? extends V> m) { throw new UnsupportedOperationException("双数组不支持增量式插入"); } @Override public void clear() { throw new UnsupportedOperationException("双数组不支持"); } @Override public Set<String> keySet() { throw new UnsupportedOperationException("双数组不支持"); } @Override public Collection<V> values() { return Arrays.asList(valueArray); } @Override public Set<Entry<String, V>> entrySet() { throw new UnsupportedOperationException("双数组不支持"); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\DartMap.java
1
请在Spring Boot框架中完成以下Java代码
public RedirectView redirectWithUsingRedirectView(final ModelMap model) { model.addAttribute("attribute", "redirectWithRedirectView"); return new RedirectView("redirectedUrl"); } @RequestMapping(value = "/forwardWithForwardPrefix", method = RequestMethod.GET) public ModelAndView forwardWithUsingForwardPrefix(final ModelMap model) { model.addAttribute("attribute", "redirectWithForwardPrefix"); return new ModelAndView("forward:/redirectedUrl", model); } @RequestMapping(value = "/redirectedUrl", method = RequestMethod.GET) public ModelAndView redirection(final ModelMap model, @ModelAttribute("flashAttribute") final Object flashAttribute) { model.addAttribute("redirectionAttribute", flashAttribute); return new ModelAndView("redirection", model); } @RequestMapping(value = "/redirectPostToPost", method = RequestMethod.POST) public ModelAndView redirectPostToPost(HttpServletRequest request) { request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
return new ModelAndView("redirect:/redirectedPostToPost"); } @RequestMapping(value = "/redirectedPostToPost", method = RequestMethod.POST) public ModelAndView redirectedPostToPost() { return new ModelAndView("redirection"); } @RequestMapping(value="/forwardWithParams", method = RequestMethod.GET) public ModelAndView forwardWithParams(HttpServletRequest request) { request.setAttribute("param1", "one"); request.setAttribute("param2", "two"); return new ModelAndView("forward:/forwardedWithParams"); } }
repos\tutorials-master\spring-web-modules\spring-resttemplate-1\src\main\java\com\baeldung\resttemplate\web\controller\redirect\RedirectController.java
2
请完成以下Java代码
void freeSeat(String seatNumber) { if (occupiedSeats.contains(seatNumber)) { occupiedSeats.remove(seatNumber); freeSeats.add(seatNumber); } else { throw new IllegalArgumentException("Seat " + seatNumber + " is not currently occupied."); } } static List<String> allSeats() { List<Integer> rows = IntStream.range(1, 20) .boxed() .toList(); return IntStream.rangeClosed('A', 'J') .mapToObj(c -> String.valueOf((char) c)) .flatMap(col -> rows.stream() .map(row -> col + row)) .sorted() .toList(); } protected Movie() { // Default constructor for JPA } Instant startTime() {
return startTime; } String title() { return title; } String screenRoom() { return screenRoom; } List<String> freeSeats() { return List.copyOf(freeSeats); } List<String> occupiedSeatsSeats() { return List.copyOf(freeSeats); } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries-3\src\main\java\com\baeldung\spring\modulith\cqrs\movie\Movie.java
1
请完成以下Java代码
public Set<Map.Entry<String, Object>> entrySet() { return variableScope.getVariables().entrySet(); } public Set<String> keySet() { return variableScope.getVariables().keySet(); } public int size() { return variableScope.getVariables().size(); } public Collection<Object> values() { return variableScope.getVariables().values(); } public void putAll(Map<? extends String, ? extends Object> toMerge) { throw new UnsupportedOperationException(); } public Object remove(Object key) { if (UNSTORED_KEYS.contains(key)) { return null; } return defaultBindings.remove(key); }
public void clear() { throw new UnsupportedOperationException(); } public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } public boolean isEmpty() { throw new UnsupportedOperationException(); } public void addUnstoredKey(String unstoredKey) { UNSTORED_KEYS.add(unstoredKey); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptBindings.java
1
请完成以下Java代码
public class OthrIdentification { @XmlElement(name = "Id", required = true) @XmlSchemaType(name = "string") protected OthrIdentificationCode id; /** * Gets the value of the id property. * * @return * possible object is * {@link OthrIdentificationCode } * */ public OthrIdentificationCode getId() { return id;
} /** * Sets the value of the id property. * * @param value * allowed object is * {@link OthrIdentificationCode } * */ public void setId(OthrIdentificationCode value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\OthrIdentification.java
1
请完成以下Java代码
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) { logger.error("MQ消息发送失败,replyCode:{}, replyText:{},exchange:{},routingKey:{},消息体:{}", replyCode, replyText, exchange, routingKey, JSON.toJSONString(message.getBody())); // TODO 保存消息到数据库 } /** * 消息相关数据(消息ID) * * @param message * @return */ private CorrelationData correlationData(Object message) { return new CorrelationData(UUID.randomUUID().toString(), message); } /** * 发送消息 * * @param exchange 交换机名称
* @param routingKey 路由key * @param message 消息内容 * @param correlationData 消息相关数据(消息ID) * @throws AmqpException */ private void convertAndSend(String exchange, String routingKey, final Object message, CorrelationData correlationData) throws AmqpException { try { rabbitTemplate.convertAndSend(exchange, routingKey, message, correlationData); } catch (Exception e) { logger.error("MQ消息发送异常,消息ID:{},消息体:{}, exchangeName:{}, routingKey:{}", correlationData.getId(), JSON.toJSONString(message), exchange, routingKey, e); // TODO 保存消息到数据库 } } @Override public void afterPropertiesSet() throws Exception { rabbitTemplate.setConfirmCallback(this); rabbitTemplate.setReturnCallback(this); } }
repos\spring-boot-student-master\spring-boot-student-rabbitmq\src\main\java\com\xiaolyuh\mq\sender\RabbitSender.java
1
请完成以下Java代码
protected static class CacheKey { protected final String modelKey; protected final String tenantId; protected CacheKey(ChannelDefinition definition) { this.modelKey = definition.getKey(); this.tenantId = definition.getTenantId(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CacheKey cacheKey = (CacheKey) o; return Objects.equals(modelKey, cacheKey.modelKey) && Objects.equals(tenantId, cacheKey.tenantId); } @Override public int hashCode() { return Objects.hash(modelKey, tenantId); } } protected static class CacheValue { protected final String json; protected final int version; protected final String definitionId; public CacheValue(String json, ChannelDefinition definition) { this.json = json; this.version = definition.getVersion(); this.definitionId = definition.getId(); } } protected static class CacheRegisteredChannel implements RegisteredChannel { protected final CacheValue value; protected CacheRegisteredChannel(CacheValue value) { this.value = value; } @Override public int getChannelDefinitionVersion() { return value.version; } @Override public String getChannelDefinitionId() { return value.definitionId; } } protected class ChannelRegistrationImpl implements ChannelRegistration { protected final boolean registered; protected final CacheRegisteredChannel previousChannel; protected final CacheKey cacheKey;
public ChannelRegistrationImpl(boolean registered, CacheRegisteredChannel previousChannel, CacheKey cacheKey) { this.registered = registered; this.previousChannel = previousChannel; this.cacheKey = cacheKey; } @Override public boolean registered() { return registered; } @Override public RegisteredChannel previousChannel() { return previousChannel; } @Override public void rollback() { CacheValue cacheValue = previousChannel != null ? previousChannel.value : null; if (cacheValue == null) { cache.remove(cacheKey); } else { cache.put(cacheKey, cacheValue); } } } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\DefaultInboundChannelModelCacheManager.java
1
请完成以下Java代码
public void setMaxNetAmount (final BigDecimal MaxNetAmount) { set_Value (COLUMNNAME_MaxNetAmount, MaxNetAmount); } @Override public BigDecimal getMaxNetAmount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxNetAmount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
} @Override public void setM_Product_Category_MaxNetAmount_ID (final int M_Product_Category_MaxNetAmount_ID) { if (M_Product_Category_MaxNetAmount_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Category_MaxNetAmount_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Category_MaxNetAmount_ID, M_Product_Category_MaxNetAmount_ID); } @Override public int getM_Product_Category_MaxNetAmount_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_MaxNetAmount_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Category_MaxNetAmount.java
1
请在Spring Boot框架中完成以下Java代码
private int getCartItemCount(List<OmsCartItem> itemList) { int count = 0; for (OmsCartItem item : itemList) { count += item.getQuantity(); } return count; } /** * 获取购物车中指定商品的总价 */ private BigDecimal getCartItemAmount(List<OmsCartItem> itemList, List<PromotionProduct> promotionProductList) { BigDecimal amount = new BigDecimal(0); for (OmsCartItem item : itemList) { //计算出商品原价 PromotionProduct promotionProduct = getPromotionProductById(item.getProductId(), promotionProductList); PmsSkuStock skuStock = getOriginalPrice(promotionProduct,item.getProductSkuId()); amount = amount.add(skuStock.getPrice().multiply(new BigDecimal(item.getQuantity()))); } return amount; } /** * 获取商品的原价 */
private PmsSkuStock getOriginalPrice(PromotionProduct promotionProduct, Long productSkuId) { for (PmsSkuStock skuStock : promotionProduct.getSkuStockList()) { if (productSkuId.equals(skuStock.getId())) { return skuStock; } } return null; } /** * 根据商品id获取商品的促销信息 */ private PromotionProduct getPromotionProductById(Long productId, List<PromotionProduct> promotionProductList) { for (PromotionProduct promotionProduct : promotionProductList) { if (productId.equals(promotionProduct.getId())) { return promotionProduct; } } return null; } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\OmsPromotionServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void setNotifyTimes(Integer notifyTimes) { this.notifyTimes = notifyTimes; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } /** 限制通知次数 **/ public Integer getLimitNotifyTimes() { return limitNotifyTimes;
} /** 限制通知次数 **/ public void setLimitNotifyTimes(Integer limitNotifyTimes) { this.limitNotifyTimes = limitNotifyTimes; } public String getBankOrderNo() { return bankOrderNo; } public void setBankOrderNo(String bankOrderNo) { this.bankOrderNo = bankOrderNo; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\entity\RpOrderResultQueryVo.java
2
请完成以下Java代码
public class MyPair { private String first; private String second; public MyPair(String first, String second) { this.first = first; this.second = second; } public MyPair(String both) { String[] pairs = both.split("and"); this.first = pairs[0].trim(); this.second = pairs[1].trim(); } @Override @JsonValue public String toString() { return first + " and " + second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((first == null) ? 0 : first.hashCode()); result = prime * result + ((second == null) ? 0 : second.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; }
if (!(obj instanceof MyPair)) { return false; } MyPair other = (MyPair) obj; if (first == null) { if (other.first != null) { return false; } } else if (!first.equals(other.first)) { return false; } if (second == null) { if (other.second != null) { return false; } } else if (!second.equals(other.second)) { return false; } return true; } public String getFirst() { return first; } public void setFirst(String first) { this.first = first; } public String getSecond() { return second; } public void setSecond(String second) { this.second = second; } }
repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\map\MyPair.java
1
请完成以下Java代码
public abstract class DomXmlNodeIterator<T extends SpinXmlNode> implements Iterator<T> { private static final DomXmlLogger LOG = DomXmlLogger.XML_DOM_LOGGER; protected int index = 0; public boolean hasNext() { for (; index < getLength() ; index++) { if (getCurrent() != null) { return true; } } return false; } public T next() { if (hasNext()) {
T current = getCurrent(); index++; return current; } else { throw LOG.iteratorHasNoMoreElements(DomXmlNodeIterator.class); } } public void remove() { throw LOG.methodNotSupportedByClass("remove", DomXmlElementIterable.class); } protected abstract int getLength(); protected abstract T getCurrent(); }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\DomXmlNodeIterator.java
1
请在Spring Boot框架中完成以下Java代码
public SimpleCookie rememberMeCookie() { //System.out.println("ShiroConfiguration.rememberMeCookie()"); //这个参数是cookie的名称,对应前端的checkbox的name = rememberMe SimpleCookie simpleCookie = new SimpleCookie("rememberMe"); //<!-- 记住我cookie生效时间30天 ,单位秒;--> simpleCookie.setMaxAge(259200); return simpleCookie; } /** * cookie管理对象; * * @return */ @Bean public CookieRememberMeManager rememberMeManager() { //System.out.println("ShiroConfiguration.rememberMeManager()"); CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); cookieRememberMeManager.setCookie(rememberMeCookie()); return cookieRememberMeManager; } @Bean(name = "sessionManager") public DefaultWebSessionManager defaultWebSessionManager() { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setGlobalSessionTimeout(18000000); // url中是否显示session Id sessionManager.setSessionIdUrlRewritingEnabled(false); // 删除失效的session sessionManager.setDeleteInvalidSessions(true); sessionManager.setSessionValidationSchedulerEnabled(true); sessionManager.setSessionValidationInterval(18000000); sessionManager.setSessionValidationScheduler(getExecutorServiceSessionValidationScheduler()); //设置SessionIdCookie 导致认证不成功,不从新设置新的cookie,从sessionManager获取sessionIdCookie //sessionManager.setSessionIdCookie(simpleIdCookie());
sessionManager.getSessionIdCookie().setName("session-z-id"); sessionManager.getSessionIdCookie().setPath("/"); sessionManager.getSessionIdCookie().setMaxAge(60 * 60 * 24 * 7); return sessionManager; } @Bean(name = "sessionValidationScheduler") public ExecutorServiceSessionValidationScheduler getExecutorServiceSessionValidationScheduler() { ExecutorServiceSessionValidationScheduler scheduler = new ExecutorServiceSessionValidationScheduler(); scheduler.setInterval(900000); return scheduler; } @Bean(name = "shiroDialect") public ShiroDialect shiroDialect() { return new ShiroDialect(); } }
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\config\ShiroConfig.java
2