instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { // copied from java.awt.component m_imageNotLoaded = (infoflags & (ALLBITS|ABORT)) == 0; if (LogManager.isLevelFinest()) log.trace("Flags=" + infoflags + ", x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + " - NotLoaded=" + m_imageNotLoaded); return m_imageNotLoaded; } // imageUpdate /** * Wait until Image is loaded. * @param image image * @return true if loaded */ public boolean waitForLoad (Image image) { long start = System.currentTimeMillis(); Thread.yield(); int count = 0; try { Toolkit toolkit = Toolkit.getDefaultToolkit(); while (!toolkit.prepareImage(image, -1, -1, this)) // ImageObserver calls imageUpdate { // Timeout if (count > 1000) // about 20+ sec overall { log.error(this + " - Timeout - " + (System.currentTimeMillis()-start) + "ms - #" + count); return false; } try { if (count < 10) Thread.sleep(10); else if (count < 100) Thread.sleep(15); else Thread.sleep(20); } catch (InterruptedException ex) { log.error("", ex); break;
} count++; } } catch (Exception e) // java.lang.SecurityException { log.error("", e); return false; } if (count > 0) log.debug((System.currentTimeMillis()-start) + "ms - #" + count); return true; } // waitForLoad /** * Get Detail Info from Sub-Class * @return detail info */ protected String getDetailInfo() { return ""; } // getDetailInfo /** * String Representation * @return info */ public String toString() { String cn = getClass().getName(); StringBuffer sb = new StringBuffer(); sb.append(cn.substring(cn.lastIndexOf('.')+1)).append("["); sb.append("Bounds=").append(getBounds()) .append(",Height=").append(p_height).append("(").append(p_maxHeight) .append("),Width=").append(p_width).append("(").append(p_maxHeight) .append("),PageLocation=").append(p_pageLocation); sb.append("]"); return sb.toString(); } // toString } // PrintElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\PrintElement.java
1
请完成以下Java代码
public TableDataManager getTableDataManager() { return processEngineConfiguration.getTableDataManager(); } public CommentEntityManager getCommentEntityManager() { return processEngineConfiguration.getCommentEntityManager(); } public PropertyEntityManager getPropertyEntityManager() { return processEngineConfiguration.getPropertyEntityManager(); } public EventSubscriptionEntityManager getEventSubscriptionEntityManager() { return processEngineConfiguration.getEventSubscriptionEntityManager(); } public HistoryManager getHistoryManager() { return processEngineConfiguration.getHistoryManager(); } public JobManager getJobManager() { return processEngineConfiguration.getJobManager(); } // Involved executions //////////////////////////////////////////////////////// public void addInvolvedExecution(ExecutionEntity executionEntity) { if (executionEntity.getId() != null) { involvedExecutions.put(executionEntity.getId(), executionEntity); } } public boolean hasInvolvedExecutions() { return involvedExecutions.size() > 0; } public Collection<ExecutionEntity> getInvolvedExecutions() { return involvedExecutions.values(); } // getters and setters // ////////////////////////////////////////////////////// public Command<?> getCommand() { return command; } public Map<Class<?>, Session> getSessions() { return sessions; } public Throwable getException() {
return exception; } public FailedJobCommandFactory getFailedJobCommandFactory() { return failedJobCommandFactory; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public ActivitiEventDispatcher getEventDispatcher() { return processEngineConfiguration.getEventDispatcher(); } public ActivitiEngineAgenda getAgenda() { return agenda; } public Object getResult() { return resultStack.pollLast(); } public void setResult(Object result) { resultStack.add(result); } public boolean isReused() { return reused; } public void setReused(boolean reused) { this.reused = reused; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Extension.class, BPMN_ELEMENT_EXTENSION) .namespaceUri(BPMN20_NS) .instanceProvider(new ModelTypeInstanceProvider<Extension>() { public Extension newInstance(ModelTypeInstanceContext instanceContext) { return new ExtensionImpl(instanceContext); } }); // TODO: qname reference extension definition definitionAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_DEFINITION) .build(); mustUnderstandAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_MUST_UNDERSTAND) .defaultValue(false) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); documentationCollection = sequenceBuilder.elementCollection(Documentation.class) .build(); typeBuilder.build(); } public ExtensionImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); }
public String getDefinition() { return definitionAttribute.getValue(this); } public void setDefinition(String Definition) { definitionAttribute.setValue(this, Definition); } public boolean mustUnderstand() { return mustUnderstandAttribute.getValue(this); } public void setMustUnderstand(boolean mustUnderstand) { mustUnderstandAttribute.setValue(this, mustUnderstand); } public Collection<Documentation> getDocumentations() { return documentationCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ExtensionImpl.java
1
请完成以下Java代码
public static String toCodeOrNull(final BOMComponentType componentType) { return componentType != null ? componentType.getCode() : null; } @NonNull public static BOMComponentType ofCode(@NonNull final String code) { return index.ofCode(code); } @NonNull public static BOMComponentType ofNullableCodeOrComponent(@Nullable final String code) { final BOMComponentType type = index.ofNullableCode(code); return type != null ? type : Component; } @JsonCreator @NonNull public static BOMComponentType ofCodeOrName(@NonNull final String code) {return index.ofCodeOrName(code);} public static Optional<BOMComponentType> optionalOfNullableCode(@Nullable final String code) { return index.optionalOfNullableCode(code); } private static final ReferenceListAwareEnums.ValuesIndex<BOMComponentType> index = ReferenceListAwareEnums.index(values()); public boolean isComponent() { return this == Component; } public boolean isPacking() { return this == Packing; } public boolean isComponentOrPacking() { return isComponent() || isPacking(); } public boolean isCoProduct() { return this == CoProduct; } public boolean isByProduct() { return this == ByProduct; } public boolean isByOrCoProduct() { return isByProduct() || isCoProduct(); } public boolean isVariant()
{ return this == Variant; } public boolean isPhantom() { return this == Phantom; } public boolean isTools() { return this == Tools; } // public boolean isReceipt() { return isByOrCoProduct(); } public boolean isIssue() { return !isReceipt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\BOMComponentType.java
1
请完成以下Java代码
public class BpmnParseHandlers { private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(BpmnParseHandlers.class); protected Map<Class<? extends BaseElement>, List<BpmnParseHandler>> parseHandlers; public BpmnParseHandlers() { this.parseHandlers = new HashMap<Class<? extends BaseElement>, List<BpmnParseHandler>>(); } public List<BpmnParseHandler> getHandlersFor(Class<? extends BaseElement> clazz) { return parseHandlers.get(clazz); } public void addHandlers(List<BpmnParseHandler> bpmnParseHandlers) { for (BpmnParseHandler bpmnParseHandler : bpmnParseHandlers) { addHandler(bpmnParseHandler); } } public void addHandler(BpmnParseHandler bpmnParseHandler) { for (Class<? extends BaseElement> type : bpmnParseHandler.getHandledTypes()) { List<BpmnParseHandler> handlers = parseHandlers.get(type); if (handlers == null) { handlers = new ArrayList<BpmnParseHandler>(); 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 + " + element.getId() + " this is likely a bug."); } else { for (BpmnParseHandler handler : handlers) { handler.parse(bpmnParse, element); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParseHandlers.java
1
请在Spring Boot框架中完成以下Java代码
public UserVO get(@PathVariable("id") Integer id) { // 查询并返回用户 return new UserVO().setId(id).setUsername("username:" + id); } /** * 获得指定用户编号的用户 * * @param id 用户编号 * @return 用户 */ @GetMapping("/v2/{id}") public UserVO get2(@PathVariable("id") Integer id) { return userService.get(id); } /** * 添加用户 * * @param addDTO 添加用户信息 DTO * @return 添加成功的用户编号 */ @PostMapping("") public Integer add(UserAddDTO addDTO) { // 插入用户记录,返回编号 Integer returnId = 1; // 返回用户编号 return returnId; } /** * 更新指定用户编号的用户 * * @param id 用户编号 * @param updateDTO 更新用户信息 DTO * @return 是否修改成功 */ @PutMapping("/{id}") public Boolean update(@PathVariable("id") Integer id, UserUpdateDTO updateDTO) { // 将 id 设置到 updateDTO 中
updateDTO.setId(id); // 更新用户记录 Boolean success = true; // 返回更新是否成功 return success; } /** * 删除指定用户编号的用户 * * @param id 用户编号 * @return 是否删除成功 */ @DeleteMapping("/{id}") public Boolean delete(@PathVariable("id") Integer id) { // 删除用户记录 Boolean success = false; // 返回是否更新成功 return success; } }
repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-01\src\main\java\cn\iocoder\springboot\lab23\springmvc\controller\UserController.java
2
请完成以下Java代码
public boolean isShowFromAllBundles() { return fShowFromAllBundles.isSelected(); } public boolean isShowOnlyDue() { return fShowOnlyDue.isSelected(); } public boolean isShowOnlyOpen() { return fShowOnlyOpen.isSelected(); } private void updateFieldsStatus() { final boolean selected = m_model.isContactSelected(); final I_RV_R_Group_Prospect contact = m_model.getRV_R_Group_Prospect(false); final boolean locked = selected ? contact.isLocked() : false; butRefresh.setEnabled(getR_Group_ID() > 0 || isShowFromAllBundles()); butCall.setEnabled(selected); butUnlock.setEnabled(locked); fUserComments.setText(contact == null ? "" : contact.getComments()); } // @Override @Override public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { if (evt.getSource() == fBundles) { final int R_Group_ID = getR_Group_ID(); lBundleInfo.setText(m_model.getBundleInfo(R_Group_ID)); query(); updateFieldsStatus(); } } // @Override @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == butCall) { callContact(); } else if (e.getSource() == butRefresh) { refreshAll(true); m_updater.start(); } else if (e.getSource() == fShowFromAllBundles) { // fBundles.setEnabled(!fShowFromAllBundles.isSelected()); fBundles.setReadWrite(!fShowFromAllBundles.isSelected()); query(); } else if (e.getSource() == fShowOnlyDue) { query(); } else if (e.getSource() == fShowOnlyOpen) { query(); } }
// @Override @Override public void windowStateChanged(WindowEvent e) { // The Customize Window was closed if (e.getID() == WindowEvent.WINDOW_CLOSED && e.getSource() == m_requestFrame && m_model != null // sometimes we get NPE ) { final I_RV_R_Group_Prospect contact = m_model.getRV_R_Group_Prospect(false); m_model.unlockContact(contact); m_frame.setEnabled(true); AEnv.showWindow(m_frame); m_requestFrame = null; refreshAll(true); m_updater.start(); } } // @Override @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getSource() == m_model.getContactsGridTab() && evt.getPropertyName().equals(GridTab.PROPERTY)) { updateFieldsStatus(); m_model.queryDetails(); vtableAutoSizeAll(); } } public static Image getImage(String fileNameInImageDir) { URL url = CallCenterForm.class.getResource("images/" + fileNameInImageDir); if (url == null) { log.error("Not found: " + fileNameInImageDir); return null; } Toolkit tk = Toolkit.getDefaultToolkit(); return tk.getImage(url); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\form\CallCenterForm.java
1
请在Spring Boot框架中完成以下Java代码
Environment rabbitStreamEnvironment(RabbitProperties properties, RabbitConnectionDetails connectionDetails, ObjectProvider<EnvironmentBuilderCustomizer> customizers) { EnvironmentBuilder builder = configure(Environment.builder(), properties, connectionDetails); customizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder.build(); } @Bean @ConditionalOnMissingBean RabbitStreamTemplateConfigurer rabbitStreamTemplateConfigurer(RabbitProperties properties, ObjectProvider<MessageConverter> messageConverter, ObjectProvider<StreamMessageConverter> streamMessageConverter, ObjectProvider<ProducerCustomizer> producerCustomizer) { RabbitStreamTemplateConfigurer configurer = new RabbitStreamTemplateConfigurer(); configurer.setMessageConverter(messageConverter.getIfUnique()); configurer.setStreamMessageConverter(streamMessageConverter.getIfUnique()); configurer.setProducerCustomizer(producerCustomizer.getIfUnique()); return configurer; } @Bean @ConditionalOnMissingBean(RabbitStreamOperations.class) @ConditionalOnProperty(name = "spring.rabbitmq.stream.name") RabbitStreamTemplate rabbitStreamTemplate(Environment rabbitStreamEnvironment, RabbitProperties properties, RabbitStreamTemplateConfigurer configurer) { String name = properties.getStream().getName(); Assert.state(name != null, "'name' must not be null"); RabbitStreamTemplate template = new RabbitStreamTemplate(rabbitStreamEnvironment, name); configurer.configure(template); return template; }
static EnvironmentBuilder configure(EnvironmentBuilder builder, RabbitProperties properties, RabbitConnectionDetails connectionDetails) { return configure(builder, properties.getStream(), connectionDetails); } private static EnvironmentBuilder configure(EnvironmentBuilder builder, RabbitProperties.Stream stream, RabbitConnectionDetails connectionDetails) { builder.lazyInitialization(true); PropertyMapper map = PropertyMapper.get(); map.from(stream.getHost()).to(builder::host); map.from(stream.getPort()).to(builder::port); map.from(stream.getVirtualHost()).orFrom(connectionDetails::getVirtualHost).to(builder::virtualHost); map.from(stream.getUsername()).orFrom(connectionDetails::getUsername).to(builder::username); map.from(stream.getPassword()).orFrom(connectionDetails::getPassword).to(builder::password); return builder; } }
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitStreamConfiguration.java
2
请完成以下Java代码
public CostAmountAndQtyDetailed negate() { return builder() .main(main.negate()) .costAdjustment(costAdjustment.negate()) .alreadyShipped(alreadyShipped.negate()) .build(); } public CostAmountAndQty getAmtAndQty(final CostAmountType type) { final CostAmountAndQty costAmountAndQty; switch (type) { case MAIN: costAmountAndQty = main; break; case ADJUSTMENT: costAmountAndQty = costAdjustment; break; case ALREADY_SHIPPED: costAmountAndQty = alreadyShipped; break;
default: throw new IllegalArgumentException(); } return costAmountAndQty; } public CostAmountDetailed getAmt() { return CostAmountDetailed.builder() .mainAmt(main.getAmt()) .costAdjustmentAmt(costAdjustment.getAmt()) .alreadyShippedAmt(alreadyShipped.getAmt()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\CostAmountAndQtyDetailed.java
1
请完成以下Java代码
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verbucht. @param Posted Posting status */ @Override public void setPosted (boolean Posted) { set_ValueNoCheck (COLUMNNAME_Posted, Boolean.valueOf(Posted)); } /** Get Verbucht. @return Posting status */ @Override public boolean isPosted () { Object oo = get_Value(COLUMNNAME_Posted); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Price Match Difference. @param PriceMatchDifference Difference between Purchase and Invoice Price per matched line */ @Override public void setPriceMatchDifference (java.math.BigDecimal PriceMatchDifference) { set_Value (COLUMNNAME_PriceMatchDifference, PriceMatchDifference); } /** Get Price Match Difference. @return Difference between Purchase and Invoice Price per matched line */ @Override public java.math.BigDecimal getPriceMatchDifference () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceMatchDifference); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); }
/** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg 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 Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** 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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MatchPO.java
1
请完成以下Java代码
static void setZeroesInCols(int[][] matrix, int rows, int cols) { for (int j = 1; j < cols; j++) { if (matrix[0][j] == 0) { for (int i = 1; i < rows; i++) { matrix[i][j] = 0; } } } } static void setZeroesInFirstRow(int[][] matrix, int cols) { for (int j = 0; j < cols; j++) { matrix[0][j] = 0; } } static void setZeroesInFirstCol(int[][] matrix, int rows) { for (int i = 0; i < rows; i++) { matrix[i][0] = 0; } }
static void setZeroesByOptimalApproach(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; boolean firstRowZero = hasZeroInFirstRow(matrix, cols); boolean firstColZero = hasZeroInFirstCol(matrix, rows); markZeroesInMatrix(matrix, rows, cols); setZeroesInRows(matrix, rows, cols); setZeroesInCols(matrix, rows, cols); if (firstRowZero) { setZeroesInFirstRow(matrix, cols); } if (firstColZero) { setZeroesInFirstCol(matrix, rows); } } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\matrixtozero\SetMatrixToZero.java
1
请完成以下Java代码
protected void checkCreateAndReadDeployments(CommandContext commandContext, Set<String> deploymentIds) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkCreateDeployment(); for (String deploymentId : deploymentIds) { checker.checkReadDeployment(deploymentId); } } } protected boolean isBpmnResource(Resource resourceEntity) { return StringUtil.hasAnySuffix(resourceEntity.getName(), BpmnDeployer.BPMN_RESOURCE_SUFFIXES); } protected boolean isCmmnResource(Resource resourceEntity) { return StringUtil.hasAnySuffix(resourceEntity.getName(), CmmnDeployer.CMMN_RESOURCE_SUFFIXES); } // ensures protected void ensureDeploymentsWithIdsExists(Set<String> expected, List<DeploymentEntity> actual) { Map<String, DeploymentEntity> deploymentMap = new HashMap<>(); for (DeploymentEntity deployment : actual) { deploymentMap.put(deployment.getId(), deployment); } List<String> missingDeployments = getMissingElements(expected, deploymentMap); if (!missingDeployments.isEmpty()) { StringBuilder builder = new StringBuilder(); builder.append("The following deployments are not found by id: "); builder.append(StringUtil.join(missingDeployments.iterator())); throw new NotFoundException(builder.toString()); } }
protected void ensureResourcesWithIdsExist(String deploymentId, Set<String> expectedIds, List<ResourceEntity> actual) { Map<String, ResourceEntity> resources = new HashMap<>(); for (ResourceEntity resource : actual) { resources.put(resource.getId(), resource); } ensureResourcesWithKeysExist(deploymentId, expectedIds, resources, "id"); } protected void ensureResourcesWithNamesExist(String deploymentId, Set<String> expectedNames, List<ResourceEntity> actual) { Map<String, ResourceEntity> resources = new HashMap<>(); for (ResourceEntity resource : actual) { resources.put(resource.getName(), resource); } ensureResourcesWithKeysExist(deploymentId, expectedNames, resources, "name"); } protected void ensureResourcesWithKeysExist(String deploymentId, Set<String> expectedKeys, Map<String, ResourceEntity> actual, String valueProperty) { List<String> missingResources = getMissingElements(expectedKeys, actual); if (!missingResources.isEmpty()) { StringBuilder builder = new StringBuilder(); builder.append("The deployment with id '"); builder.append(deploymentId); builder.append("' does not contain the following resources with "); builder.append(valueProperty); builder.append(": "); builder.append(StringUtil.join(missingResources.iterator())); throw new NotFoundException(builder.toString()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeployCmd.java
1
请完成以下Java代码
public void execute(DelegateExecution execution) { ThrowMessage throwMessage = getThrowMessage(execution); boolean isSent = send(execution, throwMessage); if (isSent) { dispatchEvent(execution, throwMessage); } super.execute(execution); } public MessageEventDefinition getMessageEventDefinition() { return messageEventDefinition; } protected ThrowMessage getThrowMessage(DelegateExecution execution) { return messageExecutionContext.createThrowMessage(execution); } protected void dispatchEvent(DelegateExecution execution, ThrowMessage throwMessage) { Optional.ofNullable(Context.getCommandContext()) .filter(commandContext -> commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) .ifPresent(commandContext -> { String messageName = throwMessage.getName(); String correlationKey = throwMessage.getCorrelationKey().orElse(null); Object payload = throwMessage.getPayload().orElse(null);
commandContext .getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createMessageSentEvent(execution, messageName, correlationKey, payload) ); }); } public ThrowMessageDelegate getDelegate() { return delegate; } public MessageExecutionContext getMessageExecutionContext() { return messageExecutionContext; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\AbstractThrowMessageEventActivityBehavior.java
1
请完成以下Spring Boot application配置
logging.level.org.springframework.web=INFO logging.level.org.hibernate=ERROR logging.level.net.guides=DEBUG logging.file=myapp.log jdbc.driver=com.mysql.jdbc.Driver jdbc.u
rl=jdbc:mysql://localhost:3306/dev_db jdbc.username=root jdbc.password=root
repos\Spring-Boot-Advanced-Projects-main\springboot2-externalizing-conf-properties\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
private de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop119VType getEDICctop119VType(@NonNull final EDICctop119VType source) { final de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop119VType target = DESADV_objectFactory.createEDICctop119VType(); target.setAddress1(source.getAddress1()); target.setAddress2(source.getAddress2()); target.setCBPartnerLocationID(source.getCBPartnerLocationID()); target.setCInvoiceID(source.getCInvoiceID()); target.setCity(source.getCity()); target.setCountryCode(source.getCountryCode()); target.setEancomLocationtype(source.getEancomLocationtype()); target.setEDICctop119VID(source.getEDICctop119VID()); target.setFax(source.getFax()); target.setGLN(source.getGLN()); target.setMInOutID(source.getMInOutID()); target.setName(source.getName()); target.setName2(source.getName2()); target.setPhone(source.getPhone()); target.setPostal(source.getPostal()); target.setValue(source.getValue()); target.setVATaxID(source.getVATaxID()); target.setReferenceNo(source.getReferenceNo()); target.setSetupPlaceNo(source.getSetupPlaceNo()); target.setSiteName(source.getSiteName()); target.setContact(source.getContact()); return target; }
@NonNull private de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop111VType getEDICctop111VType(@NonNull final EDICctop111VType source) { final de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop111VType target = DESADV_objectFactory.createEDICctop111VType(); target.setCOrderID(source.getCOrderID()); target.setDateOrdered(source.getDateOrdered()); target.setEDICctop111VID(source.getEDICctop111VID()); target.setMInOutID(source.getMInOutID()); target.setMovementDate(source.getMovementDate()); target.setPOReference(source.getPOReference()); target.setShipmentDocumentno(source.getShipmentDocumentno()); return target; } @NonNull private de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop000VType getEDICctop000V(@NonNull final EDICctop000VType source) { final de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop000VType target = DESADV_objectFactory.createEDICctop000VType(); target.setCBPartnerLocationID(source.getCBPartnerLocationID()); target.setEDICctop000VID(source.getEDICctop000VID()); target.setGLN(source.getGLN()); return target; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\metasfreshinhousev1\MetasfreshInHouseV1XMLInvoicBean.java
2
请完成以下Java代码
public class AddressDisplaySequence { public static final AddressDisplaySequence EMPTY = new AddressDisplaySequence(""); private static final AdMessageKey MSG_AddressBuilder_WrongDisplaySequence = AdMessageKey.of("MSG_AddressBuilder_WrongDisplaySequence"); @NonNull private final String pattern; private AddressDisplaySequence(@NonNull final String pattern) { this.pattern = pattern; } @NonNull public static AddressDisplaySequence ofNullable(@Nullable final String pattern) { return pattern != null && !Check.isBlank(pattern) ? new AddressDisplaySequence(pattern) : EMPTY; } @Override @Deprecated public String toString() { return pattern; } public void assertValid() { final boolean existsBPName = hasToken(Addressvars.BPartnerName); final boolean existsBP = hasToken(Addressvars.BPartner); final boolean existsBPGreeting = hasToken(Addressvars.BPartnerGreeting); if ((existsBP && existsBPName) || (existsBP && existsBPGreeting)) { throw new AdempiereException(MSG_AddressBuilder_WrongDisplaySequence) //.appendParametersToMessage() .setParameter("displaySequence", this); }
} public boolean hasToken(@NonNull final Addressvars token) { // TODO: optimize it! this is just some crap refactored code final Scanner scan = new Scanner(pattern); scan.useDelimiter("@"); while (scan.hasNext()) { if (scan.next().equals(token.getName())) { scan.close(); return true; } } scan.close(); return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\AddressDisplaySequence.java
1
请完成以下Java代码
public static BooleanWithReason falseBecause(@NonNull final Exception exception) { return falseBecause(AdempiereException.extractMessageTrl(exception)); } public static BooleanWithReason falseIf(final boolean condition, @NonNull final String falseReason) { return condition ? falseBecause(falseReason) : TRUE; } private static ITranslatableString toTrl(@Nullable final String reasonStr) { if (reasonStr == null || Check.isBlank(reasonStr)) { return TranslatableStrings.empty(); } else { return TranslatableStrings.anyLanguage(reasonStr.trim()); } } public static final BooleanWithReason TRUE = new BooleanWithReason(true, TranslatableStrings.empty()); public static final BooleanWithReason FALSE = new BooleanWithReason(false, TranslatableStrings.empty()); private final boolean value; @NonNull @Getter private final ITranslatableString reason; private BooleanWithReason( final boolean value, @NonNull final ITranslatableString reason) { this.value = value; this.reason = reason; } @Override public String toString() { final String valueStr = String.valueOf(value); final String reasonStr = !TranslatableStrings.isBlank(reason) ? reason.getDefaultValue() : null; return reasonStr != null ? valueStr + " because " + reasonStr : valueStr; } public boolean toBoolean() { return value; } public boolean isTrue() { return value; } public boolean isFalse() { return !value; }
public String getReasonAsString() { return reason.getDefaultValue(); } public void assertTrue() { if (isFalse()) { throw new AdempiereException(reason); } } public BooleanWithReason and(@NonNull final Supplier<BooleanWithReason> otherSupplier) { return isFalse() ? this : Check.assumeNotNull(otherSupplier.get(), "otherSupplier shall not return null"); } public void ifTrue(@NonNull final Consumer<String> consumer) { if (isTrue()) { consumer.accept(getReasonAsString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\BooleanWithReason.java
1
请完成以下Java代码
private static void combinationsInternal( List<Integer> inputSet, int k, List<List<Integer>> results, ArrayList<Integer> accumulator, int index) { int leftToAccumulate = k - accumulator.size(); int possibleToAcculumate = inputSet.size() - index; if (accumulator.size() == k) { results.add(new ArrayList<>(accumulator)); } else if (leftToAccumulate <= possibleToAcculumate) { combinationsInternal(inputSet, k, results, accumulator, index + 1); accumulator.add(inputSet.get(index)); combinationsInternal(inputSet, k, results, accumulator, index + 1); accumulator.remove(accumulator.size() - 1); } } public static List<List<Character>> powerSet(List<Character> sequence) { List<List<Character>> results = new ArrayList<>();
powerSetInternal(sequence, results, new ArrayList<>(), 0); return results; } private static void powerSetInternal( List<Character> set, List<List<Character>> powerSet, List<Character> accumulator, int index) { if (index == set.size()) { powerSet.add(new ArrayList<>(accumulator)); } else { accumulator.add(set.get(index)); powerSetInternal(set, powerSet, accumulator, index + 1); accumulator.remove(accumulator.size() - 1); powerSetInternal(set, powerSet, accumulator, index + 1); } } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\combinatorics\Combinatorics.java
1
请完成以下Java代码
public SqlLookupDescriptorFactory setCtxColumnName(@Nullable final String ctxColumnName) { this.ctxColumnName = ctxColumnName; this.filtersBuilder.setCtxColumnName(this.ctxColumnName); return this; } public SqlLookupDescriptorFactory setCtxTableName(@Nullable final String ctxTableName) { this.ctxTableName = ctxTableName; this.filtersBuilder.setCtxTableName(ctxTableName); return this; } public SqlLookupDescriptorFactory setDisplayType(final ReferenceId displayType) { this.displayType = displayType; this.filtersBuilder.setDisplayType(ReferenceId.toRepoId(displayType)); return this; } public SqlLookupDescriptorFactory setAD_Reference_Value_ID(final ReferenceId AD_Reference_Value_ID) { this.AD_Reference_Value_ID = AD_Reference_Value_ID; return this; } public SqlLookupDescriptorFactory setAdValRuleIds(@NonNull final Map<LookupDescriptorProvider.LookupScope, AdValRuleId> adValRuleIds) { this.filtersBuilder.setAdValRuleIds(adValRuleIds); return this; } private CompositeSqlLookupFilter getFilters() { return filtersBuilder.getOrBuild(); } private static boolean computeIsHighVolume(@NonNull final ReferenceId diplayType) { final int displayTypeInt = diplayType.getRepoId(); return DisplayType.TableDir != displayTypeInt && DisplayType.Table != displayTypeInt && DisplayType.List != displayTypeInt && DisplayType.Button != displayTypeInt; }
/** * Advice the lookup to show all records on which current user has at least read only access */ public SqlLookupDescriptorFactory setReadOnlyAccess() { this.requiredAccess = Access.READ; return this; } private Access getRequiredAccess(@NonNull final TableName tableName) { if (requiredAccess != null) { return requiredAccess; } // AD_Client_ID/AD_Org_ID (security fields): shall display only those entries on which current user has read-write access if (I_AD_Client.Table_Name.equals(tableName.getAsString()) || I_AD_Org.Table_Name.equals(tableName.getAsString())) { return Access.WRITE; } // Default: all entries on which current user has at least readonly access return Access.READ; } SqlLookupDescriptorFactory addValidationRules(final Collection<IValidationRule> validationRules) { this.filtersBuilder.addFilter(validationRules, null); return this; } SqlLookupDescriptorFactory setPageLength(final Integer pageLength) { this.pageLength = pageLength; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupDescriptorFactory.java
1
请完成以下Java代码
public java.math.BigDecimal getQualityAdj_Amt_Per_UOM () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QualityAdj_Amt_Per_UOM); if (bd == null) return Env.ZERO; return bd; } /** * QualityAdjustmentMonth AD_Reference_ID=540507 * Reference name: QualityAdjustmentMonth */ public static final int QUALITYADJUSTMENTMONTH_AD_Reference_ID=540507; /** Jan = Jan */ public static final String QUALITYADJUSTMENTMONTH_Jan = "Jan"; /** Feb = Feb */ public static final String QUALITYADJUSTMENTMONTH_Feb = "Feb"; /** Mar = Mar */ public static final String QUALITYADJUSTMENTMONTH_Mar = "Mar"; /** Apr = Apr */ public static final String QUALITYADJUSTMENTMONTH_Apr = "Apr"; /** May = May */ public static final String QUALITYADJUSTMENTMONTH_May = "May"; /** Jun = Jun */ public static final String QUALITYADJUSTMENTMONTH_Jun = "Jun"; /** Jul = Jul */ public static final String QUALITYADJUSTMENTMONTH_Jul = "Jul"; /** Aug = Aug */ public static final String QUALITYADJUSTMENTMONTH_Aug = "Aug";
/** Sep = Sep */ public static final String QUALITYADJUSTMENTMONTH_Sep = "Sep"; /** Oct = Oct */ public static final String QUALITYADJUSTMENTMONTH_Oct = "Oct"; /** Nov = Nov */ public static final String QUALITYADJUSTMENTMONTH_Nov = "Nov"; /** Dec = Dec */ public static final String QUALITYADJUSTMENTMONTH_Dec = "Dec"; /** Set Monat. @param QualityAdjustmentMonth Monat */ @Override public void setQualityAdjustmentMonth (java.lang.String QualityAdjustmentMonth) { set_Value (COLUMNNAME_QualityAdjustmentMonth, QualityAdjustmentMonth); } /** Get Monat. @return Monat */ @Override public java.lang.String getQualityAdjustmentMonth () { return (java.lang.String)get_Value(COLUMNNAME_QualityAdjustmentMonth); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf_Month_Adj.java
1
请完成以下Java代码
protected void additionalBeans(BuildProducer<AdditionalBeanBuildItem> additionalBeansProducer) { additionalBeansProducer.produce( AdditionalBeanBuildItem.builder() .setDefaultScope(DotName.createSimple(Dependent.class.getName())) .addBeanClasses( DefaultContextAssociationManager.class, BusinessProcess.class, ProcessVariableLocalMap.class, ProcessVariables.class, ProcessVariableMap.class ).build()); } @BuildStep @Record(RUNTIME_INIT) protected void cdiConfig(CamundaEngineRecorder recorder, BeanContainerBuildItem beanContainer) { recorder.configureProcessEngineCdiBeans(beanContainer.getValue()); } @Consume(AdditionalBeanBuildItem.class) @BuildStep @Record(RUNTIME_INIT) protected void processEngineConfiguration(CamundaEngineRecorder recorder, BeanContainerBuildItem beanContainerBuildItem, CamundaEngineConfig camundaEngineConfig, BuildProducer<ProcessEngineConfigurationBuildItem> configurationProducer) { BeanContainer beanContainer = beanContainerBuildItem.getValue(); recorder.configureProcessEngineCdiBeans(beanContainer); RuntimeValue<ProcessEngineConfigurationImpl> processEngineConfiguration = recorder.createProcessEngineConfiguration(beanContainer, camundaEngineConfig); configurationProducer.produce(new ProcessEngineConfigurationBuildItem(processEngineConfiguration)); } @BuildStep
@Record(RUNTIME_INIT) protected void processEngine(CamundaEngineRecorder recorder, ProcessEngineConfigurationBuildItem processEngineConfigurationBuildItem, BuildProducer<ProcessEngineBuildItem> processEngineProducer) { RuntimeValue<ProcessEngineConfigurationImpl> processEngineConfiguration = processEngineConfigurationBuildItem.getProcessEngineConfiguration(); processEngineProducer.produce(new ProcessEngineBuildItem( recorder.createProcessEngine(processEngineConfiguration))); } @Consume(ProcessEngineBuildItem.class) @BuildStep @Record(RUNTIME_INIT) protected void deployProcessEngineResources(CamundaEngineRecorder recorder) { recorder.fireCamundaEngineStartEvent(); } @BuildStep @Record(RUNTIME_INIT) protected void shutdown(CamundaEngineRecorder recorder, ProcessEngineBuildItem processEngine, ShutdownContextBuildItem shutdownContext) { recorder.registerShutdownTask(shutdownContext, processEngine.getProcessEngine()); } }
repos\camunda-bpm-platform-master\quarkus-extension\engine\deployment\src\main\java\org\camunda\bpm\quarkus\engine\extension\deployment\impl\CamundaEngineProcessor.java
1
请完成以下Java代码
public int getSequenceBits() { return sequenceBits; } public long getMaxDeltaSeconds() { return maxDeltaSeconds; } public long getMaxWorkerId() { return maxWorkerId; } public long getMaxSequence() { return maxSequence; }
public int getTimestampShift() { return timestampShift; } public int getWorkerIdShift() { return workerIdShift; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\BitsAllocator.java
1
请完成以下Java代码
public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setRevision (final @Nullable java.lang.String Revision) { set_Value (COLUMNNAME_Revision, Revision); } @Override public java.lang.String getRevision() { return get_ValueAsString(COLUMNNAME_Revision); } @Override public org.compiere.model.I_AD_Sequence getSerialNo_Sequence() { return get_ValueAsPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setSerialNo_Sequence(final org.compiere.model.I_AD_Sequence SerialNo_Sequence) { set_ValueFromPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, SerialNo_Sequence); } @Override public void setSerialNo_Sequence_ID (final int SerialNo_Sequence_ID) {
if (SerialNo_Sequence_ID < 1) set_Value (COLUMNNAME_SerialNo_Sequence_ID, null); else set_Value (COLUMNNAME_SerialNo_Sequence_ID, SerialNo_Sequence_ID); } @Override public int getSerialNo_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_SerialNo_Sequence_ID); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_BOM.java
1
请完成以下Java代码
public Quantity getTotalQtyBooked( @NonNull final IUOMConversionBL uomConversionBL, @NonNull final I_C_UOM uom) { return huForInventoryLineList.stream() .map(HuForInventoryLine::getQuantityBooked) .map(qty -> uomConversionBL.convertQuantityTo(qty, productId, UomId.ofRepoId(uom.getC_UOM_ID()))) .reduce(Quantity::add) .orElseGet(() -> Quantity.zero(uom)); } @NonNull public Map<LocatorId, ProductHUInventory> mapByLocatorId() { return mapByKey(HuForInventoryLine::getLocatorId); } @NonNull public Map<WarehouseId, ProductHUInventory> mapByWarehouseId() { return mapByKey(huForInventoryLine -> huForInventoryLine.getLocatorId().getWarehouseId()); } @NonNull public List<InventoryLineHU> toInventoryLineHUs( @NonNull final IUOMConversionBL uomConversionBL, @NonNull final UomId targetUomId) { final UnaryOperator<Quantity> uomConverter = qty -> uomConversionBL.convertQuantityTo(qty, productId, targetUomId); return huForInventoryLineList.stream() .map(DraftInventoryLinesCreateCommand::toInventoryLineHU) .map(inventoryLineHU -> inventoryLineHU.convertQuantities(uomConverter)) .collect(ImmutableList.toImmutableList()); } @NonNull public Set<HuId> getHuIds() { return huForInventoryLineList.stream() .map(HuForInventoryLine::getHuId)
.filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } @NonNull private <K> Map<K, ProductHUInventory> mapByKey(final Function<HuForInventoryLine, K> keyProvider) { final Map<K, List<HuForInventoryLine>> key2Hus = new HashMap<>(); huForInventoryLineList.forEach(hu -> { final ArrayList<HuForInventoryLine> husFromTargetWarehouse = new ArrayList<>(); husFromTargetWarehouse.add(hu); key2Hus.merge(keyProvider.apply(hu), husFromTargetWarehouse, (oldList, newList) -> { oldList.addAll(newList); return oldList; }); }); return key2Hus.keySet() .stream() .collect(ImmutableMap.toImmutableMap(Function.identity(), warehouseId -> ProductHUInventory.of(this.productId, key2Hus.get(warehouseId)))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\ProductHUInventory.java
1
请完成以下Java代码
public class ValidateTaskRelatedEntityCountCfgCmd implements Command<Void> { private static final Logger LOGGER = LoggerFactory.getLogger(ValidateTaskRelatedEntityCountCfgCmd.class); public static final String PROPERTY_TASK_RELATED_ENTITY_COUNT = "cfg.task-related-entities-count"; @Override public Void execute(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); PropertyEntityManager propertyEntityManager = processEngineConfiguration.getPropertyEntityManager(); boolean configProperty = processEngineConfiguration.getPerformanceSettings().isEnableTaskRelationshipCounts(); PropertyEntity propertyEntity = propertyEntityManager.findById(PROPERTY_TASK_RELATED_ENTITY_COUNT); if (propertyEntity == null) { // 'not there' case in the table above: easy, simply insert the value PropertyEntity newPropertyEntity = propertyEntityManager.create(); newPropertyEntity.setName(PROPERTY_TASK_RELATED_ENTITY_COUNT); newPropertyEntity.setValue(Boolean.toString(configProperty)); propertyEntityManager.insert(newPropertyEntity); } else { boolean propertyValue = Boolean.valueOf(propertyEntity.getValue().toLowerCase()); // TODO: is this required since we check the global "task count" flag each time we read/update? // might have a serious performance impact when thousands of tasks are present.
if (!configProperty && propertyValue) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Configuration change: task related entity counting feature was enabled before, but now disabled. " + "Updating all task entities."); } processEngineConfiguration.getTaskServiceConfiguration().getTaskService().updateAllTaskRelatedEntityCountFlags(configProperty); } // Update property if (configProperty != propertyValue) { propertyEntity.setValue(Boolean.toString(configProperty)); propertyEntityManager.update(propertyEntity); } } return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\ValidateTaskRelatedEntityCountCfgCmd.java
1
请完成以下Java代码
protected ProcessInstanceBatchMigrationResult convertFromBatch(Batch batch, ObjectMapper objectMapper) { ProcessInstanceBatchMigrationResult result = new ProcessInstanceBatchMigrationResult(); result.setBatchId(batch.getId()); result.setSourceProcessDefinitionId(batch.getBatchSearchKey()); result.setTargetProcessDefinitionId(batch.getBatchSearchKey2()); result.setStatus(batch.getStatus()); result.setCompleteTime(batch.getCompleteTime()); return result; } protected ProcessInstanceBatchMigrationPartResult convertFromBatchPart(BatchPart batchPart, ObjectMapper objectMapper) { ProcessInstanceBatchMigrationPartResult partResult = new ProcessInstanceBatchMigrationPartResult(); partResult.setBatchId(batchPart.getId()); partResult.setProcessInstanceId(batchPart.getScopeId()); partResult.setSourceProcessDefinitionId(batchPart.getBatchSearchKey()); partResult.setTargetProcessDefinitionId(batchPart.getBatchSearchKey2()); if (batchPart.getCompleteTime() != null) { partResult.setStatus(ProcessInstanceBatchMigrationResult.STATUS_COMPLETED); }
partResult.setResult(batchPart.getStatus()); ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(); if (ProcessInstanceBatchMigrationResult.RESULT_FAIL.equals(batchPart.getStatus()) && batchPart.getResultDocumentJson(processEngineConfiguration.getEngineCfgKey()) != null) { try { JsonNode resultNode = objectMapper.readTree(batchPart.getResultDocumentJson(processEngineConfiguration.getEngineCfgKey())); if (resultNode.has(BATCH_RESULT_MESSAGE_LABEL)) { String resultMessage = resultNode.get(BATCH_RESULT_MESSAGE_LABEL).asString(); partResult.setMigrationMessage(resultMessage); } if (resultNode.has(BATCH_RESULT_STACKTRACE_LABEL)) { String resultStacktrace = resultNode.get(BATCH_RESULT_STACKTRACE_LABEL).asString(); partResult.setMigrationStacktrace(resultStacktrace); } } catch (JacksonException e) { throw new FlowableException("Error reading batch part " + batchPart.getId()); } } return partResult; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetProcessInstanceMigrationBatchResultCmd.java
1
请完成以下Java代码
private static Set<MADBoilerPlateVar> getVars(final PO po, final int timing) { final int AD_Client_ID = Env.getAD_Client_ID(po.getCtx()); final int AD_Org_ID = Env.getAD_Org_ID(po.getCtx()); final String tableName = po.get_TableName(); final int C_DocType_ID = getC_DocType_ID(po); final String evalTime = getEvalTime(timing); final ArrayKey key = new ArrayKey(AD_Client_ID, AD_Org_ID, tableName, C_DocType_ID, evalTime); Set<MADBoilerPlateVar> vars = s_cacheVars.get(key); if (vars == null) vars = new HashSet<>(); return vars; } private static int getC_DocType_ID(final PO po) { int index = po.get_ColumnIndex("C_DocType_ID"); if (index != -1) { Integer ii = (Integer)po.get_Value(index); // DocType does not exist - get DocTypeTarget if (ii != null && ii <= 0) { index = po.get_ColumnIndex("C_DocTypeTarget_ID"); if (index > 0) ii = (Integer)po.get_Value(index); } if (ii != null) return ii; } return -1; } private static void parseField(final PO po, final String columnName, final Collection<MADBoilerPlateVar> vars) { final String text = po.get_ValueAsString(columnName); if (text == null || Check.isBlank(text)) return; // final BoilerPlateContext attributes = BoilerPlateContext.builder() .setSourceDocumentFromObject(po) .build(); // final Matcher m = MADBoilerPlate.NameTagPattern.matcher(text); final StringBuffer sb = new StringBuffer(); while (m.find()) { final String refName = MADBoilerPlate.getTagName(m); // MADBoilerPlateVar var = null; for (final MADBoilerPlateVar v : vars) { if (refName.equals(v.getValue().trim())) { var = v; break; } } // final String replacement; if (var != null) { replacement = MADBoilerPlate.getPlainText(var.evaluate(attributes));
} else { replacement = m.group(); } if (replacement == null) { continue; } m.appendReplacement(sb, replacement); } m.appendTail(sb); final String textParsed = sb.toString(); po.set_ValueOfColumn(columnName, textParsed); } private static void setDunningRunEntryNote(final I_C_DunningRunEntry dre) { final Properties ctx = InterfaceWrapperHelper.getCtx(dre); final String trxName = InterfaceWrapperHelper.getTrxName(dre); final I_C_DunningLevel dl = dre.getC_DunningLevel(); final I_C_BPartner bp = Services.get(IBPartnerDAO.class).getById(dre.getC_BPartner_ID()); final String adLanguage = bp.getAD_Language(); final String text; if (adLanguage != null) { text = InterfaceWrapperHelper.getPO(dl).get_Translation(I_C_DunningLevel.COLUMNNAME_Note, adLanguage); } else { text = dl.getNote(); } final boolean isEmbeded = true; final BoilerPlateContext attributes = BoilerPlateContext.builder() .setSourceDocumentFromObject(dre) .build(); final String textParsed = MADBoilerPlate.parseText(ctx, text, isEmbeded, attributes, trxName); dre.setNote(textParsed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\model\LettersValidator.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthorList implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String genre; private int age; @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @JoinTable(name = "author_book_list", joinColumns = @JoinColumn(name = "author_id"), inverseJoinColumns = @JoinColumn(name = "book_id") ) private List<BookList> books = new ArrayList<>(); public void addBook(BookList book) { this.books.add(book); book.getAuthors().add(this); } public void removeBook(BookList book) { this.books.remove(book); book.getAuthors().remove(this); } public void removeBooks() { Iterator<BookList> iterator = this.books.iterator(); while (iterator.hasNext()) { BookList book = iterator.next(); book.getAuthors().remove(this); iterator.remove(); } } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<BookList> getBooks() { return books; } public void setBooks(List<BookList> books) { this.books = books; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((AuthorList) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootManyToManyBidirectionalListVsSet\src\main\java\com\bookstore\entity\AuthorList.java
2
请完成以下Java代码
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getPersonNumber() { return personNumber; } public void setPersonNumber(Long personNumber) { this.personNumber = personNumber; } public Boolean getIsActive() { return isActive; } public void setIsActive(Boolean isActive) { this.isActive = isActive; } public String getScode() { return securityNumber; }
public void setScode(String scode) { this.securityNumber = scode; } public String getDcode() { return departmentCode; } public void setDcode(String dcode) { this.departmentCode = dcode; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\uniqueconstraints\Person.java
1
请在Spring Boot框架中完成以下Java代码
public ServerDeployDto findById(Long id) { ServerDeploy server = serverDeployRepository.findById(id).orElseGet(ServerDeploy::new); ValidationUtil.isNull(server.getId(),"ServerDeploy","id",id); return serverDeployMapper.toDto(server); } @Override public ServerDeployDto findByIp(String ip) { ServerDeploy deploy = serverDeployRepository.findByIp(ip); return serverDeployMapper.toDto(deploy); } @Override public Boolean testConnect(ServerDeploy resources) { ExecuteShellUtil executeShellUtil = null; try { executeShellUtil = new ExecuteShellUtil(resources.getIp(), resources.getAccount(), resources.getPassword(),resources.getPort()); return executeShellUtil.execute("ls")==0; } catch (Exception e) { return false; }finally { if (executeShellUtil != null) { executeShellUtil.close(); } } } @Override @Transactional(rollbackFor = Exception.class) public void create(ServerDeploy resources) { serverDeployRepository.save(resources); }
@Override @Transactional(rollbackFor = Exception.class) public void update(ServerDeploy resources) { ServerDeploy serverDeploy = serverDeployRepository.findById(resources.getId()).orElseGet(ServerDeploy::new); ValidationUtil.isNull( serverDeploy.getId(),"ServerDeploy","id",resources.getId()); serverDeploy.copy(resources); serverDeployRepository.save(serverDeploy); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Long> ids) { for (Long id : ids) { serverDeployRepository.deleteById(id); } } @Override public void download(List<ServerDeployDto> queryAll, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (ServerDeployDto deployDto : queryAll) { Map<String,Object> map = new LinkedHashMap<>(); map.put("服务器名称", deployDto.getName()); map.put("服务器IP", deployDto.getIp()); map.put("端口", deployDto.getPort()); map.put("账号", deployDto.getAccount()); map.put("创建日期", deployDto.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\ServerDeployServiceImpl.java
2
请完成以下Java代码
public String getCaseId() { return caseId; } /** * Sets the value of the caseId property. * * @param value * allowed object is * {@link String } * */ public void setCaseId(String value) { this.caseId = value; } /** * Gets the value of the caseDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */
public XMLGregorianCalendar getCaseDate() { return caseDate; } /** * Sets the value of the caseDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCaseDate(XMLGregorianCalendar value) { this.caseDate = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\KvgLawType.java
1
请在Spring Boot框架中完成以下Java代码
public class SqlAcctDocLockService implements AcctDocLockService { @Override public boolean lock(final AcctDocModel docModel, final boolean force, final boolean repost) { final String tableName = docModel.getTableName(); final int recordId = docModel.getId(); final StringBuilder sql = new StringBuilder("UPDATE "); sql.append(tableName).append(" SET Processing='Y' WHERE ") .append(tableName).append("_ID=").append(recordId) .append(" AND Processed='Y' AND IsActive='Y'"); if (!force) { sql.append(" AND (Processing='N' OR Processing IS NULL)"); } if (!repost) { sql.append(" AND Posted='N'"); } final int updatedCount = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); return updatedCount == 1; } @Override public boolean unlock(final AcctDocModel docModel, @Nullable final PostingStatus newPostingStatus, @Nullable final AdIssueId postingErrorIssueId) { final String tableName = docModel.getTableName(); final POInfo poInfo = POInfo.getPOInfoNotNull(tableName); final String keyColumnName = poInfo.getKeyColumnName(); final int recordId = docModel.getId(); final StringBuilder sql = new StringBuilder("UPDATE ").append(tableName).append(" SET ") .append("Processing='N'"); // Processing (i.e. unlock it)
// // Posted if (newPostingStatus != null) { sql.append(", Posted=").append(DB.TO_STRING(newPostingStatus)); } // // PostingError_Issue_ID final String COLUMNNAME_PostingError_Issue_ID = "PostingError_Issue_ID"; final boolean hasPostingIssueColumn = poInfo.hasColumnName(COLUMNNAME_PostingError_Issue_ID); if (hasPostingIssueColumn) { if (postingErrorIssueId != null) { sql.append(", ").append(COLUMNNAME_PostingError_Issue_ID).append("=").append(postingErrorIssueId.getRepoId()); } else { sql.append(", ").append(COLUMNNAME_PostingError_Issue_ID).append(" = NULL "); } } sql.append("\n WHERE ").append(keyColumnName).append("=").append(recordId); final int updateCount = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); return updateCount == 1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\SqlAcctDocLockService.java
2
请完成以下Java代码
public void setM_Shipment_Declaration_Correction(org.compiere.model.I_M_Shipment_Declaration M_Shipment_Declaration_Correction) { set_ValueFromPO(COLUMNNAME_M_Shipment_Declaration_Correction_ID, org.compiere.model.I_M_Shipment_Declaration.class, M_Shipment_Declaration_Correction); } /** Set M_Shipment_Declaration_Correction_ID. @param M_Shipment_Declaration_Correction_ID M_Shipment_Declaration_Correction_ID */ @Override public void setM_Shipment_Declaration_Correction_ID (int M_Shipment_Declaration_Correction_ID) { if (M_Shipment_Declaration_Correction_ID < 1) set_Value (COLUMNNAME_M_Shipment_Declaration_Correction_ID, null); else set_Value (COLUMNNAME_M_Shipment_Declaration_Correction_ID, Integer.valueOf(M_Shipment_Declaration_Correction_ID)); } /** Get M_Shipment_Declaration_Correction_ID. @return M_Shipment_Declaration_Correction_ID */ @Override public int getM_Shipment_Declaration_Correction_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_Correction_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Abgabemeldung. @param M_Shipment_Declaration_ID Abgabemeldung */ @Override public void setM_Shipment_Declaration_ID (int M_Shipment_Declaration_ID) { if (M_Shipment_Declaration_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_ID, Integer.valueOf(M_Shipment_Declaration_ID)); } /** Get Abgabemeldung. @return Abgabemeldung */ @Override public int getM_Shipment_Declaration_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg 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 Process Now. @param Processing Process Now */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipment_Declaration.java
1
请在Spring Boot框架中完成以下Java代码
public class Employee { private Long id; private String name; private int age; private String position; public Employee() { } public Employee(String name, int age, String position) { this.name = name; this.age = age; this.position = position; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; }
public void setAge(int age) { this.age = age; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", position=" + position + "]"; } }
repos\sample-spring-microservices-new-master\department-service\src\main\java\pl\piomin\services\department\model\Employee.java
2
请完成以下Java代码
public int size() { return pipeList.size(); } @Override public boolean isEmpty() { return pipeList.isEmpty(); } @Override public boolean contains(Object o) { return pipeList.contains(o); } @Override public Iterator<Pipe<List<IWord>, List<IWord>>> iterator() { return pipeList.iterator(); } @Override public Object[] toArray() { return pipeList.toArray(); } @Override public <T> T[] toArray(T[] a) { return pipeList.toArray(a); } @Override public boolean add(Pipe<List<IWord>, List<IWord>> pipe) { return pipeList.add(pipe); } @Override public boolean remove(Object o) { return pipeList.remove(o); } @Override public boolean containsAll(Collection<?> c) { return pipeList.containsAll(c); } @Override public boolean addAll(Collection<? extends Pipe<List<IWord>, List<IWord>>> c) { return pipeList.addAll(c); } @Override public boolean addAll(int index, Collection<? extends Pipe<List<IWord>, List<IWord>>> c) { return pipeList.addAll(c); } @Override public boolean removeAll(Collection<?> c) { return pipeList.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return pipeList.retainAll(c); } @Override public void clear() {
pipeList.clear(); } @Override public boolean equals(Object o) { return pipeList.equals(o); } @Override public int hashCode() { return pipeList.hashCode(); } @Override public Pipe<List<IWord>, List<IWord>> get(int index) { return pipeList.get(index); } @Override public Pipe<List<IWord>, List<IWord>> set(int index, Pipe<List<IWord>, List<IWord>> element) { return pipeList.set(index, element); } @Override public void add(int index, Pipe<List<IWord>, List<IWord>> element) { pipeList.add(index, element); } @Override public Pipe<List<IWord>, List<IWord>> remove(int index) { return pipeList.remove(index); } @Override public int indexOf(Object o) { return pipeList.indexOf(o); } @Override public int lastIndexOf(Object o) { return pipeList.lastIndexOf(o); } @Override public ListIterator<Pipe<List<IWord>, List<IWord>>> listIterator() { return pipeList.listIterator(); } @Override public ListIterator<Pipe<List<IWord>, List<IWord>>> listIterator(int index) { return pipeList.listIterator(index); } @Override public List<Pipe<List<IWord>, List<IWord>>> subList(int fromIndex, int toIndex) { return pipeList.subList(fromIndex, toIndex); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\SegmentPipeline.java
1
请完成以下Java代码
public CipherDataType getCipherData() { return cipherData; } /** * Sets the value of the cipherData property. * * @param value * allowed object is * {@link CipherDataType } * */ public void setCipherData(CipherDataType value) { this.cipherData = value; } /** * Gets the value of the encryptionProperties property. * * @return * possible object is * {@link EncryptionPropertiesType } * */ public EncryptionPropertiesType getEncryptionProperties() { return encryptionProperties; } /** * Sets the value of the encryptionProperties property. * * @param value * allowed object is * {@link EncryptionPropertiesType } * */ public void setEncryptionProperties(EncryptionPropertiesType value) { this.encryptionProperties = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is
* {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the mimeType property. * * @return * possible object is * {@link String } * */ public String getMimeType() { return mimeType; } /** * Sets the value of the mimeType property. * * @param value * allowed object is * {@link String } * */ public void setMimeType(String value) { this.mimeType = value; } /** * Gets the value of the encoding property. * * @return * possible object is * {@link String } * */ public String getEncoding() { return encoding; } /** * Sets the value of the encoding property. * * @param value * allowed object is * {@link String } * */ public void setEncoding(String value) { this.encoding = 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\EncryptedType.java
1
请完成以下Java代码
public String getHtmlText() { try { StringWriter sw = new StringWriter(); new AltHTMLWriter(sw, this.document).write(); // new HTMLWriter(sw, editor.document).write(); String html = sw.toString(); return html; } catch (Exception e) { e.printStackTrace(); } return null; } public HTMLDocument getDocument() { return this.document; } @Override public void requestFocus() { this.editor.requestFocus(); } @Override public boolean requestFocus(boolean temporary) { return this.editor.requestFocus(temporary); } @Override public boolean requestFocusInWindow() { return this.editor.requestFocusInWindow(); }
public void setText(String html) { this.editor.setText(html); } public void setCaretPosition(int position) { this.editor.setCaretPosition(position); } public ActionMap getEditorActionMap() { return this.editor.getActionMap(); } public InputMap getEditorInputMap(int condition) { return this.editor.getInputMap(condition); } public Keymap getEditorKeymap() { return this.editor.getKeymap(); } public JTextComponent getTextComponent() { return this.editor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\HTMLEditor.java
1
请完成以下Java代码
public String getMetaInfo() { return metaInfo; } public void setMetaInfo(String metaInfo) { this.metaInfo = metaInfo; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getEditorSourceValueId() { return editorSourceValueId; } public void setEditorSourceValueId(String editorSourceValueId) { this.editorSourceValueId = editorSourceValueId; } public String getEditorSourceExtraValueId() { return editorSourceExtraValueId; }
public void setEditorSourceExtraValueId(String editorSourceExtraValueId) { this.editorSourceExtraValueId = editorSourceExtraValueId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean hasEditorSource() { return this.editorSourceValueId != null; } public boolean hasEditorSourceExtra() { return this.editorSourceExtraValueId != null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ModelEntityImpl.java
1
请完成以下Java代码
protected WarehouseId findOrderWarehouseId(@NonNull final I_C_Order order) { final IOrgDAO orgsRepo = Services.get(IOrgDAO.class); final OrgId adOrgId = OrgId.ofRepoId(order.getAD_Org_ID()); final boolean isSOTrx = order.isSOTrx(); // task 07014: for a dropship purchase order, we take the org info's dropship warehouse. our vendor will send the good directly to our customer and it will never enter any of our physical // warehouses, but none the less we own it for a certain time. That'S what the dropship warehouse is for. // For a sales order, "dropship" means that the order's receiver is someone other than the partner who ordered. For this scenario, we don't need a particular dropship warehouse. if (order.isDropShip() && !isSOTrx) { final WarehouseId dropShipWarehouseId = orgsRepo.getOrgDropshipWarehouseId(adOrgId); if (dropShipWarehouseId == null) { final String orgName = orgsRepo.retrieveOrgName(adOrgId); throw new AdempiereException("@NotFound@ @DropShip_Warehouse_ID@ (@AD_Org_ID@: " + orgName + ")"); } return dropShipWarehouseId; } // first check for picking warehouse // this check is valid only for sales order; for purchase order will return null final WarehouseId pickingWarehouseId = findPickingWarehouseId(order); if (pickingWarehouseId != null) { return pickingWarehouseId; } final WarehouseId orgPOWarehouseId = orgsRepo.getOrgPOWarehouseId(adOrgId); return !isSOTrx && orgPOWarehouseId != null ? orgPOWarehouseId : orgsRepo.getOrgWarehouseId(adOrgId); } /** * Retrieve the picking warehouse based on the order's bPartner. Returns <code>null</code> if the partner is not customer, has no warehouse assigned or the order is not a sales order. */ private WarehouseId findPickingWarehouseId(@NonNull final I_C_Order order) { if (!order.isSOTrx()) {
return null; } final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(order.getC_BPartner_ID()); if (bpartnerId == null) { return null; } final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class); final I_C_BPartner bp = bpartnersRepo.getById(bpartnerId); if (!bp.isCustomer()) { return null; } final WarehouseId customerWarehouseId = WarehouseId.ofRepoIdOrNull(bp.getM_Warehouse_ID()); if (customerWarehouseId != null && isPickingWarehouse(customerWarehouseId)) { return customerWarehouseId; } // if order is a purchase order, return null return null; } private boolean isPickingWarehouse(final WarehouseId warehouseId) { final IWarehouseDAO warehousesRepo = Services.get(IWarehouseDAO.class); final I_M_Warehouse warehouse = warehousesRepo.getById(warehouseId); return warehouse.isPickingWarehouse(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\warehouse\spi\impl\WarehouseAdvisor.java
1
请完成以下Java代码
private boolean isDisconnected(){ for (Vertex vertex : graph){ if (!vertex.isVisited()){ return true; } } return false; } public String originalGraphToString(){ StringBuilder sb = new StringBuilder(); for (Vertex vertex : graph){ sb.append(vertex.originalToString()); } return sb.toString(); } public void resetPrintHistory(){
for (Vertex vertex : graph){ Iterator<Map.Entry<Vertex,Edge>> it = vertex.getEdges().entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); pair.getValue().setPrinted(false); } } } public String minimumSpanningTreeToString(){ StringBuilder sb = new StringBuilder(); for (Vertex vertex : graph){ sb.append(vertex.includedToString()); } return sb.toString(); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\prim\Prim.java
1
请完成以下Java代码
public class GeodeLoggingApplicationListener implements GenericApplicationListener { private static final Class<?>[] EVENT_TYPES = { ApplicationEnvironmentPreparedEvent.class }; private static final Class<?>[] SOURCE_TYPES = { ApplicationContext.class, SpringApplication.class }; public static final String SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY = "spring.boot.data.gemfire.log.level"; public static final String SPRING_DATA_GEMFIRE_CACHE_LOG_LEVEL = "spring.data.gemfire.cache.log-level"; public static final String SPRING_DATA_GEMFIRE_LOGGING_LOG_LEVEL = "spring.data.gemfire.logging.level"; @Override public int getOrder() { return LoggingApplicationListener.DEFAULT_ORDER > Ordered.HIGHEST_PRECEDENCE ? LoggingApplicationListener.DEFAULT_ORDER - 1 : Ordered.HIGHEST_PRECEDENCE; } @Override public void onApplicationEvent(@Nullable ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { ApplicationEnvironmentPreparedEvent environmentPreparedEvent = (ApplicationEnvironmentPreparedEvent) event; onApplicationEnvironmentPreparedEvent(environmentPreparedEvent); } } protected void onApplicationEnvironmentPreparedEvent( @NonNull ApplicationEnvironmentPreparedEvent environmentPreparedEvent) { Assert.notNull(environmentPreparedEvent, "ApplicationEnvironmentPreparedEvent must not be null"); Environment environment = environmentPreparedEvent.getEnvironment(); if (isSystemPropertyNotSet(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY)) { String logLevel = environment.getProperty(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY, environment.getProperty(SPRING_DATA_GEMFIRE_LOGGING_LOG_LEVEL, environment.getProperty(SPRING_DATA_GEMFIRE_CACHE_LOG_LEVEL))); setSystemProperty(SPRING_BOOT_DATA_GEMFIRE_LOG_LEVEL_PROPERTY, logLevel); } } protected boolean isSystemPropertySet(@Nullable String propertyName) { return StringUtils.hasText(propertyName) && StringUtils.hasText(System.getProperty(propertyName)); } protected boolean isSystemPropertyNotSet(@Nullable String propertyName) {
return !isSystemPropertySet(propertyName); } protected void setSystemProperty(@NonNull String propertyName, @Nullable String propertyValue) { Assert.hasText(propertyName, () -> String.format("PropertyName [%s] is required", propertyName)); if (StringUtils.hasText(propertyValue)) { System.setProperty(propertyName, propertyValue); } } @Override public boolean supportsEventType(@NonNull ResolvableType eventType) { Class<?> rawType = eventType.getRawClass(); return rawType != null && Arrays.stream(EVENT_TYPES).anyMatch(it -> it.isAssignableFrom(rawType)); } @Override public boolean supportsSourceType(@Nullable Class<?> sourceType) { return sourceType != null && Arrays.stream(SOURCE_TYPES).anyMatch(it -> it.isAssignableFrom(sourceType)); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\context\logging\GeodeLoggingApplicationListener.java
1
请完成以下Java代码
public long getCountAll() { return getMeter(METERNAME_All).getGauge(); } @Override public void incrementCountAll() { getMeter(METERNAME_All).plusOne(); } @Override public long getCountProcessed() { return getMeter(METERNAME_Processed).getGauge(); } @Override public void incrementCountProcessed() { getMeter(METERNAME_Processed).plusOne(); } @Override public long getCountErrors() { return getMeter(METERNAME_Error).getGauge(); } @Override public void incrementCountErrors() { getMeter(METERNAME_Error).plusOne(); } @Override public long getQueueSize() { return getMeter(METERNAME_QueueSize).getGauge(); } @Override public void incrementQueueSize() { getMeter(METERNAME_QueueSize).plusOne();
} @Override public void decrementQueueSize() { getMeter(METERNAME_QueueSize).minusOne(); } @Override public long getCountSkipped() { return getMeter(METERNAME_Skipped).getGauge(); } @Override public void incrementCountSkipped() { getMeter(METERNAME_Skipped).plusOne(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\MonitorableQueueProcessorStatistics.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonProduct { @NonNull @JsonProperty("id") String id; @Nullable @JsonProperty("parentId") String parentId; @Nullable @JsonProperty("name") String name; @NonNull @JsonProperty("productNumber") String productNumber; @Nullable @JsonProperty("ean") String ean; @Nullable @JsonProperty("unitId") String unitId; @Nullable @JsonProperty("tax") JsonTax jsonTax; @NonNull @JsonProperty("createdAt") ZonedDateTime createdAt; @Nullable
@JsonProperty("updatedAt") ZonedDateTime updatedAt; @Nullable @JsonProperty("price") List<JsonPrice> prices; @JsonIgnoreProperties(ignoreUnknown = true) @JsonPOJOBuilder(withPrefix = "") static class JsonProductBuilder { } @JsonIgnore @NonNull public ZonedDateTime getUpdatedAtNonNull() { if (updatedAt != null) { return updatedAt; } return createdAt; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\api\model\product\JsonProduct.java
2
请完成以下Java代码
public Booking createBooking(String hotelId, String checkIn, int nights, int guests, String guestName) { Objects.requireNonNull(hotelId, "hotelId"); Objects.requireNonNull(checkIn, "checkIn"); Objects.requireNonNull(guestName, "guestName"); LocalDate.parse(checkIn); Hotel hotel = inventory.stream() .filter(h -> h.id().equalsIgnoreCase(hotelId)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Unknown hotelId: " + hotelId)); if (hotel.maxGuests() < guests) { throw new IllegalArgumentException("Guest count exceeds hotel maxGuests"); } HotelOffer offer = toOffer(hotel, nights, guests); return new Booking( "BK-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase(), hotel.id(), hotel.name(), hotel.city(), checkIn, nights, guests, guestName, offer.totalPrice(), "CONFIRMED" ); } private HotelOffer toOffer(Hotel hotel, int nights, int guests) { int perNight = hotel.basePricePerNight() + Math.max(0, guests - 1) * 25; int total = Math.max(1, nights) * perNight; return new HotelOffer(hotel.id(), hotel.name(), hotel.city(), perNight, total, hotel.maxGuests()); }
public record Hotel(String id, String name, String city, int basePricePerNight, int maxGuests) { } public record HotelOffer( String hotelId, String hotelName, String city, int pricePerNight, int totalPrice, int maxGuests ) { } public record Booking( String bookingId, String hotelId, String hotelName, String city, String checkIn, int nights, int guests, String guestName, int totalPrice, String status ) { } }
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\simpleopenai\HotelService.java
1
请完成以下Java代码
public void evict(Object key) { // 删除的时候要先删除二级缓存再删除一级缓存,否则有并发问题 redisCache.evict(key); if (usedFirstCache) { // 删除一级缓存需要用到redis的Pub/Sub(订阅/发布)模式,否则集群中其他服服务器节点的一级缓存数据无法删除 Map<String, Object> message = new HashMap<>(); message.put("cacheName", name); message.put("key", key); // 创建redis发布者 RedisPublisher redisPublisher = new RedisPublisher(redisOperations, ChannelTopicEnum.REDIS_CACHE_DELETE_TOPIC.getChannelTopic()); // 发布消息 redisPublisher.publisher(message); } } @Override public void clear() { redisCache.clear(); if (usedFirstCache) { // 清除一级缓存需要用到redis的订阅/发布模式,否则集群中其他服服务器节点的一级缓存数据无法删除 Map<String, Object> message = new HashMap<>(); message.put("cacheName", name); // 创建redis发布者 RedisPublisher redisPublisher = new RedisPublisher(redisOperations, ChannelTopicEnum.REDIS_CACHE_CLEAR_TOPIC.getChannelTopic()); // 发布消息 redisPublisher.publisher(message); } } @Override protected Object lookup(Object key) { Object value = null; if (usedFirstCache) { value = caffeineCache.get(key); logger.debug("查询一级缓存 key:{},返回值是:{}", key, JSON.toJSONString(value)); } if (value == null) { value = redisCache.get(key); logger.debug("查询二级缓存 key:{},返回值是:{}", key, JSON.toJSONString(value));
} return value; } /** * 查询二级缓存 * * @param key * @param valueLoader * @return */ private <T> Object getForSecondaryCache(Object key, Callable<T> valueLoader) { T value = redisCache.get(key, valueLoader); logger.debug("查询二级缓存 key:{},返回值是:{}", key, JSON.toJSONString(value)); return toStoreValue(value); } }
repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\layering\LayeringCache.java
1
请完成以下Java代码
public void setMemo (final @Nullable java.lang.String Memo) { set_Value (COLUMNNAME_Memo, Memo); } @Override public java.lang.String getMemo() { return get_ValueAsString(COLUMNNAME_Memo); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setReconciledBy_SAP_GLJournal_ID (final int ReconciledBy_SAP_GLJournal_ID) { if (ReconciledBy_SAP_GLJournal_ID < 1) set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournal_ID, null); else set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournal_ID, ReconciledBy_SAP_GLJournal_ID); } @Override public int getReconciledBy_SAP_GLJournal_ID() { return get_ValueAsInt(COLUMNNAME_ReconciledBy_SAP_GLJournal_ID); } @Override public void setReconciledBy_SAP_GLJournalLine_ID (final int ReconciledBy_SAP_GLJournalLine_ID) { if (ReconciledBy_SAP_GLJournalLine_ID < 1) set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournalLine_ID, null); else set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournalLine_ID, ReconciledBy_SAP_GLJournalLine_ID); } @Override public int getReconciledBy_SAP_GLJournalLine_ID() { return get_ValueAsInt(COLUMNNAME_ReconciledBy_SAP_GLJournalLine_ID); } @Override public void setReferenceNo (final @Nullable java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } @Override public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setStatementLineDate (final java.sql.Timestamp StatementLineDate) { set_Value (COLUMNNAME_StatementLineDate, StatementLineDate); } @Override public java.sql.Timestamp getStatementLineDate() { return get_ValueAsTimestamp(COLUMNNAME_StatementLineDate); }
@Override public void setStmtAmt (final BigDecimal StmtAmt) { set_Value (COLUMNNAME_StmtAmt, StmtAmt); } @Override public BigDecimal getStmtAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTrxAmt (final BigDecimal TrxAmt) { set_Value (COLUMNNAME_TrxAmt, TrxAmt); } @Override public BigDecimal getTrxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValutaDate (final java.sql.Timestamp ValutaDate) { set_Value (COLUMNNAME_ValutaDate, ValutaDate); } @Override public java.sql.Timestamp getValutaDate() { return get_ValueAsTimestamp(COLUMNNAME_ValutaDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementLine.java
1
请完成以下Java代码
public class TasklistContainerBootstrap implements ServletContextListener { protected TasklistEnvironment environment; @Override public void contextInitialized(ServletContextEvent sce) { environment = createTasklistEnvironment(); environment.setup(); WebApplicationUtil.setApplicationServer(sce.getServletContext().getServerInfo()); } @Override public void contextDestroyed(ServletContextEvent sce) { environment.tearDown(); } protected TasklistEnvironment createTasklistEnvironment() { return new TasklistEnvironment(); } protected static class TasklistEnvironment {
public void tearDown() { Tasklist.setTasklistRuntimeDelegate(null); } public void setup() { Tasklist.setTasklistRuntimeDelegate(new DefaultTasklistRuntimeDelegate()); } protected RuntimeContainerDelegate getContainerRuntimeDelegate() { return RuntimeContainerDelegate.INSTANCE.get(); } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\tasklist\impl\web\bootstrap\TasklistContainerBootstrap.java
1
请完成以下Java代码
public BigDecimal getValueAsBigDecimal(final BigDecimal defaultValueIfNull) { return value != null ? toBigDecimal(value) : defaultValueIfNull; } @SuppressWarnings("unused") public Optional<BigDecimal> getValueAsBigDecimalOptional() { return Optional.ofNullable(getValueAsBigDecimal(null)); } @Nullable private static BigDecimal toBigDecimal(@Nullable final Object value) { if (value == null) { return null; } else if (value instanceof BigDecimal) { return (BigDecimal)value; } else { final String valueStr = value.toString().trim(); if (valueStr.isEmpty()) { return null; } return new BigDecimal(valueStr); } } public ZonedDateTime getValueAsZonedDateTime() { return DateTimeConverters.fromObjectToZonedDateTime(value); } public LocalDate getValueAsLocalDate() { return DateTimeConverters.fromObjectToLocalDate(value); } public IntegerLookupValue getValueAsIntegerLookupValue() { return DataTypes.convertToIntegerLookupValue(value); } public LookupValue getValueAsStringLookupValue() { if (value == null) { return null; } else if (value instanceof Map) { @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>)value; return JSONLookupValue.stringLookupValueFromJsonMap(map); } else if (value instanceof JSONLookupValue) { final JSONLookupValue json = (JSONLookupValue)value; return json.toIntegerLookupValue();
} else { throw new AdempiereException("Cannot convert value '" + value + "' (" + value.getClass() + ") to " + IntegerLookupValue.class); } } @Nullable public <T extends ReferenceListAwareEnum> T getValueAsEnum(@NonNull final Class<T> enumType) { if (value == null) { return null; } else if (enumType.isInstance(value)) { //noinspection unchecked return (T)value; } final String valueStr; if (value instanceof Map) { @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>)value; final LookupValue.StringLookupValue lookupValue = JSONLookupValue.stringLookupValueFromJsonMap(map); valueStr = lookupValue.getIdAsString(); } else if (value instanceof JSONLookupValue) { final JSONLookupValue json = (JSONLookupValue)value; valueStr = json.getKey(); } else { valueStr = value.toString(); } try { return ReferenceListAwareEnums.ofNullableCode(valueStr, enumType); } catch (Exception ex) { throw new AdempiereException("Failed converting `" + value + "` (" + value.getClass().getSimpleName() + ") to " + enumType.getSimpleName(), ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentChangedEvent.java
1
请完成以下Java代码
public class WebAuthnAuthenticationRequestToken extends AbstractAuthenticationToken { @Serial private static final long serialVersionUID = -1682693433877522403L; private final RelyingPartyAuthenticationRequest webAuthnRequest; /** * Creates a new instance. * @param webAuthnRequest the {@link RelyingPartyAuthenticationRequest} to use for * authentication. Cannot be null. */ public WebAuthnAuthenticationRequestToken(RelyingPartyAuthenticationRequest webAuthnRequest) { super(AuthorityUtils.NO_AUTHORITIES); Assert.notNull(webAuthnRequest, "webAuthnRequest cannot be null"); this.webAuthnRequest = webAuthnRequest; } /** * Gets the {@link RelyingPartyAuthenticationRequest} * @return the {@link RelyingPartyAuthenticationRequest} */ public RelyingPartyAuthenticationRequest getWebAuthnRequest() { return this.webAuthnRequest; }
@Override public void setAuthenticated(boolean authenticated) { Assert.isTrue(!authenticated, "Cannot set this token to trusted"); super.setAuthenticated(authenticated); } @Override public Object getCredentials() { return this.webAuthnRequest.getPublicKey(); } @Override public @Nullable Object getPrincipal() { return this.webAuthnRequest.getPublicKey().getResponse().getUserHandle(); } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\authentication\WebAuthnAuthenticationRequestToken.java
1
请完成以下Java代码
public TaxCategoryId computeTaxCategoryId() { final IPricingContext pricingCtx = createPricingContext() .setDisallowDiscount(true); // don't bother computing discounts; we know that the tax category is not related to them. final IPricingResult pricingResult = pricingBL.calculatePrice(pricingCtx); if (!pricingResult.isCalculated()) { final I_C_OrderLine orderLine = request.getOrderLine(); throw new ProductNotOnPriceListException(pricingCtx, orderLine.getLine()) .setParameter("log", pricingResult.getLoggableMessages()); } return pricingResult.getTaxCategoryId(); } public IPricingResult computePrices()
{ final IEditablePricingContext pricingCtx = createPricingContext(); return pricingBL.calculatePrice(pricingCtx); } public PriceLimitRuleResult computePriceLimit() { final I_C_OrderLine orderLine = request.getOrderLine(); return pricingBL.computePriceLimit(PriceLimitRuleContext.builder() .pricingContext(createPricingContext()) .priceLimit(orderLine.getPriceLimit()) .priceActual(orderLine.getPriceActual()) .paymentTermId(orderLineBL.getPaymentTermId(orderLine)) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLinePriceCalculator.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getNumberOfPackages() { return numberOfPackages; } /** * Sets the value of the numberOfPackages property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setNumberOfPackages(BigDecimal value) { this.numberOfPackages = value; } /** * Gets the value of the customersPackagingNumber property. * * @return * possible object is * {@link String } * */ public String getCustomersPackagingNumber() { return customersPackagingNumber; } /** * Sets the value of the customersPackagingNumber property. * * @param value * allowed object is * {@link String } * */ public void setCustomersPackagingNumber(String value) { this.customersPackagingNumber = value; } /** * Gets the value of the suppliersPackagingNumber property. * * @return * possible object is * {@link String } * */ public String getSuppliersPackagingNumber() { return suppliersPackagingNumber; }
/** * Sets the value of the suppliersPackagingNumber property. * * @param value * allowed object is * {@link String } * */ public void setSuppliersPackagingNumber(String value) { this.suppliersPackagingNumber = value; } /** * Gets the value of the packagingCapacity property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getPackagingCapacity() { return packagingCapacity; } /** * Sets the value of the packagingCapacity property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setPackagingCapacity(BigDecimal value) { this.packagingCapacity = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PackagingDetailsType.java
2
请完成以下Java代码
public Long getAverageRt() { return averageRt; } public void setAverageRt(Long averageRt) { this.averageRt = averageRt; } public Long getSuccessQps() { return successQps; } public void setSuccessQps(Long successQps) { this.successQps = successQps; } public Long getExceptionQps() { return exceptionQps; } public void setExceptionQps(Long exceptionQps) { this.exceptionQps = exceptionQps; } public Long getOneMinutePass() { return oneMinutePass; } public void setOneMinutePass(Long oneMinutePass) { this.oneMinutePass = oneMinutePass; } public Long getOneMinuteBlock() { return oneMinuteBlock; } public void setOneMinuteBlock(Long oneMinuteBlock) { this.oneMinuteBlock = oneMinuteBlock; } public Long getOneMinuteException() {
return oneMinuteException; } public void setOneMinuteException(Long oneMinuteException) { this.oneMinuteException = oneMinuteException; } public Long getOneMinuteTotal() { return oneMinuteTotal; } public void setOneMinuteTotal(Long oneMinuteTotal) { this.oneMinuteTotal = oneMinuteTotal; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public List<ResourceTreeNode> getChildren() { return children; } public void setChildren(List<ResourceTreeNode> children) { this.children = children; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\ResourceTreeNode.java
1
请完成以下Spring Boot application配置
server.port=9999 # Mysql 数据源配置 spring.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=xxxxxx spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 初始化时建立物理连接的个数 spring.datasource.druid.initial-size=5 # 最大连接池数量 spring.datasource.druid.max-active=30 # 最小连接池数量 spring.datasource.druid.min-idle=5 # 获取连接时最大等待时间,单位毫秒 spring.datasource.druid.max-wait=60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 spring.datasource.druid.time-between-eviction-runs-millis=60000 # 连接保持空闲而不被驱逐的最小时间 spring.datasource.druid.min-evictable-idle-time-millis=300000 # 用来检测连接是否有效的sql,要求是一个查询语句 spring.datasource.druid.validation-query=SELECT 1 FROM DUAL # 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 spring.datasource.druid.test-while-idle=true # 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 spring.datasource.druid.test-on-borrow=false # 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 spring.datasource.druid.test-on-return=false # 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。 spring.datasource.druid.pool-prepared-statements=true # 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。 spring.datasource.druid.max-pool-prepared-statement-per-connection-size=50 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计 spring.datasource.druid.f
ilters=stat,wall # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 # 合并多个DruidDataSource的监控数据 spring.datasource.druid.use-global-data-source-stat=true # 关于Druid可视化界面登录的权限控制 spring.datasource.druid.stat-view-servlet.login-username=admin spring.datasource.druid.stat-view-servlet.login-password=123 spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/* # mybatis配置 mybatis.mapper-locations=classpath:mapper/*.xml mybatis.configuration.map-underscore-to-camel-case=true
repos\Spring-Boot-In-Action-master\springbt_uid_generator\uid-consumer\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
private static Collection<? extends OrderByField> createOrderByFields(Table table, Sort sortToUse) { List<OrderByField> fields = new ArrayList<>(); for (Sort.Order order : sortToUse) { String propertyName = order.getProperty(); OrderByField orderByField = !propertyName.contains(".") ? OrderByField.from(table.column(propertyName).as(EntityManager.ALIAS_PREFIX + propertyName)) : createOrderByField(propertyName); fields.add(order.isAscending() ? orderByField.asc() : orderByField.desc()); } return fields; } /** * Creates an OrderByField instance for sorting a query by the specified property. * * @param propertyName The full property name in the format "tableName.columnName". * @return An OrderByField instance for sorting by the specified property. */ private static OrderByField createOrderByField(String propertyName) { // Split the propertyName into table name and column name String[] parts = propertyName.split("\\."); String tableName = parts[0]; String columnName = parts[1]; // Create and return an OrderByField instance return OrderByField.from( // Create a column with the given name and alias it with the table name and column name Column.aliased( columnName, // Create a table alias with the same name as the table Table.aliased(camelCaseToSnakeCase(tableName), tableName),
// Use a composite alias of "tableName_columnName" String.format("%s_%s", tableName, columnName) ) ); } /** * Converts a camel case string to snake case. * * @param input The camel case string to be converted to snake case. * @return The input string converted to snake case. */ public static String camelCaseToSnakeCase(String input) { // Regular Expression String regex = "([a-z])([A-Z]+)"; // Replacement string String replacement = "$1_$2"; // Replace the given regex // with replacement string // and convert it to lower case. return input.replaceAll(regex, replacement).toLowerCase(); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\repository\EntityManager.java
2
请完成以下Java代码
public String getIcon() { return "InfoBPartner16"; } @Override public boolean isAvailable() { final int adClientId = Env.getAD_Client_ID(Env.getCtx()); if (!Services.get(ISysConfigBL.class).getBooleanValue("UI_EnableBPartnerContextMenu", true, adClientId)) { return false; } final VEditor editor = getEditor(); final GridField gridField = editor.getField(); if (gridField == null) { return false; } if (!gridField.isLookup()) { return false; } final Lookup lookup = gridField.getLookup(); if (lookup == null) { // No Lookup??? log.warn("No lookup found for " + gridField + " even if is marked as Lookup"); return false; } final String tableName = lookup.getTableName(); if (!I_C_BPartner.Table_Name.equals(tableName)) { return false; } return true; } @Override public boolean isRunnable() { final VEditor editor = getEditor(); return editor.isReadWrite(); } @Override public void run() {
final VEditor editor = getEditor(); final GridField gridField = editor.getField(); final Lookup lookup = gridField.getLookup(); final int windowNo = gridField.getWindowNo(); final VBPartner vbp = new VBPartner(Env.getWindow(windowNo), windowNo); int BPartner_ID = 0; // if update, get current value if (!createNew) { final Object value = editor.getValue(); if (value instanceof Integer) BPartner_ID = ((Integer)value).intValue(); else if (value != null) BPartner_ID = Integer.parseInt(value.toString()); } vbp.loadBPartner(BPartner_ID); vbp.setVisible(true); // get result int result = vbp.getC_BPartner_ID(); if (result == 0 // 0 = not saved && result == BPartner_ID) // the same return; // Maybe new BPartner - put in cache lookup.getDirect(IValidationContext.NULL, new Integer(result), false, true); // actionCombo (new Integer(result)); // data binding gridField.getGridTab().setValue(gridField, result); } // actionBPartner }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\BPartnerNewUpdateContextEditorAction.java
1
请在Spring Boot框架中完成以下Java代码
public class Employee { @ApiModelProperty(notes = "The database generated employee ID") private long id; @ApiModelProperty(notes = "The employee first name") private String firstName; @ApiModelProperty(notes = "The employee last name") private String lastName; @ApiModelProperty(notes = "The employee email id") private String emailId; public Employee() { } public Employee(String firstName, String lastName, String emailId) { this.firstName = firstName; this.lastName = lastName; this.emailId = emailId; } @Id @GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; } @Column(name = "first_name", nullable = false)
public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "last_name", nullable = false) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name = "email_address", nullable = false) public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId=" + emailId + "]"; } }
repos\Spring-Boot-Advanced-Projects-main\springboot2-jpa-swagger2\src\main\java\net\alanbinu\springboot2\springboot2swagger2\model\Employee.java
2
请完成以下Java代码
public class SessionFixationProtectionEvent extends AbstractAuthenticationEvent { @Serial private static final long serialVersionUID = -2554621992006921150L; private final String oldSessionId; private final String newSessionId; /** * Constructs a new session fixation protection event. * @param authentication The authentication object * @param oldSessionId The old session ID before it was changed * @param newSessionId The new session ID after it was changed */ public SessionFixationProtectionEvent(Authentication authentication, String oldSessionId, String newSessionId) { super(authentication); Assert.hasLength(oldSessionId, "oldSessionId must have length"); Assert.hasLength(newSessionId, "newSessionId must have length"); this.oldSessionId = oldSessionId; this.newSessionId = newSessionId; } /** * Getter for the session ID before it was changed.
* @return the old session ID. */ public String getOldSessionId() { return this.oldSessionId; } /** * Getter for the session ID after it was changed. * @return the new session ID. */ public String getNewSessionId() { return this.newSessionId; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\session\SessionFixationProtectionEvent.java
1
请完成以下Java代码
public class SerializeOptionalTypeExample { public static void main(String[] args) { User user1 = new User(); user1.setUserId(1l); user1.setFirstName("baeldung"); serializeObject(user1, "user1.ser"); UserOptionalField user2 = new UserOptionalField(); user2.setUserId(1l); user2.setFirstName(Optional.of("baeldung")); serializeObject(user2, "user2.ser"); } public static void serializeObject(Object object, String fileName) { // Serialization
try { FileOutputStream file = new FileOutputStream(fileName); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(object); out.close(); file.close(); System.out.println("Object " + object.toString() + " has been serialized to file " + fileName); } catch (IOException e) { e.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-optional\src\main\java\com\baeldung\optionalreturntype\SerializeOptionalTypeExample.java
1
请在Spring Boot框架中完成以下Java代码
public class Store { @Id @GeneratedValue private int id; private String name; @Embedded private Address address; @OneToMany( mappedBy = "store", cascade = CascadeType.ALL, orphanRemoval = true ) private List<Product> products = new ArrayList<>(); public Store(String name, Address address) { this.name = name; this.address = address; } public Store() { } public String getName() { return name; } public void setName(String name) { this.name = name;
} public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void addProduct(Product product) { product.setStore(this); this.products.add(product); } public List<Product> getProducts() { return this.products; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\javers\domain\Store.java
2
请完成以下Java代码
public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public byte getState() { return state; } public void setState(byte state) { this.state = state; } public List<SysRole> getRoleList() { return roleList;
} public void setRoleList(List<SysRole> roleList) { this.roleList = roleList; } /** * Salt * @return */ public String getCredentialsSalt(){ return this.username+this.salt; } }
repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\UserInfo.java
1
请完成以下Java代码
protected TaskEntityManager getTaskEntityManager() { return getProcessEngineConfiguration().getTaskEntityManager(); } protected IdentityLinkEntityManager getIdentityLinkEntityManager() { return getProcessEngineConfiguration().getIdentityLinkEntityManager(); } protected EventSubscriptionEntityManager getEventSubscriptionEntityManager() { return getProcessEngineConfiguration().getEventSubscriptionEntityManager(); } protected VariableInstanceEntityManager getVariableInstanceEntityManager() { return getProcessEngineConfiguration().getVariableInstanceEntityManager(); } protected JobEntityManager getJobEntityManager() { return getProcessEngineConfiguration().getJobEntityManager(); } protected TimerJobEntityManager getTimerJobEntityManager() { return getProcessEngineConfiguration().getTimerJobEntityManager(); } protected SuspendedJobEntityManager getSuspendedJobEntityManager() { return getProcessEngineConfiguration().getSuspendedJobEntityManager(); } protected DeadLetterJobEntityManager getDeadLetterJobEntityManager() { return getProcessEngineConfiguration().getDeadLetterJobEntityManager(); } protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() { return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager();
} protected HistoricDetailEntityManager getHistoricDetailEntityManager() { return getProcessEngineConfiguration().getHistoricDetailEntityManager(); } protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() { return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager(); } protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() { return getProcessEngineConfiguration().getHistoricVariableInstanceEntityManager(); } protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() { return getProcessEngineConfiguration().getHistoricTaskInstanceEntityManager(); } protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() { return getProcessEngineConfiguration().getHistoricIdentityLinkEntityManager(); } protected AttachmentEntityManager getAttachmentEntityManager() { return getProcessEngineConfiguration().getAttachmentEntityManager(); } protected CommentEntityManager getCommentEntityManager() { return getProcessEngineConfiguration().getCommentEntityManager(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java
1
请完成以下Java代码
public static ValueNamePair of( @JsonProperty("v") final String value, @JsonProperty("n") final String name, @JsonProperty("description") final String description, @JsonProperty("validationInformation") @Nullable final ValueNamePairValidationInformation validationInformation) { if (Objects.equals(value, EMPTY.getValue()) && Objects.equals(name, EMPTY.getName()) && validationInformation == null) { return EMPTY; } return new ValueNamePair(value, name, description, validationInformation); } /** * Construct KeyValue Pair * * @param value value * @param name string representation */ public ValueNamePair(final String value, final String name, final String help) { super(name, help); m_value = value == null ? "" : value; m_validationInformation = null; } // ValueNamePair public ValueNamePair( final String value, final String name, final String help, @Nullable final ValueNamePairValidationInformation validationInformation) { super(name, help); m_value = value == null ? "" : value; m_validationInformation = validationInformation; } // ValueNamePair /** * The Value */ private final String m_value; /** * Get Value * * @return Value */ @JsonProperty("v") public String getValue() { return m_value; } // getValue /** * Get Validation Message * * @return Validation Message */ @JsonProperty("validationInformation")
@JsonInclude(JsonInclude.Include.NON_NULL) public ValueNamePairValidationInformation getValidationInformation() { return m_validationInformation; } /** * Get ID * * @return Value */ @Override @JsonIgnore public String getID() { return m_value; } // getID @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof ValueNamePair) { final ValueNamePair other = (ValueNamePair)obj; return Objects.equals(this.m_value, other.m_value) && Objects.equals(this.getName(), other.getName()) && Objects.equals(this.m_validationInformation, other.m_validationInformation); } return false; } // equals @Override public int hashCode() { return m_value.hashCode(); } // hashCode } // KeyValuePair
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ValueNamePair.java
1
请在Spring Boot框架中完成以下Java代码
public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Boolean getBoss() { return boss; } public void setBoss(Boolean boss) { this.boss = boss; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; }
public List<Object> getList() { return list; } public void setList(List<Object> list) { this.list = list; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } @Override public String toString() { final StringBuilder sb = new StringBuilder( "{\"Person\":{" ); sb.append( "\"lastName\":\"" ) .append( lastName ).append( '\"' ); sb.append( ",\"age\":" ) .append( age ); sb.append( ",\"boss\":" ) .append( boss ); sb.append( ",\"birth\":\"" ) .append( birth ).append( '\"' ); sb.append( ",\"map\":" ) .append( map ); sb.append( ",\"list\":" ) .append( list ); sb.append( ",\"dog\":" ) .append( dog ); sb.append( "}}" ); return sb.toString(); } }
repos\SpringBootLearning-master (1)\springboot-config\src\main\java\com\gf\entity\Person.java
2
请完成以下Java代码
private List<IHUDocumentLine> createHUDocumentLines(final HUDocumentsCollector documentsCollector, final I_M_InOut inOut) { final List<I_M_InOutLine> ioLines = Services.get(IInOutDAO.class).retrieveLines(inOut); if (ioLines.isEmpty()) { throw AdempiereException.newWithTranslatableMessage("@NoLines@ (@M_InOut_ID@: " + inOut.getDocumentNo() + ")"); } final List<IHUDocumentLine> sourceLines = new ArrayList<>(ioLines.size()); for (final I_M_InOutLine ioLine : ioLines) { // // Create HU Document Line final List<I_M_Transaction> mtrxs = Services.get(IMTransactionDAO.class).retrieveReferenced(ioLine); for (final I_M_Transaction mtrx : mtrxs) { final MInOutLineHUDocumentLine sourceLine = new MInOutLineHUDocumentLine(ioLine, mtrx); sourceLines.add(sourceLine);
} // // Create Target Qty final Capacity targetCapacity = Capacity.createCapacity( ioLine.getMovementQty(), // qty ProductId.ofRepoId(ioLine.getM_Product_ID()), uomDAO.getById(ioLine.getC_UOM_ID()), false // allowNegativeCapacity ); documentsCollector.getTargetCapacities().add(targetCapacity); } return sourceLines; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\MInOutHUDocumentFactory.java
1
请完成以下Java代码
public final ProductsProposalView createView(@NonNull final ProductsProposalView parentView) { final PriceListVersionId basePriceListVersionId = parentView.getBasePriceListVersionIdOrFail(); final ProductsProposalRowsData rowsData = ProductsProposalRowsLoader.builder() .bpartnerProductStatsService(bpartnerProductStatsService) .orderProductProposalsService(orderProductProposalsService) .lookupDataSourceFactory(lookupDataSourceFactory) // .priceListVersionId(basePriceListVersionId) .productIdsToExclude(parentView.getProductIds()) .bpartnerId(parentView.getBpartnerId().orElse(null)) .currencyId(parentView.getCurrencyId()) .soTrx(parentView.getSoTrx()) // .build().load(); logger.debug("loaded ProductsProposalRowsData with size={} for basePriceListVersionId={}", basePriceListVersionId, rowsData.size()); final ProductsProposalView view = ProductsProposalView.builder() .windowId(getWindowId()) .rowsData(rowsData) .processes(getRelatedProcessDescriptors()) .initialViewId(parentView.getInitialViewId()) .build(); put(view); return view; } @Override
protected List<RelatedProcessDescriptor> getRelatedProcessDescriptors() { return ImmutableList.of( createProcessDescriptor(WEBUI_ProductsProposal_AddProductFromBasePriceList.class)); } @Override public ProductsProposalView filterView( final IView view, final JSONFilterViewRequest filterViewRequest, final Supplier<IViewsRepository> viewsRepo) { final ProductsProposalView productsProposalView = ProductsProposalView.cast(view); final ProductsProposalViewFilter filter = ProductsProposalViewFilters.extractPackageableViewFilterVO(filterViewRequest); productsProposalView.filter(filter); return productsProposalView; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\BasePLVProductsProposalViewFactory.java
1
请完成以下Java代码
public class PaymentDto { private String type; private Double amount; public PaymentDto() { } public PaymentDto(String type, Double amount) { this.type = type; this.amount = amount; } public String getType() {
return type; } public void setType(String type) { this.type = type; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } }
repos\tutorials-master\mapstruct-3\src\main\java\com\baeldung\dto\PaymentDto.java
1
请完成以下Java代码
public void setCamundaIntegration(String camundaIntegration) { this.camundaIntegration = camundaIntegration; } public LicenseKeyDataImpl getLicenseKey() { return licenseKey; } public void setLicenseKey(LicenseKeyDataImpl licenseKey) { this.licenseKey = licenseKey; } public synchronized Set<String> getWebapps() { return webapps; } public synchronized void setWebapps(Set<String> webapps) { this.webapps = webapps; } public void markOccurrence(String name) { markOccurrence(name, 1); } public void markOccurrence(String name, long times) { CommandCounter counter = commands.get(name); if (counter == null) { synchronized (commands) { if (counter == null) { counter = new CommandCounter(name);
commands.put(name, counter); } } } counter.mark(times); } public synchronized void addWebapp(String webapp) { if (!webapps.contains(webapp)) { webapps.add(webapp); } } public void clearCommandCounts() { commands.clear(); } public void clear() { commands.clear(); licenseKey = null; applicationServer = null; webapps.clear(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\diagnostics\DiagnosticsRegistry.java
1
请完成以下Java代码
public void setC_ServiceLevelLine_ID (int C_ServiceLevelLine_ID) { if (C_ServiceLevelLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ServiceLevelLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ServiceLevelLine_ID, Integer.valueOf(C_ServiceLevelLine_ID)); } /** Get Service Level Line. @return Product Revenue Recognition Service Level Line */ public int getC_ServiceLevelLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ServiceLevelLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Service date. @param ServiceDate Date service was provided */ public void setServiceDate (Timestamp ServiceDate) { set_ValueNoCheck (COLUMNNAME_ServiceDate, ServiceDate); } /** Get Service date.
@return Date service was provided */ public Timestamp getServiceDate () { return (Timestamp)get_Value(COLUMNNAME_ServiceDate); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getServiceDate())); } /** Set Quantity Provided. @param ServiceLevelProvided Quantity of service or product provided */ public void setServiceLevelProvided (BigDecimal ServiceLevelProvided) { set_ValueNoCheck (COLUMNNAME_ServiceLevelProvided, ServiceLevelProvided); } /** Get Quantity Provided. @return Quantity of service or product provided */ public BigDecimal getServiceLevelProvided () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ServiceLevelProvided); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ServiceLevelLine.java
1
请完成以下Java代码
static class AgeCalculator { private AgeCalculator() { } public static int calculateAge(String birthDate) throws CalculationException { if (birthDate == null || birthDate.isEmpty()) { throw new IllegalArgumentException(); } try { return Period .between(parseDate(birthDate), LocalDate.now()) .getYears(); } catch (DateParseException ex) { throw new CalculationException(ex); } } private static LocalDate parseDate(String birthDateAsString) throws DateParseException { LocalDate birthDate; try { birthDate = LocalDate.parse(birthDateAsString); } catch (DateTimeParseException ex) { throw new InvalidFormatException(birthDateAsString, ex); } if (birthDate.isAfter(LocalDate.now())) { throw new DateOutOfRangeException(birthDateAsString); } return birthDate; } } static class CalculationException extends Exception { CalculationException(DateParseException ex) { super(ex); } } static class DateParseException extends Exception {
DateParseException(String input) { super(input); } DateParseException(String input, Throwable thr) { super(input, thr); } } static class InvalidFormatException extends DateParseException { InvalidFormatException(String input, Throwable thr) { super("Invalid date format: " + input, thr); } } static class DateOutOfRangeException extends DateParseException { DateOutOfRangeException(String date) { super("Date out of range: " + date); } } }
repos\tutorials-master\core-java-modules\core-java-exceptions-2\src\main\java\com\baeldung\rootcausefinder\RootCauseFinder.java
1
请完成以下Java代码
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { return Mono .fromRunnable(() -> restTemplate.getForObject(buildUrl(), Void.class, createMessage(event, instance))); } protected String buildUrl() { return String.format("%s/bot%s/sendmessage?chat_id={chat_id}&text={text}&parse_mode={parse_mode}" + "&disable_notification={disable_notification}", this.apiUrl, this.authToken); } private Map<String, Object> createMessage(InstanceEvent event, Instance instance) { Map<String, Object> parameters = new HashMap<>(); parameters.put("chat_id", this.chatId); parameters.put("parse_mode", this.parseMode); parameters.put("disable_notification", this.disableNotify); parameters.put("text", createContent(event, instance)); return parameters; } @Override protected String getDefaultMessage() { return DEFAULT_MESSAGE; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public String getApiUrl() { return apiUrl; } public void setApiUrl(String apiUrl) { this.apiUrl = apiUrl; } @Nullable public String getChatId() {
return chatId; } public void setChatId(@Nullable String chatId) { this.chatId = chatId; } @Nullable public String getAuthToken() { return authToken; } public void setAuthToken(@Nullable String authToken) { this.authToken = authToken; } public boolean isDisableNotify() { return disableNotify; } public void setDisableNotify(boolean disableNotify) { this.disableNotify = disableNotify; } public String getParseMode() { return parseMode; } public void setParseMode(String parseMode) { this.parseMode = parseMode; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\TelegramNotifier.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getM_Package_ID())); } /** Set Package Line. @param M_PackageLine_ID The detail content of the Package */ public void setM_PackageLine_ID (int M_PackageLine_ID) { if (M_PackageLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PackageLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PackageLine_ID, Integer.valueOf(M_PackageLine_ID)); } /** Get Package Line. @return The detail content of the Package */ public int getM_PackageLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PackageLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Quantity. @param Qty Quantity
*/ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PackageLine.java
1
请完成以下Java代码
public AtJwtBuilder validators(Consumer<Map<String, OAuth2TokenValidator<Jwt>>> validators) { validators.accept(this.validators); return this; } /** * Build the validator * @return the RFC 9068 validator */ public OAuth2TokenValidator<Jwt> build() { List.of(JoseHeaderNames.TYP, JwtClaimNames.EXP, JwtClaimNames.SUB, JwtClaimNames.IAT, JwtClaimNames.JTI, JwtClaimNames.ISS, JwtClaimNames.AUD, "client_id") .forEach((name) -> Assert.isTrue(this.validators.containsKey(name), name + " must be validated")); return new DelegatingOAuth2TokenValidator<>(this.validators.values()); } } private static final class RequireClaimValidator implements OAuth2TokenValidator<Jwt> { private final String claimName; RequireClaimValidator(String claimName) { this.claimName = claimName; } @Override public OAuth2TokenValidatorResult validate(Jwt token) { if (token.getClaim(this.claimName) == null) { return OAuth2TokenValidatorResult .failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, this.claimName + " must have a value", "https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure")); } return OAuth2TokenValidatorResult.success(); } OAuth2TokenValidator<Jwt> isEqualTo(String value) { return and(satisfies((jwt) -> value.equals(jwt.getClaim(this.claimName)))); } OAuth2TokenValidator<Jwt> satisfies(Predicate<Jwt> predicate) { return and((jwt) -> {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, this.claimName + " is not valid", "https://datatracker.ietf.org/doc/html/rfc9068#name-data-structure"); if (predicate.test(jwt)) { return OAuth2TokenValidatorResult.success(); } return OAuth2TokenValidatorResult.failure(error); }); } OAuth2TokenValidator<Jwt> and(OAuth2TokenValidator<Jwt> that) { return (jwt) -> { OAuth2TokenValidatorResult result = validate(jwt); return (result.hasErrors()) ? result : that.validate(jwt); }; } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtValidators.java
1
请完成以下Java代码
public String get_ValueAsString(final String variableName) { if (!has_Variable(variableName)) { return ""; } final Object value = POJOWrapper.this.getValuesMap().get(variableName); return value == null ? "" : value.toString(); } @Override public boolean has_Variable(final String variableName) { return POJOWrapper.this.hasColumnName(variableName); } @Override public String get_ValueOldAsString(final String variableName) { throw new UnsupportedOperationException("not implemented"); } }; } public IModelInternalAccessor getModelInternalAccessor() { if (_modelInternalAccessor == null) { _modelInternalAccessor = new POJOModelInternalAccessor(this); } return _modelInternalAccessor; }
POJOModelInternalAccessor _modelInternalAccessor = null; public static IModelInternalAccessor getModelInternalAccessor(final Object model) { final POJOWrapper wrapper = getWrapper(model); if (wrapper == null) { return null; } return wrapper.getModelInternalAccessor(); } public boolean isProcessed() { return hasColumnName("Processed") ? StringUtils.toBoolean(getValue("Processed", Object.class)) : false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOWrapper.java
1
请完成以下Java代码
public String getId() { return id; } public String getKey() { return key; } public String getCategory() { return category; } public String getName() { return name; } public int getVersion() {
return version; } public String getResource() { return resource; } public String getDeploymentId() { return deploymentId; } public String getContextPath() { return contextPath; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\caseDefinition\HalCaseDefinition.java
1
请完成以下Java代码
public ELResolver getELResolver() { return elResolver; } public FunctionMapper getFunctionMapper() { if (functions == null) { functions = new ActivitiFunctionMapper(); } return functions; } public VariableMapper getVariableMapper() { if (variables == null) { variables = new ActivitiVariablesMapper(); } return variables; }
public void setFunction(String prefix, String localName, Method method) { if (functions == null) { functions = new ActivitiFunctionMapper(); } functions.setFunction(prefix, localName, method); } public ValueExpression setVariable(String name, ValueExpression expression) { if (variables == null) { variables = new ActivitiVariablesMapper(); } return variables.setVariable(name, expression); } }
repos\Activiti-develop\activiti-core-common\activiti-expression-language\src\main\java\org\activiti\core\el\ActivitiElContext.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Mail Template. @param R_MailText_ID Text templates for mailings */
public void setR_MailText_ID (int R_MailText_ID) { if (R_MailText_ID < 1) set_ValueNoCheck (COLUMNNAME_R_MailText_ID, null); else set_ValueNoCheck (COLUMNNAME_R_MailText_ID, Integer.valueOf(R_MailText_ID)); } /** Get Mail Template. @return Text templates for mailings */ public int getR_MailText_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_MailText_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_MailText.java
1
请完成以下Java代码
public final class InvoiceCandidateGenerateRequest { public static InvoiceCandidateGenerateRequest of(final IInvoiceCandidateHandler handler, final Object model) { return new InvoiceCandidateGenerateRequest(handler, model); } public static List<InvoiceCandidateGenerateRequest> ofAll(@NonNull final List<? extends IInvoiceCandidateHandler> handlers, @NonNull final List<?> models) { if (handlers.isEmpty() || models.isEmpty()) { return ImmutableList.of(); } final ImmutableList.Builder<InvoiceCandidateGenerateRequest> requests = ImmutableList.builder(); for (final Object model : models) { for (final IInvoiceCandidateHandler handler : handlers) { requests.add(InvoiceCandidateGenerateRequest.of(handler, model)); } } return requests.build(); } private final IInvoiceCandidateHandler handler; private final Object model;
private InvoiceCandidateGenerateRequest(@NonNull final IInvoiceCandidateHandler handler, @NonNull final Object model) { this.handler = handler; this.model = model; } public IInvoiceCandidateHandler getHandler() { return handler; } public <T> T getModel(final Class<T> modelClass) { return InterfaceWrapperHelper.create(model, modelClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\InvoiceCandidateGenerateRequest.java
1
请完成以下Java代码
public String getTUName() { return wrappedHUInfo.getTUName(); } @Override public int getQtyTU() { return qtyTU; } @Override public IHandlingUnitsInfo add(@NonNull final IHandlingUnitsInfo infoToAdd) { Check.assume(Objects.equals(infoToAdd.getTUName(), this.getTUName()), "infoToAdd {} has a TUName that differs from ours {}", infoToAdd, this); return new PlainHandlingUnitsInfo( wrappedHUInfo.getTUName(), wrappedHUInfo.getQtyTU() + infoToAdd.getQtyTU());
} @Override public void setQtyTU(int qtyTU) { this.qtyTU = qtyTU; } @Override public String toString() { return ObjectUtils.toString(this); } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\spi\impl\HandlingUnitsInfoFactory.java
1
请完成以下Java代码
public void uncaughtException(Thread t, Throwable e) { LOGGER.error("unhandled exception in thread: " + t.getId() + ":" + t.getName(), e); } }); } return thread; } /** * Get the method invoker's class name * * @param depth * @return */ private String getInvoker(int depth) { Exception e = new Exception(); StackTraceElement[] stes = e.getStackTrace(); if (stes.length > depth) { return ClassUtils.getShortClassName(stes[depth].getClassName()); } return getClass().getSimpleName(); } /** * Get sequence for different naming prefix * * @param invoker * @return */ private long getSequence(String invoker) { AtomicLong r = this.sequences.get(invoker); if (r == null) { r = new AtomicLong(0); AtomicLong previous = this.sequences.putIfAbsent(invoker, r); if (previous != null) { r = previous; } } return r.incrementAndGet();
} /** * Getters & Setters */ public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isDaemon() { return daemon; } public void setDaemon(boolean daemon) { this.daemon = daemon; } public UncaughtExceptionHandler getUncaughtExceptionHandler() { return uncaughtExceptionHandler; } public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) { this.uncaughtExceptionHandler = handler; } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\utils\NamingThreadFactory.java
1
请完成以下Java代码
public class ParallelStreamApplication { public long usingCollectionsParallel(Collection<Book> listOfbooks, int year) { AtomicLong countOfBooks = new AtomicLong(); listOfbooks.parallelStream() .forEach(book -> { if (book.getYearPublished() == year) { countOfBooks.getAndIncrement(); } }); return countOfBooks.get(); } public long usingStreamParallel(Collection<Book> listOfBooks, int year) { AtomicLong countOfBooks = new AtomicLong(); listOfBooks.stream() .parallel() .forEach(book -> { if (book.getYearPublished() == year) { countOfBooks.getAndIncrement(); }
}); return countOfBooks.get(); } public long usingWithCustomSpliterator(MyBookContainer<Book> listOfBooks, int year) { AtomicLong countOfBooks = new AtomicLong(); listOfBooks.parallelStream() .forEach(book -> { if (book.getYearPublished() == year) { countOfBooks.getAndIncrement(); } }); return countOfBooks.get(); } }
repos\tutorials-master\core-java-modules\core-java-streams-5\src\main\java\com\baeldung\streams\parallelstream\ParallelStreamApplication.java
1
请完成以下Java代码
public SetRemovalTimeToHistoricDecisionInstancesBuilder calculatedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); this.mode = Mode.CALCULATED_REMOVAL_TIME; return this; } public SetRemovalTimeToHistoricDecisionInstancesBuilder clearedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); mode = Mode.CLEARED_REMOVAL_TIME; return this; } public SetRemovalTimeToHistoricDecisionInstancesBuilder hierarchical() { isHierarchical = true; return this; } public Batch executeAsync() { return commandExecutor.execute(new SetRemovalTimeToHistoricDecisionInstancesCmd(this)); } public HistoricDecisionInstanceQuery getQuery() { return query;
} public List<String> getIds() { return ids; } public Date getRemovalTime() { return removalTime; } public Mode getMode() { return mode; } public enum Mode { CALCULATED_REMOVAL_TIME, ABSOLUTE_REMOVAL_TIME, CLEARED_REMOVAL_TIME; } public boolean isHierarchical() { return isHierarchical; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricDecisionInstancesBuilderImpl.java
1
请完成以下Java代码
public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } public String getValidationMessage() { return validationMessage; } public void setValidationMessage(String validationMessage) { this.validationMessage = validationMessage; } public Boolean isStrictMode() { return strictMode; } public void setStrictMode(Boolean strictMode) { this.strictMode = strictMode; } public Map<String, String> getInputVariableTypes() { return inputVariableTypes; } public void setInputVariableTypes(Map<String, String> inputVariableTypes) { this.inputVariableTypes = inputVariableTypes; } public Map<String, String> getDecisionResultTypes() { return decisionResultTypes; } public void addDecisionResultType(String decisionResultId, String decisionResultType) { this.decisionResultTypes.put(decisionResultId, decisionResultType); } protected static boolean isBoolean(Object obj) { return obj instanceof Boolean; } protected static boolean isDate(Object obj) {
return (obj instanceof Date || obj instanceof DateTime || obj instanceof LocalDate || obj instanceof java.time.LocalDate || obj instanceof LocalDateTime || obj instanceof Instant); } protected static boolean isNumber(Object obj) { return obj instanceof Number; } protected Map<String, Object> createDefensiveCopyInputVariables(Map<String, Object> inputVariables) { Map<String, Object> defensiveCopyMap = new HashMap<>(); if (inputVariables != null) { for (Map.Entry<String, Object> entry : inputVariables.entrySet()) { Object newValue = null; if (entry.getValue() == null) { // do nothing } else if (entry.getValue() instanceof Long) { newValue = Long.valueOf(((Long) entry.getValue()).longValue()); } else if (entry.getValue() instanceof Double) { newValue = Double.valueOf(((Double) entry.getValue()).doubleValue()); } else if (entry.getValue() instanceof Integer) { newValue = Integer.valueOf(((Integer) entry.getValue()).intValue()); } else if (entry.getValue() instanceof Date) { newValue = new Date(((Date) entry.getValue()).getTime()); } else if (entry.getValue() instanceof Boolean) { newValue = Boolean.valueOf(((Boolean) entry.getValue()).booleanValue()); } else { newValue = new String(entry.getValue().toString()); } defensiveCopyMap.put(entry.getKey(), newValue); } } return defensiveCopyMap; } }
repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\DecisionExecutionAuditContainer.java
1
请完成以下Java代码
public ResponseEntity<JsonOLCandCreateBulkResponse> createOrderLineCandidate(@RequestBody @NonNull final JsonOLCandCreateRequest request) { return createOrderLineCandidates(JsonOLCandCreateBulkRequest.of(request)); } @PostMapping(PATH_BULK) public ResponseEntity<JsonOLCandCreateBulkResponse> createOrderLineCandidates(@RequestBody @NonNull final JsonOLCandCreateBulkRequest bulkRequest) { try { bulkRequest.validate(); final MasterdataProvider masterdataProvider = MasterdataProvider.builder() .permissionService(permissionServiceFactory.createPermissionService()) .bpartnerRestController(bpartnerRestController) .externalReferenceRestControllerService(externalReferenceRestControllerService) .jsonRetrieverService(jsonRetrieverService) .externalSystemRepository(externalSystemRepository) .bPartnerMasterdataProvider(bPartnerMasterdataProvider) .build(); final ITrxManager trxManager = Services.get(ITrxManager.class); final JsonOLCandCreateBulkResponse response = trxManager .callInNewTrx(() -> orderCandidateRestControllerService.creatOrderLineCandidatesBulk(bulkRequest, masterdataProvider)); return Check.isEmpty(response.getErrors()) ? new ResponseEntity<>(response, HttpStatus.CREATED) : new ResponseEntity<>(response, HttpStatus.MULTI_STATUS); } catch (final Exception ex) { logger.warn("Got exception while processing {}", bulkRequest, ex); final String adLanguage = Env.getADLanguageOrBaseLanguage();
return ResponseEntity.badRequest() .body(JsonOLCandCreateBulkResponse.error(JsonErrors.ofThrowable(ex, adLanguage))); } } @PutMapping(PATH_PROCESS) public ResponseEntity<JsonProcessCompositeResponse> processOLCands(@RequestBody @NonNull final JsonOLCandProcessRequest request) { try { final JsonProcessCompositeResponse response = orderCandidateRestControllerService.processOLCands(request); return ResponseEntity.ok(response); } catch (final Exception ex) { logger.warn("Got exception while processing {}", request, ex); return ResponseEntity.badRequest().build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\OrderCandidatesRestController.java
1
请完成以下Java代码
public static WFProcessId ofIdPart(@NonNull final MobileApplicationId applicationId, @NonNull final RepoIdAware idPart) { return new WFProcessId(applicationId, String.valueOf(idPart.getRepoId())); } private static final String SEPARATOR = "-"; @Getter private final MobileApplicationId applicationId; private final String idPart; private transient String stringRepresentation = null; private WFProcessId( @NonNull final MobileApplicationId applicationId, @NonNull final String idPart) { this.applicationId = applicationId; this.idPart = Check.assumeNotEmpty(idPart, "idPart"); } @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { String stringRepresentation = this.stringRepresentation; if (stringRepresentation == null) { stringRepresentation = this.stringRepresentation = applicationId.getAsString() + SEPARATOR + idPart; } return stringRepresentation; } @Nullable public static String getAsStringOrNull(@Nullable final WFProcessId id) { return id != null ? id.getAsString() : null; } @NonNull public <ID extends RepoIdAware> ID getRepoId(@NonNull final Function<Integer, ID> idMapper) {
try { final int repoIdInt = Integer.parseInt(idPart); return idMapper.apply(repoIdInt); } catch (final Exception ex) { throw new AdempiereException("Failed converting " + this + " to ID", ex); } } @NonNull public <ID extends RepoIdAware> ID getRepoIdAssumingApplicationId(@NonNull MobileApplicationId expectedApplicationId, @NonNull final Function<Integer, ID> idMapper) { assertApplicationId(expectedApplicationId); return getRepoId(idMapper); } public void assertApplicationId(@NonNull final MobileApplicationId expectedApplicationId) { if (!Objects.equals(this.applicationId, expectedApplicationId)) { throw new AdempiereException("Expected applicationId `" + expectedApplicationId + "` but was `" + this.applicationId + "`"); } } public static boolean equals(@Nullable final WFProcessId id1, @Nullable final WFProcessId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFProcessId.java
1
请完成以下Java代码
public java.lang.String getPath() { return get_ValueAsString(COLUMNNAME_Path); } @Override public void setRemoteAddr (final @Nullable java.lang.String RemoteAddr) { set_Value (COLUMNNAME_RemoteAddr, RemoteAddr); } @Override public java.lang.String getRemoteAddr() { return get_ValueAsString(COLUMNNAME_RemoteAddr); } @Override public void setRemoteHost (final @Nullable java.lang.String RemoteHost) { set_Value (COLUMNNAME_RemoteHost, RemoteHost); } @Override public java.lang.String getRemoteHost() { return get_ValueAsString(COLUMNNAME_RemoteHost); } @Override public void setRequestURI (final @Nullable java.lang.String RequestURI) { set_Value (COLUMNNAME_RequestURI, RequestURI); } @Override public java.lang.String getRequestURI() { return get_ValueAsString(COLUMNNAME_RequestURI); } /** * Status AD_Reference_ID=541316 * Reference name: StatusList */ public static final int STATUS_AD_Reference_ID=541316; /** Empfangen = Empfangen */ public static final String STATUS_Empfangen = "Empfangen"; /** Verarbeitet = Verarbeitet */ public static final String STATUS_Verarbeitet = "Verarbeitet"; /** Fehler = Fehler */ public static final String STATUS_Fehler = "Fehler"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus()
{ return get_ValueAsString(COLUMNNAME_Status); } @Override public void setTime (final java.sql.Timestamp Time) { set_Value (COLUMNNAME_Time, Time); } @Override public java.sql.Timestamp getTime() { return get_ValueAsTimestamp(COLUMNNAME_Time); } @Override public void setUI_Trace_ExternalId (final @Nullable java.lang.String UI_Trace_ExternalId) { set_Value (COLUMNNAME_UI_Trace_ExternalId, UI_Trace_ExternalId); } @Override public java.lang.String getUI_Trace_ExternalId() { return get_ValueAsString(COLUMNNAME_UI_Trace_ExternalId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Request_Audit.java
1
请完成以下Java代码
public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } /** * The nested class for {@link StatusChecker}'s names * <pre> * registry= org.apache.dubbo.registry.status.RegistryStatusChecker * spring= org.apache.dubbo.config.spring.status.SpringStatusChecker * datasource= org.apache.dubbo.config.spring.status.DataSourceStatusChecker * memory= org.apache.dubbo.common.status.support.MemoryStatusChecker * load= org.apache.dubbo.common.status.support.LoadStatusChecker * server= org.apache.dubbo.rpc.protocol.dubbo.status.ServerStatusChecker * threadpool= org.apache.dubbo.rpc.protocol.dubbo.status.ThreadPoolStatusChecker * </pre> * * @see StatusChecker */ public static class Status { /** * The defaults names of {@link StatusChecker} * <p> * The defaults : "memory", "load"
*/ private Set<String> defaults = new LinkedHashSet<>(Arrays.asList("memory", "load")); /** * The extra names of {@link StatusChecker} */ private Set<String> extras = new LinkedHashSet<>(); public Set<String> getDefaults() { return defaults; } public void setDefaults(Set<String> defaults) { this.defaults = defaults; } public Set<String> getExtras() { return extras; } public void setExtras(Set<String> extras) { this.extras = extras; } } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\health\DubboHealthIndicatorProperties.java
1
请完成以下Java代码
public final void setClaimTypeConverterFactory( Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory) { Assert.notNull(claimTypeConverterFactory, "claimTypeConverterFactory cannot be null"); this.claimTypeConverterFactory = claimTypeConverterFactory; } /** * Sets the {@code Predicate} used to determine if the UserInfo Endpoint should be * called to retrieve information about the End-User (Resource Owner). * <p> * By default, the UserInfo Endpoint is called if all the following are true: * <ul> * <li>The user info endpoint is defined on the ClientRegistration</li> * <li>The Client Registration uses the * {@link AuthorizationGrantType#AUTHORIZATION_CODE}</li> * </ul> * @param retrieveUserInfo the {@code Predicate} used to determine if the UserInfo * Endpoint should be called * @since 6.3
*/ public final void setRetrieveUserInfo(Predicate<OidcUserRequest> retrieveUserInfo) { Assert.notNull(retrieveUserInfo, "retrieveUserInfo cannot be null"); this.retrieveUserInfo = retrieveUserInfo; } /** * Allows converting from the {@link OidcUserSource} to and {@link OidcUser}. * @param oidcUserConverter the {@link Converter} to use. Cannot be null. */ public void setOidcUserConverter(Converter<OidcUserSource, OidcUser> oidcUserConverter) { Assert.notNull(oidcUserConverter, "oidcUserConverter cannot be null"); this.oidcUserConverter = oidcUserConverter; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\userinfo\OidcUserService.java
1
请在Spring Boot框架中完成以下Java代码
public class JDBCController { @Autowired private DataSource dataSource; @RequestMapping("/commit") public List<Map<String, String>> select() { List<Map<String, String>> results = new ArrayList<>(); try { Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); statement.executeQuery("SELECT * FROM student"); connection.commit(); } catch (Exception e) { throw new IllegalStateException(e); } return results; } @RequestMapping("/rollback") public List<Map<String, String>> rollback() { List<Map<String, String>> results = new ArrayList<>();
try (Connection connection = dataSource.getConnection()) { connection.rollback(); } catch (Exception e) { throw new IllegalStateException(e); } return results; } @RequestMapping("/query-error") public void error() { try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.execute("SELECT UNDEFINED()"); } catch (Exception ignored) { } } }
repos\tutorials-master\spring-boot-modules\spring-boot-3-observation\src\main\java\com\baeldung\p6spy\controllers\JDBCController.java
2
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Direct Deploy. @param DirectDeploy Direct Deploy */ public void setDirectDeploy (String DirectDeploy) { set_Value (COLUMNNAME_DirectDeploy, DirectDeploy); } /** Get Direct Deploy. @return Direct Deploy */ public String getDirectDeploy () { return (String)get_Value(COLUMNNAME_DirectDeploy); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Summary Level. @param IsSummary This is a summary entity */ public void setIsSummary (boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary)); } /** Get Summary Level. @return This is a summary entity */ public boolean isSummary () { Object oo = get_Value(COLUMNNAME_IsSummary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** MediaType AD_Reference_ID=388 */ public static final int MEDIATYPE_AD_Reference_ID=388; /** image/gif = GIF */ public static final String MEDIATYPE_ImageGif = "GIF"; /** image/jpeg = JPG */ public static final String MEDIATYPE_ImageJpeg = "JPG"; /** image/png = PNG */ public static final String MEDIATYPE_ImagePng = "PNG"; /** application/pdf = PDF */ public static final String MEDIATYPE_ApplicationPdf = "PDF"; /** text/css = CSS */ public static final String MEDIATYPE_TextCss = "CSS"; /** text/js = JS */ public static final String MEDIATYPE_TextJs = "JS";
/** Set Media Type. @param MediaType Defines the media type for the browser */ public void setMediaType (String MediaType) { set_Value (COLUMNNAME_MediaType, MediaType); } /** Get Media Type. @return Defines the media type for the browser */ public String getMediaType () { return (String)get_Value(COLUMNNAME_MediaType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media.java
1
请完成以下Java代码
protected final QueueWorkPackageId getQueueWorkPackageId() { Check.assumeNotNull(workpackage, "workpackage not null"); return QueueWorkPackageId.ofRepoId(this.workpackage.getC_Queue_WorkPackage_ID()); } /** * @return <code>true</code>, i.e. ask the executor to run this processor in transaction (backward compatibility) */ @Override public boolean isRunInTransaction() { return true; } @Override public boolean isAllowRetryOnError() { return true; } @Override public final Optional<ILock> getElementsLock() { final String elementsLockOwnerName = getParameters().getParameterAsString(PARAMETERNAME_ElementsLockOwner); if (Check.isBlank(elementsLockOwnerName)) { return Optional.empty(); // no lock was created for this workpackage } final LockOwner elementsLockOwner = LockOwner.forOwnerName(elementsLockOwnerName); try { final ILock existingLockForOwner = Services.get(ILockManager.class).getExistingLockForOwner(elementsLockOwner); return Optional.of(existingLockForOwner); } catch (final LockFailedException e) { // this can happen, if e.g. there was a restart, or if the WP was flagged as error once Loggables.addLog("Missing lock for ownerName={}; was probably cleaned up meanwhile", elementsLockOwnerName); return Optional.empty(); } } /** * Returns the {@link NullLatchStrategy}. */ @Override
public ILatchStragegy getLatchStrategy() { return NullLatchStrategy.INSTANCE; } public final <T> List<T> retrieveItems(final Class<T> modelType) { return Services.get(IQueueDAO.class).retrieveAllItemsSkipMissing(getC_Queue_WorkPackage(), modelType); } /** * Retrieves all active POs, even the ones that are caught in other packages */ public final <T> List<T> retrieveAllItems(final Class<T> modelType) { return Services.get(IQueueDAO.class).retrieveAllItems(getC_Queue_WorkPackage(), modelType); } public final List<I_C_Queue_Element> retrieveQueueElements(final boolean skipAlreadyScheduledItems) { return Services.get(IQueueDAO.class).retrieveQueueElements(getC_Queue_WorkPackage(), skipAlreadyScheduledItems); } /** * retrieves all active PO's IDs, even the ones that are caught in other packages */ public final Set<Integer> retrieveAllItemIds() { return Services.get(IQueueDAO.class).retrieveAllItemIds(getC_Queue_WorkPackage()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackageProcessorAdapter.java
1
请完成以下Java代码
public class AD_Table_CopyColumnsToAllAcctDocTables extends JavaProcess implements IProcessPrecondition { private final IADTableDAO adTablesRepo = Services.get(IADTableDAO.class); private final AcctDocRegistry acctDocRegistry = SpringContextHolder.instance.getBean(AcctDocRegistry.class); private static final String TABLENAME_X_AcctDocTableTemplate = "X_AcctDocTableTemplate"; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal(); } final AdTableId adTableId = AdTableId.ofRepoId(context.getSingleSelectedRecordId()); String tableName = adTablesRepo.retrieveTableName(adTableId); if (!TABLENAME_X_AcctDocTableTemplate.equals(tableName)) { return ProcessPreconditionsResolution.rejectWithInternalReason("Not the accountable doc table template"); } return ProcessPreconditionsResolution.accept(); } @Override @RunOutOfTrx protected String doIt() { final I_AD_Table acctDocTableTemplate = adTablesRepo.retrieveTable(TABLENAME_X_AcctDocTableTemplate); final List<I_AD_Column> acctDocTableTemplateColumns = adTablesRepo.retrieveColumnsForTable(acctDocTableTemplate); for (final String acctDocTableName : acctDocRegistry.getDocTableNames())
{ final I_AD_Table acctDocTable = adTablesRepo.retrieveTable(acctDocTableName); final CopyColumnsResult result = CopyColumnsProducer.newInstance() .setLogger(Loggables.nop()) .setTargetTable(acctDocTable) .setSourceColumns(acctDocTableTemplateColumns) .setSyncDatabase(true) .create(); addLog("" + result); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\AD_Table_CopyColumnsToAllAcctDocTables.java
1
请在Spring Boot框架中完成以下Java代码
public void setStreet(String value) { this.street = value; } /** * Post-office box. * * @return * possible object is * {@link String } * */ public String getPOBox() { return poBox; } /** * Sets the value of the poBox property. * * @param value * allowed object is * {@link String } * */ public void setPOBox(String value) { this.poBox = value; } /** * City information. * * @return * possible object is * {@link String } * */ public String getTown() { return town; } /** * Sets the value of the town property. * * @param value * allowed object is * {@link String } * */ public void setTown(String value) { this.town = value; } /** * ZIP code. * * @return * possible object is * {@link String } * */ public String getZIP() { return zip; } /** * Sets the value of the zip property. * * @param value * allowed object is * {@link String } *
*/ public void setZIP(String value) { this.zip = value; } /** * Country information. * * @return * possible object is * {@link CountryType } * */ public CountryType getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link CountryType } * */ public void setCountry(CountryType value) { this.country = value; } /** * Any further elements or attributes which are necessary for an address may be provided here. * Note that extensions should be used with care and only those extensions shall be used, which are officially provided by ERPEL. * Gets the value of the addressExtension property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the addressExtension property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAddressExtension().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAddressExtension() { if (addressExtension == null) { addressExtension = new ArrayList<String>(); } return this.addressExtension; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AddressType.java
2
请完成以下Java代码
public java.lang.String getMessageID () { return (java.lang.String)get_Value(COLUMNNAME_MessageID); } @Override public org.compiere.model.I_R_Request getR_Request() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_R_Request_ID, org.compiere.model.I_R_Request.class); } @Override public void setR_Request(org.compiere.model.I_R_Request R_Request) { set_ValueFromPO(COLUMNNAME_R_Request_ID, org.compiere.model.I_R_Request.class, R_Request); } /** Set Aufgabe. @param R_Request_ID Request from a Business Partner or Prospect */ @Override public void setR_Request_ID (int R_Request_ID) { if (R_Request_ID < 1) set_Value (COLUMNNAME_R_Request_ID, null); else set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID)); } /** Get Aufgabe. @return Request from a Business Partner or Prospect */ @Override public int getR_Request_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Betreff. @param Subject Mail Betreff */ @Override public void setSubject (java.lang.String Subject) { set_Value (COLUMNNAME_Subject, Subject); }
/** Get Betreff. @return Mail Betreff */ @Override public java.lang.String getSubject () { return (java.lang.String)get_Value(COLUMNNAME_Subject); } @Override public org.compiere.model.I_AD_User getTo_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setTo_User(org.compiere.model.I_AD_User To_User) { set_ValueFromPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class, To_User); } /** Set To User. @param To_User_ID To User */ @Override public void setTo_User_ID (int To_User_ID) { if (To_User_ID < 1) set_Value (COLUMNNAME_To_User_ID, null); else set_Value (COLUMNNAME_To_User_ID, Integer.valueOf(To_User_ID)); } /** Get To User. @return To User */ @Override public int getTo_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_To_User_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Mail.java
1
请完成以下Java代码
protected String doIt() { final ImmutableSet<ResourceId> resourceIds = getSelectedResourceIds(); final QRCodePDFResource pdf = resourceQRCodePrintService.createPDF(resourceIds); getResult().setReportData(pdf, pdf.getFilename(), pdf.getContentType()); return MSG_OK; } private ImmutableSet<ResourceId> getSelectedResourceIds() { final IView view = getView(); return getSelectedRowIdsAsSet() .stream() .map(view::getTableRecordReferenceOrNull) .filter(Objects::nonNull) .map(recordRef -> ResourceId.ofRepoId(recordRef.getRecord_ID())) .collect(ImmutableSet.toImmutableSet()); } private Set<DocumentId> getSelectedRowIdsAsSet() {
final IView view = getView(); final DocumentIdsSelection rowIds = getSelectedRowIds(); final Set<DocumentId> rowIdsEffective; if (rowIds.isEmpty()) { return ImmutableSet.of(); } else if (rowIds.isAll()) { rowIdsEffective = view.streamByIds(DocumentIdsSelection.ALL) .map(IViewRow::getId) .collect(ImmutableSet.toImmutableSet()); } else { rowIdsEffective = rowIds.toSet(); } return rowIdsEffective; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\resource\process\S_Resource_PrintQRCodes.java
1
请完成以下Java代码
public boolean isValidHuForReturn(final InOutId inOutId, final HuId huId) { final Optional<AttributeId> serialNoAttributeIdOptional = serialNoBL.getSerialNoAttributeId(); if (!serialNoAttributeIdOptional.isPresent()) { return false; } final AttributeId serialNoAttributeId = serialNoAttributeIdOptional.get(); final I_M_HU hu = handlingUnitsDAO.getById(huId); final I_M_HU_Attribute serialNoAttr = huAttributesDAO.retrieveAttribute(hu, serialNoAttributeId); if (serialNoAttr == null) { //no S/N defined. Should not be a valid scenario return false; } final Set<HuId> huIds = getHUIdsByInOutIds(Collections.singleton(inOutId)); if (huIds.isEmpty()) { return true; } final ImmutableSet<HuId> topLevelHUs = handlingUnitsBL.getTopLevelHUs(huIds); return !handlingUnitsBL.createHUQueryBuilder().addOnlyHUIds(topLevelHUs) .addHUStatusToInclude(X_M_HU.HUSTATUS_Planning) .addOnlyWithAttribute(AttributeConstants.ATTR_SerialNo, serialNoAttr.getValue()) .createQueryBuilder() .create() .anyMatch(); } @Override public void validateMandatoryOnShipmentAttributes(@NonNull final I_M_InOut shipment) { final List<I_M_InOutLine> inOutLines = retrieveLines(shipment, I_M_InOutLine.class);
for (final I_M_InOutLine line : inOutLines) { final AttributeSetInstanceId asiID = AttributeSetInstanceId.ofRepoIdOrNull(line.getM_AttributeSetInstance_ID()); if (asiID == null) { continue; } final ProductId productId = ProductId.ofRepoId(line.getM_Product_ID()); final List<I_M_HU> husForLine = huAssignmentDAO.retrieveTopLevelHUsForModel(line); for (final I_M_HU hu : husForLine) { huAttributesBL.validateMandatoryShipmentAttributes(HuId.ofRepoId(hu.getM_HU_ID()), productId); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\HUInOutBL.java
1
请完成以下Java代码
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (name.equals("toUnsignedString0")) { logger.info("Visiting unsigned method"); return tracer.visitMethod(ACC_PUBLIC + ACC_STATIC, name, desc, signature, exceptions); } return tracer.visitMethod(access, name, desc, signature, exceptions); } public void visitEnd() { tracer.visitEnd(); System.out.println(tracer.p.getText()); } } public class AddFieldAdapter extends ClassVisitor { String fieldName; int access; boolean isFieldPresent; public AddFieldAdapter(String fieldName, int access, ClassVisitor cv) { super(ASM4, cv); this.cv = cv; this.access = access; this.fieldName = fieldName; }
@Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (name.equals(fieldName)) { isFieldPresent = true; } return cv.visitField(access, name, desc, signature, value); } @Override public void visitEnd() { if (!isFieldPresent) { FieldVisitor fv = cv.visitField(access, fieldName, Type.BOOLEAN_TYPE.toString(), null, null); if (fv != null) { fv.visitEnd(); } } cv.visitEnd(); } } }
repos\tutorials-master\libraries-bytecode\src\main\java\com\baeldung\asm\CustomClassWriter.java
1
请完成以下Java代码
public int getCS_Creditpass_BP_Group_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_BP_Group_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config getCS_Creditpass_Config() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_CS_Creditpass_Config_ID, de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config.class); } @Override public void setCS_Creditpass_Config(de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config CS_Creditpass_Config) { set_ValueFromPO(COLUMNNAME_CS_Creditpass_Config_ID, de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config.class, CS_Creditpass_Config); } /** Get Creditpass Einstellung. @return Creditpass Einstellung */ @Override
public int getCS_Creditpass_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_Config_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Creditpass Einstellung. @param CS_Creditpass_Config_ID Creditpass Einstellung */ @Override public void setCS_Creditpass_Config_ID (int CS_Creditpass_Config_ID) { if (CS_Creditpass_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_ID, Integer.valueOf(CS_Creditpass_Config_ID)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_BP_Group.java
1
请在Spring Boot框架中完成以下Java代码
public void putPDFCache(String key, String value) { pdfCache.put(key, value); } @Override public void putImgCache(String key, List<String> value) { imgCache.put(key, value); } @Override public Map<String, String> getPDFCache() { return pdfCache; } @Override public String getPDFCache(String key) { return pdfCache.get(key); } @Override public Map<String, List<String>> getImgCache() { return imgCache; } @Override public List<String> getImgCache(String key) { if(StringUtils.isEmpty(key)){ return new ArrayList<>(); } return imgCache.get(key); } @Override public Integer getPdfImageCache(String key) { return pdfImagesCache.get(key); } @Override public void putPdfImageCache(String pdfFilePath, int num) { pdfImagesCache.put(pdfFilePath, num); } @Override public Map<String, String> getMediaConvertCache() { return mediaConvertCache; } @Override public void putMediaConvertCache(String key, String value) { mediaConvertCache.put(key, value); } @Override public String getMediaConvertCache(String key) {
return mediaConvertCache.get(key); } @Override public void cleanCache() { initPDFCachePool(CacheService.DEFAULT_PDF_CAPACITY); initIMGCachePool(CacheService.DEFAULT_IMG_CAPACITY); initPdfImagesCachePool(CacheService.DEFAULT_PDFIMG_CAPACITY); initMediaConvertCachePool(CacheService.DEFAULT_MEDIACONVERT_CAPACITY); } @Override public void addQueueTask(String url) { blockingQueue.add(url); } @Override public String takeQueueTask() throws InterruptedException { return blockingQueue.take(); } @Override public void initPDFCachePool(Integer capacity) { pdfCache = new ConcurrentLinkedHashMap.Builder<String, String>() .maximumWeightedCapacity(capacity).weigher(Weighers.singleton()) .build(); } @Override public void initIMGCachePool(Integer capacity) { imgCache = new ConcurrentLinkedHashMap.Builder<String, List<String>>() .maximumWeightedCapacity(capacity).weigher(Weighers.singleton()) .build(); } @Override public void initPdfImagesCachePool(Integer capacity) { pdfImagesCache = new ConcurrentLinkedHashMap.Builder<String, Integer>() .maximumWeightedCapacity(capacity).weigher(Weighers.singleton()) .build(); } @Override public void initMediaConvertCachePool(Integer capacity) { mediaConvertCache = new ConcurrentLinkedHashMap.Builder<String, String>() .maximumWeightedCapacity(capacity).weigher(Weighers.singleton()) .build(); } }
repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceJDKImpl.java
2
请完成以下Java代码
public List<IncidentEntity> findIncidentsByExecution(String id) { return getDbEntityManager().selectList("selectIncidentsByExecutionId", id); } @SuppressWarnings("unchecked") public List<IncidentEntity> findIncidentsByProcessInstance(String id) { return getDbEntityManager().selectList("selectIncidentsByProcessInstanceId", id); } public long findIncidentCountByQueryCriteria(IncidentQueryImpl incidentQuery) { configureQuery(incidentQuery); return (Long) getDbEntityManager().selectOne("selectIncidentCountByQueryCriteria", incidentQuery); } public Incident findIncidentById(String id) { return (Incident) getDbEntityManager().selectById(IncidentEntity.class, id); } public List<Incident> findIncidentByConfiguration(String configuration) { return findIncidentByConfigurationAndIncidentType(configuration, null); } @SuppressWarnings("unchecked") public List<Incident> findIncidentByConfigurationAndIncidentType(String configuration, String incidentType) { Map<String,Object> params = new HashMap<String, Object>();
params.put("configuration", configuration); params.put("incidentType", incidentType); return getDbEntityManager().selectList("selectIncidentsByConfiguration", params); } @SuppressWarnings("unchecked") public List<Incident> findIncidentByQueryCriteria(IncidentQueryImpl incidentQuery, Page page) { configureQuery(incidentQuery); return getDbEntityManager().selectList("selectIncidentByQueryCriteria", incidentQuery, page); } protected void configureQuery(IncidentQueryImpl query) { getAuthorizationManager().configureIncidentQuery(query); getTenantManager().configureQuery(query); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IncidentManager.java
1
请完成以下Java代码
public void setAuthenticationValidator(Consumer<OidcLogoutAuthenticationContext> authenticationValidator) { Assert.notNull(authenticationValidator, "authenticationValidator cannot be null"); this.authenticationValidator = authenticationValidator; } private SessionInformation findSessionInformation(Authentication principal, String sessionId) { List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(principal.getPrincipal(), true); SessionInformation sessionInformation = null; if (!CollectionUtils.isEmpty(sessions)) { for (SessionInformation session : sessions) { if (session.getSessionId().equals(sessionId)) { sessionInformation = session; break; } } }
return sessionInformation; } private static void throwError(String errorCode, String parameterName) { OAuth2Error error = new OAuth2Error(errorCode, "OpenID Connect 1.0 Logout Request Parameter: " + parameterName, "https://openid.net/specs/openid-connect-rpinitiated-1_0.html#ValidationAndErrorHandling"); throw new OAuth2AuthenticationException(error); } private static String createHash(String value) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII)); return Base64.getUrlEncoder().withoutPadding().encodeToString(digest); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\authentication\OidcLogoutAuthenticationProvider.java
1