instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class SetPickFromHUWFActivityHandler implements WFActivityHandler, SetScannedBarcodeSupport { public static final WFActivityType HANDLED_ACTIVITY_TYPE = WFActivityType.ofString("picking.setPickFromHU"); @NonNull private final PickingJobRestService pickingJobRestService; @NonNull private final HUQRCodesService huQRCodesService; @Override public WFActivityType getHandledActivityType() { return HANDLED_ACTIVITY_TYPE; } @Override public UIComponent getUIComponent( final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { final JsonQRCode pickFromHU = getPickingJob(wfProcess) .getPickFromHU() .map(SetPickFromHUWFActivityHandler::toJsonQRCode) .orElse(null); return SetScannedBarcodeSupportHelper.uiComponent() .currentValue(pickFromHU) .alwaysAvailableToUser(wfActivity.getAlwaysAvailableToUser()) .build(); } public static JsonQRCode toJsonQRCode(final HUInfo pickFromHU) { final HUQRCode qrCode = pickFromHU.getQrCode(); return JsonQRCode.builder() .qrCode(qrCode.toGlobalQRCodeString()) .caption(qrCode.toDisplayableQRCode()) .build(); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { final PickingJob pickingJob = getPickingJob(wfProcess); return computeActivityState(pickingJob); } public static WFActivityStatus computeActivityState(final PickingJob pickingJob) { return pickingJob.getPickFromHU().isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override
public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request) { final HUQRCode qrCode = parseHUQRCode(request.getScannedBarcode()); final HuId huId = huQRCodesService.getHuIdByQRCode(qrCode); final HUInfo pickFromHU = HUInfo.builder() .id(huId) .qrCode(qrCode) .build(); return PickingMobileApplication.mapPickingJob( request.getWfProcess(), pickingJob -> pickingJobRestService.setPickFromHU(pickingJob, pickFromHU) ); } private HUQRCode parseHUQRCode(final String scannedCode) { final IHUQRCode huQRCode = huQRCodesService.parse(scannedCode); if (huQRCode instanceof HUQRCode) { return (HUQRCode)huQRCode; } else { throw new AdempiereException("Invalid HU QR code: " + scannedCode); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickFromHUWFActivityHandler.java
2
请完成以下Java代码
public void setA_Period (int A_Period) { set_Value (COLUMNNAME_A_Period, Integer.valueOf(A_Period)); } /** Get Period/Yearly. @return Period/Yearly */ public int getA_Period () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Period); if (ii == null) return 0; return ii.intValue(); } /** A_Table_Rate_Type AD_Reference_ID=53255 */ public static final int A_TABLE_RATE_TYPE_AD_Reference_ID=53255; /** Amount = AM */ public static final String A_TABLE_RATE_TYPE_Amount = "AM"; /** Rate = RT */ public static final String A_TABLE_RATE_TYPE_Rate = "RT"; /** Set Type. @param A_Table_Rate_Type Type */ public void setA_Table_Rate_Type (String A_Table_Rate_Type) { set_ValueNoCheck (COLUMNNAME_A_Table_Rate_Type, A_Table_Rate_Type); } /** Get Type. @return Type */ public String getA_Table_Rate_Type () { return (String)get_Value(COLUMNNAME_A_Table_Rate_Type); } /** Set Processed. @param Processed The document has been processed
*/ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Table_Detail.java
1
请完成以下Java代码
private void checkBP(final I_C_BPartner bp) throws SQLException { final IBPartnerStatsDAO bpartnerStatsDAO = Services.get(IBPartnerStatsDAO.class); final BPartnerStats stats = bpartnerStatsDAO.getCreateBPartnerStats(bp); addLog(0, null, null, bp.getName() + ":"); // See also VMerge.postMerge checkPayments(bp); checkInvoices(bp); // // task FRESH-152.Update bpartner stats Services.get(IBPartnerStatisticsUpdater.class) .updateBPartnerStatistics(BPartnerStatisticsUpdateRequest.builder() .bpartnerId(bp.getC_BPartner_ID()) .build()); // // if (bp.getSO_CreditUsed().signum() != 0) addLog(0, null, stats.getSOCreditUsed(), Msg.getElement(getCtx(), "SO_CreditUsed")); addLog(0, null, stats.getOpenItems(), Msg.getElement(getCtx(), "OpenItems")); addLog(0, null, stats.getActualLifeTimeValue(), Msg.getElement(getCtx(), "ActualLifeTimeValue")); // commitEx(); } // checkBP /** * Check Payments * * @param bp business partner */ private void checkPayments(final I_C_BPartner bp) { // See also VMerge.postMerge int changed = 0; final MPayment[] payments = MPayment.getOfBPartner(getCtx(), bp.getC_BPartner_ID(), get_TrxName()); for (final MPayment payment : payments) { if (payment.testAllocation()) { payment.save(); changed++; } } if (changed != 0) { addLog(0, null, new BigDecimal(payments.length), Msg.getElement(getCtx(), "C_Payment_ID") + " - #" + changed);
} } // checkPayments /** * Check Invoices * * @param bp business partner */ private void checkInvoices(final I_C_BPartner bp) { // See also VMerge.postMerge int changed = 0; final MInvoice[] invoices = MInvoice.getOfBPartner(getCtx(), bp.getC_BPartner_ID(), get_TrxName()); for (final MInvoice invoice : invoices) { if (invoice.testAllocation()) { invoice.save(); changed++; } } if (changed != 0) { addLog(0, null, new BigDecimal(invoices.length), Msg.getElement(getCtx(), "C_Invoice_ID") + " - #" + changed); } } // checkInvoices } // BPartnerValidate
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\BPartnerValidate.java
1
请完成以下Java代码
private I_M_HU_LUTU_Configuration getDefaultLUTUConfiguration() { if (_defaultLUTUConfiguration == null) { final I_M_ReceiptSchedule receiptSchedule = getM_ReceiptSchedule(); final I_M_HU_LUTU_Configuration defaultLUTUConfiguration = getCurrentLUTUConfiguration(receiptSchedule); huReceiptScheduleBL.adjustLUTUConfiguration(defaultLUTUConfiguration, receiptSchedule); _defaultLUTUConfiguration = defaultLUTUConfiguration; } return _defaultLUTUConfiguration; } private static final String PARAM_IsSaveLUTUConfiguration = "IsSaveLUTUConfiguration"; @Param(parameterName = PARAM_IsSaveLUTUConfiguration) private boolean p_IsSaveLUTUConfiguration; // // Parameters private static final String PARAM_M_HU_PI_Item_Product_ID = "M_HU_PI_Item_Product_ID"; @Param(parameterName = PARAM_M_HU_PI_Item_Product_ID) private int p_M_HU_PI_Item_Product_ID; // private static final String PARAM_M_LU_HU_PI_ID = "M_LU_HU_PI_ID"; @Param(parameterName = PARAM_M_LU_HU_PI_ID) private int p_M_LU_HU_PI_ID; // private static final String PARAM_QtyCUsPerTU = "QtyCUsPerTU"; @Param(parameterName = PARAM_QtyCUsPerTU) private BigDecimal p_QtyCUsPerTU; // private static final String PARAM_QtyTU = "QtyTU"; @Param(parameterName = PARAM_QtyTU) private BigDecimal p_QtyTU; // private static final String PARAM_QtyLU = "QtyLU"; @Param(parameterName = PARAM_QtyLU) private BigDecimal p_QtyLU; @Override protected boolean isUpdateReceiptScheduleDefaultConfiguration() { return p_IsSaveLUTUConfiguration; } @Override protected I_M_HU_LUTU_Configuration createM_HU_LUTU_Configuration(final I_M_HU_LUTU_Configuration template) { // Validate parameters final int M_LU_HU_PI_ID = p_M_LU_HU_PI_ID; final int M_HU_PI_Item_Product_ID = p_M_HU_PI_Item_Product_ID; final BigDecimal qtyCUsPerTU = p_QtyCUsPerTU; final BigDecimal qtyTU = p_QtyTU; final BigDecimal qtyLU = p_QtyLU; if (M_HU_PI_Item_Product_ID <= 0)
{ throw new FillMandatoryException(PARAM_M_HU_PI_Item_Product_ID); } if (qtyCUsPerTU == null || qtyCUsPerTU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyCUsPerTU); } if (qtyTU == null || qtyTU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyTU); } if (M_LU_HU_PI_ID > 0 && qtyLU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyLU); } final ILUTUConfigurationFactory.CreateLUTUConfigRequest lutuConfigRequest = ILUTUConfigurationFactory.CreateLUTUConfigRequest.builder() .baseLUTUConfiguration(template) .qtyLU(qtyLU) .qtyTU(qtyTU) .qtyCUsPerTU(qtyCUsPerTU) .tuHUPIItemProductID(M_HU_PI_Item_Product_ID) .luHUPIID(M_LU_HU_PI_ID) .build(); return lutuConfigurationFactory.createNewLUTUConfigWithParams(lutuConfigRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_ReceiveHUs_UsingConfig.java
1
请在Spring Boot框架中完成以下Java代码
public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } public String getRegisterTimeStart() { return registerTimeStart; } public void setRegisterTimeStart(String registerTimeStart) { this.registerTimeStart = registerTimeStart; } public String getRegisterTimeEnd() { return registerTimeEnd; } public void setRegisterTimeEnd(String registerTimeEnd) { this.registerTimeEnd = registerTimeEnd; } public Integer getOrderByRegisterTime() { return orderByRegisterTime; } public void setOrderByRegisterTime(Integer orderByRegisterTime) { this.orderByRegisterTime = orderByRegisterTime; } public String getPassword() {
return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "UserQueryReq{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", phone='" + phone + '\'' + ", mail='" + mail + '\'' + ", registerTimeStart='" + registerTimeStart + '\'' + ", registerTimeEnd='" + registerTimeEnd + '\'' + ", userType=" + userType + ", userState=" + userState + ", roleId='" + roleId + '\'' + ", orderByRegisterTime=" + orderByRegisterTime + ", page=" + page + ", numPerPage=" + numPerPage + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\UserQueryReq.java
2
请完成以下Java代码
public class RandomKeyTrackingMap<K, V> { private final Map<K, V> delegate = new HashMap<>(); private final List<K> keys = new ArrayList<>(); public void put(K key, V value) { V previousValue = delegate.put(key, value); if (previousValue == null) { keys.add(key); } } public V remove(K key) { V removedValue = delegate.remove(key); if (removedValue != null) { int index = keys.indexOf(key); if (index >= 0) { keys.remove(index);
} } return removedValue; } public V getRandomValue() { if (keys.isEmpty()) { return null; } int randomIndex = ThreadLocalRandom.current().nextInt(keys.size()); K randomKey = keys.get(randomIndex); return delegate.get(randomKey); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-9\src\main\java\com\baeldung\map\randommapkey\RandomKeyTrackingMap.java
1
请完成以下Java代码
public List<HttpCookie> get(URI uri) { // TODO Auto-generated method stub return null; } @Override public List<HttpCookie> getCookies() { // TODO Auto-generated method stub return null; } @Override public List<URI> getURIs() { // TODO Auto-generated method stub return null;
} @Override public boolean remove(URI uri, HttpCookie cookie) { // TODO Auto-generated method stub return false; } @Override public boolean removeAll() { // TODO Auto-generated method stub return false; } }
repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\cookies\PersistentCookieStore.java
1
请完成以下Java代码
public static WFDurationUnit ofCode(@NonNull final String code) { return typesByCode.ofCode(code); } @SuppressWarnings("unused") public static WFDurationUnit ofTemporalUnit(@NonNull final TemporalUnit temporalUnit) { final WFDurationUnit type = typesByTemporalUnit.get(temporalUnit); if (type == null) { throw new AdempiereException("No " + WFDurationUnit.class.getSimpleName() + " found for temporal unit: " + temporalUnit); } return type; } public BigDecimal toBigDecimal(@NonNull final Duration duration)
{ return DurationUtils.toBigDecimal(duration, getTemporalUnit()); } public int toInt(@NonNull final Duration duration) { return DurationUtils.toInt(duration, getTemporalUnit()); } public Duration toDuration(@NonNull final BigDecimal durationBD) { return DurationUtils.toWorkDurationRoundUp(durationBD, getTemporalUnit()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFDurationUnit.java
1
请完成以下Java代码
public class Specification implements Serializable { private int ram; private int internalMemory; private String processor; public Specification() { } public int getRam() { return ram; } public void setRam(int ram) { this.ram = ram; }
public int getInternalMemory() { return internalMemory; } public void setInternalMemory(int internalMemory) { this.internalMemory = internalMemory; } public String getProcessor() { return processor; } public void setProcessor(String processor) { this.processor = processor; } }
repos\tutorials-master\persistence-modules\hibernate6\src\main\java\com\baeldung\persistjson\Specification.java
1
请完成以下Java代码
public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public String getExt() { return ext; } public void setExt(String ext) { this.ext = ext; }
public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-7 课:使用 Spring Boot 上传文件到 FastDFS\spring-boot-fastDFS\src\main\java\com\neo\fastdfs\FastDFSFile.java
1
请完成以下Java代码
public @Nullable String getServerNamespace() { return this.serverNamespace; } @Override public void setServerNamespace(@Nullable String serverNamespace) { this.serverNamespace = serverNamespace; } @Override public void setServletConfig(@Nullable ServletConfig servletConfig) { this.servletConfig = servletConfig; } @Override public @Nullable ServletConfig getServletConfig() { return this.servletConfig; } /** * Returns the {@link WebServer} that was created by the context or {@code null} if * the server has not yet been created. * @return the embedded web server */ @Override public @Nullable WebServer getWebServer() { return this.webServer; } /** * Utility class to store and restore any user defined scopes. This allows scopes to * be registered in an ApplicationContextInitializer in the same way as they would in * a classic non-embedded web application context. */ public static class ExistingWebApplicationScopes { private static final Set<String> SCOPES; static { Set<String> scopes = new LinkedHashSet<>(); scopes.add(WebApplicationContext.SCOPE_REQUEST); scopes.add(WebApplicationContext.SCOPE_SESSION); SCOPES = Collections.unmodifiableSet(scopes);
} private final ConfigurableListableBeanFactory beanFactory; private final Map<String, Scope> scopes = new HashMap<>(); public ExistingWebApplicationScopes(ConfigurableListableBeanFactory beanFactory) { this.beanFactory = beanFactory; for (String scopeName : SCOPES) { Scope scope = beanFactory.getRegisteredScope(scopeName); if (scope != null) { this.scopes.put(scopeName, scope); } } } public void restore() { this.scopes.forEach((key, value) -> { if (logger.isInfoEnabled()) { logger.info("Restoring user defined scope " + key); } this.beanFactory.registerScope(key, value); }); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\ServletWebServerApplicationContext.java
1
请完成以下Java代码
public InventoryLineAggregationKey createAggregationKey(@NonNull final InventoryLine inventoryLine) { final Quantity qty = CoalesceUtil.coalesce(inventoryLine.getQtyCount(), inventoryLine.getQtyBook()); final UomId uomId = qty == null ? null : qty.getUomId(); return MultipleHUInventoryLineInventoryLineAggregationKey.builder() .productId(inventoryLine.getProductId()) .uomId(uomId) .storageAttributesKey(AttributesKeys.createAttributesKeyFromASIStorageAttributes(inventoryLine.getAsiId()).orElse(AttributesKey.NONE)) .locatorId(inventoryLine.getLocatorId()) .build(); } @Override public AggregationType getAggregationType()
{ return AggregationType.MULTIPLE_HUS; } @Value @Builder private static class MultipleHUInventoryLineInventoryLineAggregationKey implements InventoryLineAggregationKey { @NonNull ProductId productId; // needed for the case that stocking UOM has changed, and there are still HUs with an old UOM @Nullable UomId uomId; @NonNull AttributesKey storageAttributesKey; @NonNull LocatorId locatorId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\aggregator\MultipleHUInventoryLineAggregator.java
1
请完成以下Java代码
public T call() throws Exception { return doCall(callable); } }, targetProcessApplication); } else { return doCall(callable); } } protected <T> T doCall(Callable<T> callable) { try { return callable.call(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ProcessEngineException(e);
} } public void submitFormVariables(final VariableMap properties, final VariableScope variableScope) { performContextSwitch(new Callable<Void> () { public Void call() throws Exception { Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(new SubmitFormVariablesInvocation(formHandler, properties, variableScope)); return null; } }); } public abstract FormHandler getFormHandler(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\DelegateFormHandler.java
1
请完成以下Java代码
private TbMsg getResponseMsg(TbMsg originalMsg, InvokeResult invokeResult) { TbMsgMetaData metaData = originalMsg.getMetaData().copy(); metaData.putValue("requestId", invokeResult.getSdkResponseMetadata().getRequestId()); String data = getPayload(invokeResult); return originalMsg.transform() .metaData(metaData) .data(data) .build(); } private TbMsg processException(TbMsg origMsg, InvokeResult invokeResult, Throwable t) { TbMsgMetaData metaData = origMsg.getMetaData().copy(); metaData.putValue("error", t.getClass() + ": " + t.getMessage()); metaData.putValue("requestId", invokeResult.getSdkResponseMetadata().getRequestId()); return origMsg.transform()
.metaData(metaData) .build(); } @Override public void destroy() { if (client != null) { try { client.shutdown(); } catch (Exception e) { log.error("Failed to shutdown Lambda client during destroy", e); } } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\aws\lambda\TbAwsLambdaNode.java
1
请完成以下Java代码
public Builder verificationUriComplete(String verificationUriComplete) { this.verificationUriComplete = verificationUriComplete; return this; } /** * Sets the lifetime (in seconds) of the device code and user code. * @param expiresIn the lifetime (in seconds) of the device code and user code * @return the {@link Builder} */ public Builder expiresIn(long expiresIn) { this.expiresIn = expiresIn; return this; } /** * Sets the minimum amount of time (in seconds) that the client should wait * between polling requests to the token endpoint. * @param interval the minimum amount of time between polling requests * @return the {@link Builder} */ public Builder interval(long interval) { this.interval = interval; return this; } /** * Sets the additional parameters returned in the response. * @param additionalParameters the additional parameters returned in the response * @return the {@link Builder} */ public Builder additionalParameters(Map<String, Object> additionalParameters) { this.additionalParameters = additionalParameters; return this; } /** * Builds a new {@link OAuth2DeviceAuthorizationResponse}.
* @return a {@link OAuth2DeviceAuthorizationResponse} */ public OAuth2DeviceAuthorizationResponse build() { Assert.hasText(this.verificationUri, "verificationUri cannot be empty"); Assert.isTrue(this.expiresIn > 0, "expiresIn must be greater than zero"); Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plusSeconds(this.expiresIn); OAuth2DeviceCode deviceCode = new OAuth2DeviceCode(this.deviceCode, issuedAt, expiresAt); OAuth2UserCode userCode = new OAuth2UserCode(this.userCode, issuedAt, expiresAt); OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse = new OAuth2DeviceAuthorizationResponse(); deviceAuthorizationResponse.deviceCode = deviceCode; deviceAuthorizationResponse.userCode = userCode; deviceAuthorizationResponse.verificationUri = this.verificationUri; deviceAuthorizationResponse.verificationUriComplete = this.verificationUriComplete; deviceAuthorizationResponse.interval = this.interval; deviceAuthorizationResponse.additionalParameters = Collections .unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap() : this.additionalParameters); return deviceAuthorizationResponse; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2DeviceAuthorizationResponse.java
1
请在Spring Boot框架中完成以下Java代码
public String getFirstName() { return firstName; } /** * @param firstName the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return the lastName */ public String getLastName() { return lastName; } /** * @param lastName the lastName to set */ public void setLastName(String lastName) { this.lastName = lastName; } /** * @return the pageDescription */ public String getPageDescription() { return pageDescription; } /** * @param pageDescription the pageDescription to set */
public void setPageDescription(String pageDescription) { this.pageDescription = pageDescription; } /** * @return the pageCounter */ public int getPageCounter() { return pageCounter; } /** * @param pageCounter the pageCounter to set */ public void setPageCounter(int pageCounter) { this.pageCounter = pageCounter; } }
repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\ELSampleBean.java
2
请在Spring Boot框架中完成以下Java代码
public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } private static class ProxyDataSourceInterceptor implements MethodInterceptor { private final DataSource dataSource; public ProxyDataSourceInterceptor(final DataSource dataSource) { super(); this.dataSource = ProxyDataSourceBuilder.create(dataSource) .name("DATA_SOURCE_PROXY") .logQueryBySlf4j(SLF4JLogLevel.INFO) .multiline() .build(); }
@Override public Object invoke(final MethodInvocation invocation) throws Throwable { final Method proxyMethod = ReflectionUtils. findMethod(this.dataSource.getClass(), invocation.getMethod().getName()); if (proxyMethod != null) { return proxyMethod.invoke(this.dataSource, invocation.getArguments()); } return invocation.proceed(); } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchDeleteCascadeDelete\src\main\java\com\bookstore\config\DatasourceProxyBeanPostProcessor.java
2
请完成以下Java代码
public void setScaleStep(final int scaleStep) { if (scaleStep < 0 || zoomFactors.length <= scaleStep) { return; } this.scaleStep = scaleStep; zoomSelect.setSelectedIndex(scaleStep); updateZoomRotate(); } protected void updateZoomRotate() { final Cursor oldCursor = getCursor(); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); decoder.setPageParameters(zoomFactors[scaleStep], currentPage, rotation); decoder.invalidate(); decoder.repaint(); zoomInAction.setEnabled(scaleStep < zoomFactors.length - 1); zoomOutAction.setEnabled(scaleStep > 0); } finally { setCursor(oldCursor); } } public void setScale(final int percent) { int step; for (step = 0; step < zoomFactors.length - 1; step++) { if (zoomFactors[step] * 100 >= percent) { break; } } setScaleStep(step); } public boolean loadPDF(final byte[] data) { return loadPDF(new ByteArrayInputStream(data)); } public boolean loadPDF(final InputStream is) { if (tmpFile != null) { tmpFile.delete(); } try { tmpFile = File.createTempFile("adempiere", ".pdf"); tmpFile.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); return false; } try {
final OutputStream os = new FileOutputStream(tmpFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } catch (IOException e) { e.printStackTrace(); } finally { os.close(); } } catch (IOException e) { e.printStackTrace(); } return loadPDF(tmpFile.getAbsolutePath()); } @Override protected void finalize() throws Throwable { if (tmpFile != null) { tmpFile.delete(); } decoder.closePdfFile(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\pdf\viewer\PDFViewerBean.java
1
请在Spring Boot框架中完成以下Java代码
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { for (String url : limits.keySet()) { if (pathMatcher.match(url, request.getRequestURI())) { if (checkMaxPayloadSizeExceeded(request, response, limits.get(url))) { return; } break; } } chain.doFilter(request, response); } private boolean checkMaxPayloadSizeExceeded(HttpServletRequest request, HttpServletResponse response, long maxPayloadSize) throws IOException { if (request.getContentLength() > maxPayloadSize) { log.info("[{}] [{}] Payload size {} exceeds the limit of {} bytes", request.getRemoteAddr(), request.getRequestURL(), request.getContentLength(), maxPayloadSize); handleMaxPayloadSizeExceededException(response, new MaxPayloadSizeExceededException(maxPayloadSize)); return true; } return false; }
@Override protected boolean shouldNotFilterAsyncDispatch() { return false; } @Override protected boolean shouldNotFilterErrorDispatch() { return false; } private void handleMaxPayloadSizeExceededException(HttpServletResponse response, MaxPayloadSizeExceededException exception) throws IOException { response.setStatus(HttpStatus.PAYLOAD_TOO_LARGE.value()); JacksonUtil.writeValue(response.getWriter(), exception.getMessage()); } }
repos\thingsboard-master\common\transport\http\src\main\java\org\thingsboard\server\transport\http\config\PayloadSizeFilter.java
2
请完成以下Java代码
public class Product { @PrimaryKey String id; String name; String description; double price; public Product() { } public Product(String id, String name, String description, double price) { this.id = id; this.name = name; this.description = description; this.price = price; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name;
} public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\xml\Product.java
1
请完成以下Java代码
/* package */ IAutoCloseable temporarySetLoggable(@NonNull final ILoggable loggable) { final ILoggable loggableOld = loggableRef.get(); loggableRef.set(loggable); return new IAutoCloseable() { boolean closed = false; @Override public void close() { if (closed) { return; } closed = true; loggable.flush(); loggableRef.set(loggableOld); } }; } /** * @return current thread's {@link ILoggable} instance or the {@link NullLoggable}. Never returns <code>null</code> */ @NonNull /* package */ ILoggable getLoggable() { return Objects.requireNonNull(getLoggableOr(Loggables.nop())); }
/** * @return current thread's {@link ILoggable} instance or <code>defaultLoggable</code> if there was no thread level {@link ILoggable} */ @Nullable /* package */ ILoggable getLoggableOr(@Nullable final ILoggable defaultLoggable) { final ILoggable loggable = loggableRef.get(); return loggable != null ? loggable : defaultLoggable; } /** * Holds the {@link ILoggable} instance of current thread */ public static final ThreadLocalLoggableHolder instance = new ThreadLocalLoggableHolder(); private final ThreadLocal<ILoggable> loggableRef = new ThreadLocal<>(); private ThreadLocalLoggableHolder() { super(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\ThreadLocalLoggableHolder.java
1
请完成以下Java代码
public class M_Securpharm_Config_Test extends JavaProcess implements IProcessPrecondition { private final SecurPharmConfigRespository configRepo = Adempiere.getBean(SecurPharmConfigRespository.class); private final SecurPharmClientFactory clientFactory = Adempiere.getBean(SecurPharmClientFactory.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); }
return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final SecurPharmConfigId configId = SecurPharmConfigId.ofRepoId(getRecord_ID()); final SecurPharmConfig config = configRepo.getById(configId); final SecurPharmClient client = clientFactory.createClient(config); client.authenticate(); return "@AuthenticationOK@"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\process\M_Securpharm_Config_Test.java
1
请完成以下Java代码
public FinancialInstrumentQuantityChoice getQty() { return qty; } /** * Sets the value of the qty property. * * @param value * allowed object is * {@link FinancialInstrumentQuantityChoice } * */ public void setQty(FinancialInstrumentQuantityChoice value) { this.qty = value; } /** * Gets the value of the prtry property. * * @return * possible object is * {@link ProprietaryQuantity1 } * */ public ProprietaryQuantity1 getPrtry() {
return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link ProprietaryQuantity1 } * */ public void setPrtry(ProprietaryQuantity1 value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionQuantities1Choice.java
1
请在Spring Boot框架中完成以下Java代码
public void save(Employee employee) { keyValueTemplate.insert(employee); } @Override public Optional<Employee> get(Integer id) { return keyValueTemplate.findById(id, Employee.class); } @Override public Iterable<Employee> fetchAll() { return keyValueTemplate.findAll(Employee.class); } @Override public void update(Employee employee) { keyValueTemplate.update(employee);
} @Override public void delete(Integer id) { keyValueTemplate.delete(id, Employee.class); } @Override public Iterable<Employee> getSortedListOfEmployeesBySalary() { KeyValueQuery query = new KeyValueQuery(); query.setSort(Sort.by(Sort.Direction.DESC, "salary")); return keyValueTemplate.find(query, Employee.class); } }
repos\tutorials-master\persistence-modules\spring-data-keyvalue\src\main\java\com\baeldung\spring\data\keyvalue\services\impl\EmployeeServicesWithKeyValueTemplate.java
2
请完成以下Java代码
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { byte[] byteCode = classfileBuffer; String finalTargetClassName = this.targetClassName.replaceAll("\\.", "/"); //replace . with / if (!className.equals(finalTargetClassName)) { return byteCode; } if (className.equals(finalTargetClassName) && loader.equals(targetClassLoader)) { LOGGER.info("[Agent] Transforming class MyAtm"); try { ClassPool cp = ClassPool.getDefault(); CtClass cc = cp.get(targetClassName); CtMethod m = cc.getDeclaredMethod(WITHDRAW_MONEY_METHOD); m.addLocalVariable("startTime", CtClass.longType); m.insertBefore("startTime = System.currentTimeMillis();"); StringBuilder endBlock = new StringBuilder(); m.addLocalVariable("endTime", CtClass.longType); m.addLocalVariable("opTime", CtClass.longType); endBlock.append("endTime = System.currentTimeMillis();");
endBlock.append("opTime = (endTime-startTime)/1000;"); endBlock.append("LOGGER.info(\"[Application] Withdrawal operation completed in:\" + opTime + \" seconds!\");"); m.insertAfter(endBlock.toString()); byteCode = cc.toBytecode(); cc.detach(); } catch (NotFoundException | CannotCompileException | IOException e) { LOGGER.error("Exception", e); } } return byteCode; } }
repos\tutorials-master\core-java-modules\core-java-jvm\src\main\java\com\baeldung\instrumentation\agent\AtmTransformer.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ExtensionElements.class, CMMN_ELEMENT_EXTENSION_ELEMENTS) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<ExtensionElements>() { public ExtensionElements newInstance(ModelTypeInstanceContext instanceContext) { return new ExtensionElementsImpl(instanceContext); } }); typeBuilder.build(); } public ExtensionElementsImpl(ModelTypeInstanceContext context) { super(context); } public Collection<ModelElementInstance> getElements() { return ModelUtil.getModelElementCollection(getDomElement().getChildElements(), modelInstance); } public Query<ModelElementInstance> getElementsQuery() {
return new QueryImpl<ModelElementInstance>(getElements()); } public ModelElementInstance addExtensionElement(String namespaceUri, String localName) { ModelElementType extensionElementType = modelInstance.registerGenericType(namespaceUri, localName); ModelElementInstance extensionElement = extensionElementType.newInstance(modelInstance); addChildElement(extensionElement); return extensionElement; } public <T extends ModelElementInstance> T addExtensionElement(Class<T> extensionElementClass) { ModelElementInstance extensionElement = modelInstance.newInstance(extensionElementClass); addChildElement(extensionElement); return extensionElementClass.cast(extensionElement); } @Override public void addChildElement(ModelElementInstance extensionElement) { getDomElement().appendChild(extensionElement.getDomElement()); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ExtensionElementsImpl.java
1
请完成以下Java代码
public String toString() { return ObjectUtils.toString(this); } public BigDecimal getInvoicedAmt() { return invoicedAmt; } public BigDecimal getPaymentExistingAmt() { return paymentExistingAmt; } public BigDecimal getPaymentCandidatesAmt() { return paymentCandidatesAmt; } public BigDecimal getDiffInvoiceMinusPay() { return diffInvoiceMinusPay; } public boolean hasDifferences() { return diffInvoiceMinusPay.signum() != 0; } public boolean isMoreInvoicedThanPaid() { final int invoicedAmtSign = invoicedAmt.signum(); final int paymentAmtSign = paymentTotalAmt.signum(); if (invoicedAmtSign >= 0) { // Positive invoiced, positive paid if (paymentAmtSign >= 0) { return invoicedAmt.compareTo(paymentTotalAmt) > 0; } // Positive invoiced, negative paid else { return true; // more invoiced than paid } } else { // Negative invoiced, positive paid if (paymentAmtSign >= 0) {
return false; // more paid than invoiced } // Negative invoiced, negative paid else { return invoicedAmt.abs().compareTo(paymentTotalAmt.abs()) > 0; } } } // // // ------------------------------------------------------------------------------------------------------------------------------ // // public static final class Builder { private BigDecimal invoicedAmt = BigDecimal.ZERO; private BigDecimal paymentExistingAmt = BigDecimal.ZERO; private BigDecimal paymentCandidatesAmt = BigDecimal.ZERO; private Builder() { super(); } public PaymentAllocationTotals build() { return new PaymentAllocationTotals(this); } public Builder setInvoicedAmt(final BigDecimal invoicedAmt) { this.invoicedAmt = invoicedAmt; return this; } public Builder setPaymentExistingAmt(final BigDecimal paymentExistingAmt) { this.paymentExistingAmt = paymentExistingAmt; return this; } public Builder setPaymentCandidatesAmt(final BigDecimal paymentCandidatesAmt) { this.paymentCandidatesAmt = paymentCandidatesAmt; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentAllocationTotals.java
1
请完成以下Java代码
public abstract class AbstractAddIdentityLinkCmd extends AbstractSetTaskPropertyCmd<Integer> { protected final String userId; protected final String groupId; protected final String type; public AbstractAddIdentityLinkCmd(String taskId, String userId, String groupId, String type) { super(taskId, null, true); validateParameters(type, userId, groupId); this.userId = userId; this.groupId = groupId; this.type = type; } @Override protected void executeSetOperation(TaskEntity task, Integer value) { if (isAssignee(type)) { task.setAssignee(userId); return; } if (isOwner(type)) { task.setOwner(userId); return; } task.addIdentityLink(userId, groupId, type); } /** * Method to be overridden by concrete identity commands that wish to log an operation. * * @param context the command context * @param task the task related entity */ protected abstract void logOperation(CommandContext context, TaskEntity task); @Override protected String getUserOperationLogName() {
return null; // Ignored for identity commands } protected void validateParameters(String type, String userId, String groupId) { if (isAssignee(type) && groupId != null) { throw new BadUserRequestException("Incompatible usage: cannot use ASSIGNEE together with a groupId"); } if (!isAssignee(type) && hasNullIdentity(userId, groupId)) { throw new NullValueException("userId and groupId cannot both be null"); } } protected boolean hasNullIdentity(String userId, String groupId) { return (userId == null) && (groupId == null); } protected boolean isAssignee(String type) { return IdentityLinkType.ASSIGNEE.equals(type); } protected boolean isOwner(String type) { return IdentityLinkType.OWNER.equals(type); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractAddIdentityLinkCmd.java
1
请完成以下Java代码
public static HUQRCodeUniqueId ofJson(@NonNull final String json) { final int idx = json.indexOf('-'); if (idx <= 0) { throw new AdempiereException("Invalid ID: `" + json + "`"); } final String idBase = json.substring(0, idx); final String displayableSuffix = json.substring(idx + 1); return new HUQRCodeUniqueId(idBase, displayableSuffix); } @Override @Deprecated public String toString()
{ return getAsString(); } @JsonValue public String getAsString() { return idBase + "-" + displayableSuffix; } public static boolean equals(@Nullable final HUQRCodeUniqueId id1, @Nullable final HUQRCodeUniqueId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCodeUniqueId.java
1
请完成以下Java代码
public ResponseEntity<Object> updateQuartzJobStatus(@PathVariable Long id){ quartzJobService.updateIsPause(quartzJobService.findById(id)); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("执行定时任务") @ApiOperation("执行定时任务") @PutMapping(value = "/exec/{id}") @PreAuthorize("@el.check('timing:edit')") public ResponseEntity<Object> executionQuartzJob(@PathVariable Long id){ quartzJobService.execution(quartzJobService.findById(id)); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("删除定时任务") @ApiOperation("删除定时任务")
@DeleteMapping @PreAuthorize("@el.check('timing:del')") public ResponseEntity<Object> deleteQuartzJob(@RequestBody Set<Long> ids){ quartzJobService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } private void checkBean(String beanName){ // 避免调用攻击者可以从SpringContextHolder获得控制jdbcTemplate类 // 并使用getDeclaredMethod调用jdbcTemplate的queryForMap函数,执行任意sql命令。 if(!SpringBeanHolder.getAllServiceBeanName().contains(beanName)){ throw new BadRequestException("非法的 Bean,请重新输入!"); } } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\quartz\rest\QuartzJobController.java
1
请在Spring Boot框架中完成以下Java代码
public void setContractNumber(String value) { this.contractNumber = value; } /** * Gets the value of the agreementNumber property. * * @return * possible object is * {@link String } * */ public String getAgreementNumber() { return agreementNumber; } /** * Sets the value of the agreementNumber property. * * @param value * allowed object is * {@link String } * */ public void setAgreementNumber(String value) { this.agreementNumber = value; } /** * Gets the value of the timeForPayment property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getTimeForPayment() { return timeForPayment; } /** * Sets the value of the timeForPayment property. * * @param value * allowed object is * {@link BigInteger } * */ public void setTimeForPayment(BigInteger value) { this.timeForPayment = value; } /** * Additional free text.Gets the value of the freeText 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 freeText property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFreeText().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FreeTextType } * * */ public List<FreeTextType> getFreeText() { if (freeText == null) { freeText = new ArrayList<FreeTextType>(); } return this.freeText; } /** * Reference to the consignment. * * @return * possible object is * {@link String } * */ public String getConsignmentReference() { return consignmentReference; } /** * Sets the value of the consignmentReference property. * * @param value * allowed object is * {@link String } * */ public void setConsignmentReference(String value) { this.consignmentReference = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ORDERSExtensionType.java
2
请完成以下Java代码
private PlainHUPackingAware createAndInitHuPackingAware( @NonNull final I_M_Forecast forecast, @NonNull final IForecastLineQuickInput quickInput) { final PlainHUPackingAware huPackingAware = new PlainHUPackingAware(); huPackingAware.setC_BPartner_ID(forecast.getC_BPartner_ID()); huPackingAware.setInDispute(false); final ProductAndAttributes productAndAttributes = ProductLookupDescriptor.toProductAndAttributes(quickInput.getM_Product_ID()); final I_M_Product product = load(productAndAttributes.getProductId(), I_M_Product.class); huPackingAware.setM_Product_ID(product.getM_Product_ID()); huPackingAware.setC_UOM_ID(product.getC_UOM_ID()); huPackingAware.setM_AttributeSetInstance_ID(createASI(productAndAttributes)); final int piItemProductId = quickInput.getM_HU_PI_Item_Product_ID(); huPackingAware.setM_HU_PI_Item_Product_ID(piItemProductId); return huPackingAware; } private PlainHUPackingAware validateNewHuPackingAware(@NonNull final PlainHUPackingAware huPackingAware) { if (huPackingAware.getQty() == null || huPackingAware.getQty().signum() <= 0) { throw new AdempiereException("Qty shall be greather than zero"); } if (huPackingAware.getQtyTU() == null || huPackingAware.getQtyTU().signum() <= 0) { throw new AdempiereException("QtyTU shall be greather than zero"); } return huPackingAware; } private static final int createASI(final ProductAndAttributes productAndAttributes)
{ final ImmutableAttributeSet attributes = productAndAttributes.getAttributes(); if (attributes.isEmpty()) { return -1; } final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class); final I_M_AttributeSetInstance asi = asiBL.createASIWithASFromProductAndInsertAttributeSet( productAndAttributes.getProductId(), attributes); return asi.getM_AttributeSetInstance_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\forecastline\ForecastLineQuickInputProcessor.java
1
请完成以下Java代码
public java.sql.Timestamp getDK_DesiredDeliveryTime_To () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DK_DesiredDeliveryTime_To); } /** Set EMail Empfänger. @param EMail_To EMail address to send requests to - e.g. edi@manufacturer.com */ @Override public void setEMail_To (java.lang.String EMail_To) { set_Value (COLUMNNAME_EMail_To, EMail_To); } /** Get EMail Empfänger. @return EMail address to send requests to - e.g. edi@manufacturer.com */ @Override public java.lang.String getEMail_To () { return (java.lang.String)get_Value(COLUMNNAME_EMail_To); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } /** Set Lieferweg. @param M_Shipper_ID Methode oder Art der Warenlieferung */ @Override public void setM_Shipper_ID (int M_Shipper_ID)
{ if (M_Shipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID)); } /** Get Lieferweg. @return Methode oder Art der Warenlieferung */ @Override public int getM_Shipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_Shipper_Config.java
1
请完成以下Java代码
public final class HotelFunctions { private static HotelService HOTEL_SERVICE; private HotelFunctions() { } public static FunctionExecutor createFunctionExecutor(HotelService hotelService) { HOTEL_SERVICE = Objects.requireNonNull(hotelService, "hotelService"); FunctionExecutor executor = new FunctionExecutor(); executor.enrollFunction(FunctionDef.builder() .name("search_hotels") .description("Search for available hotels given a city, check-in date, nights, and guests") .functionalClass(SearchHotels.class) .strict(Boolean.TRUE) .build()); executor.enrollFunction(FunctionDef.builder() .name("create_booking") .description("Create a booking given a hotel id, check-in date, nights, guests, and guest name") .functionalClass(CreateBooking.class) .strict(Boolean.TRUE) .build()); return executor; } public record SearchHotelsResult(List<HotelService.HotelOffer> offers) { } public static class SearchHotels implements Functional { @JsonPropertyDescription("City name, for example: Tokyo") @JsonProperty(required = true) public String city; @JsonPropertyDescription("Check-in date in ISO-8601 format, for example: 2026-01-10") @JsonProperty(required = true) public String checkIn; @JsonPropertyDescription("Number of nights to stay")
@JsonProperty(required = true) public int nights; @JsonPropertyDescription("Number of guests") @JsonProperty(required = true) public int guests; @Override public Object execute() { List<HotelService.HotelOffer> offers = HOTEL_SERVICE.searchOffers(city, checkIn, nights, guests); return new SearchHotelsResult(offers); } } public static class CreateBooking implements Functional { @JsonPropertyDescription("Hotel identifier returned by search_hotels") @JsonProperty(required = true) public String hotelId; @JsonPropertyDescription("Check-in date in ISO-8601 format, for example: 2026-01-10") @JsonProperty(required = true) public String checkIn; @JsonPropertyDescription("Number of nights to stay") @JsonProperty(required = true) public int nights; @JsonPropertyDescription("Number of guests") @JsonProperty(required = true) public int guests; @JsonPropertyDescription("Guest full name for the booking") @JsonProperty(required = true) public String guestName; @Override public Object execute() { return HOTEL_SERVICE.createBooking(hotelId, checkIn, nights, guests, guestName); } } }
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\simpleopenai\HotelFunctions.java
1
请完成以下Java代码
public HistoricIdentityLinkLogQuery operationType(String operationType) { ensureNotNull("operationType", operationType); this.operationType = operationType; return this; } @Override public HistoricIdentityLinkLogQuery assignerId(String assignerId) { ensureNotNull("assignerId", assignerId); this.assignerId = assignerId; return this; } @Override public HistoricIdentityLinkLogQuery orderByTime() { orderBy(HistoricIdentityLinkLogQueryProperty.TIME); return this; } @Override public HistoricIdentityLinkLogQuery orderByType() { orderBy(HistoricIdentityLinkLogQueryProperty.TYPE); return this; } @Override public HistoricIdentityLinkLogQuery orderByUserId() { orderBy(HistoricIdentityLinkLogQueryProperty.USER_ID); return this; } @Override public HistoricIdentityLinkLogQuery orderByGroupId() { orderBy(HistoricIdentityLinkLogQueryProperty.GROUP_ID); return this; } @Override public HistoricIdentityLinkLogQuery orderByTaskId() { orderBy(HistoricIdentityLinkLogQueryProperty.TASK_ID); return this; } @Override public HistoricIdentityLinkLogQuery orderByProcessDefinitionId() {
orderBy(HistoricIdentityLinkLogQueryProperty.PROC_DEFINITION_ID); return this; } @Override public HistoricIdentityLinkLogQuery orderByProcessDefinitionKey() { orderBy(HistoricIdentityLinkLogQueryProperty.PROC_DEFINITION_KEY); return this; } @Override public HistoricIdentityLinkLogQuery orderByOperationType() { orderBy(HistoricIdentityLinkLogQueryProperty.OPERATION_TYPE); return this; } @Override public HistoricIdentityLinkLogQuery orderByAssignerId() { orderBy(HistoricIdentityLinkLogQueryProperty.ASSIGNER_ID); return this; } @Override public HistoricIdentityLinkLogQuery orderByTenantId() { orderBy(HistoricIdentityLinkLogQueryProperty.TENANT_ID); return this; } @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricIdentityLinkManager() .findHistoricIdentityLinkLogCountByQueryCriteria(this); } @Override public List<HistoricIdentityLinkLog> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricIdentityLinkManager() .findHistoricIdentityLinkLogByQueryCriteria(this, page); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricIdentityLinkLogQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setTRANSPORTMEANS(String value) { this.transportmeans = value; } /** * Gets the value of the carrierid property. * * @return * possible object is * {@link String } * */ public String getCARRIERID() { return carrierid; } /** * Sets the value of the carrierid property. * * @param value * allowed object is * {@link String } * */ public void setCARRIERID(String value) { this.carrierid = value; } /** * Gets the value of the carrierdesc property. * * @return * possible object is * {@link String } * */ public String getCARRIERDESC() { return carrierdesc; } /** * Sets the value of the carrierdesc property. * * @param value * allowed object is * {@link String } * */ public void setCARRIERDESC(String value) { this.carrierdesc = value; } /** * Gets the value of the locationqual property. * * @return * possible object is * {@link String } * */ public String getLOCATIONQUAL() { return locationqual; } /** * Sets the value of the locationqual property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONQUAL(String value) { this.locationqual = value; } /** * Gets the value of the locationcode property. * * @return * possible object is * {@link String } * */ public String getLOCATIONCODE() { return locationcode; } /** * Sets the value of the locationcode property. * * @param value * allowed object is * {@link String }
* */ public void setLOCATIONCODE(String value) { this.locationcode = value; } /** * Gets the value of the locationname property. * * @return * possible object is * {@link String } * */ public String getLOCATIONNAME() { return locationname; } /** * Sets the value of the locationname property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONNAME(String value) { this.locationname = value; } /** * Gets the value of the locationdate property. * * @return * possible object is * {@link String } * */ public String getLOCATIONDATE() { return locationdate; } /** * Sets the value of the locationdate property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONDATE(String value) { this.locationdate = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DTRSD1.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isAuthenticated() { return this.delegate.isAuthenticated(); } @Override public String getName() { return this.delegate.getName(); } @Override public Collection<GrantedAuthority> getAuthorities() { return this.delegate.getAuthorities(); } @Override public Map<String, Object> getTokenAttributes() { return this.delegate.getTokenAttributes(); } /** * Returns a JWT. It usually refers to a token string expressing with 'eyXXX.eyXXX.eyXXX' format. *
* @return the token value as a String */ public String tokenValue() { return delegate.getToken().getTokenValue(); } /** * Extract Subject from JWT. Here, Subject is the user ID in UUID format. * * @return the user ID as a UUID */ public UUID userId() { return UUID.fromString(delegate.getName()); } }
repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\config\AuthToken.java
2
请完成以下Java代码
protected String[] getDeploymentDescriptorLocations(AbstractProcessApplication processApplication) { ProcessApplication annotation = processApplication.getClass().getAnnotation(ProcessApplication.class); if(annotation == null) { return new String[] {ProcessApplication.DEFAULT_META_INF_PROCESSES_XML}; } else { return annotation.deploymentDescriptors(); } } protected boolean isEmptyFile(URL url) { InputStream inputStream = null; try { inputStream = url.openStream(); return inputStream.available() == 0; } catch (IOException e) { throw LOG.exceptionWhileReadingProcessesXml(url.toString(), e); } finally { IoUtil.closeSilently(inputStream);
} } protected ProcessesXml parseProcessesXml(URL url) { final ProcessesXmlParser processesXmlParser = new ProcessesXmlParser(); ProcessesXml processesXml = processesXmlParser.createParse() .sourceUrl(url) .execute() .getProcessesXml(); return processesXml; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\ParseProcessesXmlStep.java
1
请完成以下Java代码
public class CustomIdentityManager implements IdentityManager { private final Map<String, char[]> users; CustomIdentityManager(final Map<String, char[]> users) { this.users = users; } @Override public Account verify(Account account) { return account; } @Override public Account verify(Credential credential) { return null; } @Override public Account verify(String id, Credential credential) { Account account = getAccount(id); if (account != null && verifyCredential(account, credential)) { return account; } return null; } private boolean verifyCredential(Account account, Credential credential) { if (credential instanceof PasswordCredential) { char[] password = ((PasswordCredential) credential).getPassword(); char[] expectedPassword = users.get(account.getPrincipal().getName()); return Arrays.equals(password, expectedPassword); } return false;
} private Account getAccount(final String id) { if (users.containsKey(id)) { return new Account() { private static final long serialVersionUID = 1L; private final Principal principal = () -> id; @Override public Principal getPrincipal() { return principal; } @Override public Set<String> getRoles() { return Collections.emptySet(); } }; } return null; } }
repos\tutorials-master\server-modules\undertow\src\main\java\com\baeldung\undertow\secure\CustomIdentityManager.java
1
请完成以下Java代码
public String createBookForm(ModelMap map) { map.addAttribute("book", new Book()); map.addAttribute("action", "create"); return BOOK_FORM_PATH_NAME; } /** * 创建 Book * 处理 "/book/create" 的 POST 请求,用来新建 Book 信息 * 通过 @ModelAttribute 绑定表单实体参数,也通过 @RequestParam 传递参数 */ @RequestMapping(value = "/create", method = RequestMethod.POST) public String postBook(@ModelAttribute Book book) { bookService.insertByBook(book); return REDIRECT_TO_BOOK_URL; } /** * 获取更新 Book 表单 * 处理 "/book/update/{id}" 的 GET 请求,通过 URL 中的 id 值获取 Book 信息 * URL 中的 id ,通过 @PathVariable 绑定参数 */ @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public String getUser(@PathVariable Long id, ModelMap map) { map.addAttribute("book", bookService.findById(id)); map.addAttribute("action", "update"); return BOOK_FORM_PATH_NAME; } /** * 更新 Book * 处理 "/update" 的 PUT 请求,用来更新 Book 信息 */
@RequestMapping(value = "/update", method = RequestMethod.POST) public String putBook(@ModelAttribute Book book) { bookService.update(book); return REDIRECT_TO_BOOK_URL; } /** * 删除 Book * 处理 "/book/{id}" 的 GET 请求,用来删除 Book 信息 */ @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) public String deleteBook(@PathVariable Long id) { bookService.delete(id); return REDIRECT_TO_BOOK_URL; } }
repos\springboot-learning-example-master\chapter-5-spring-boot-data-jpa\src\main\java\demo\springboot\web\BookController.java
1
请完成以下Java代码
public class Rating { double points; List<Review> reviews = new ArrayList<>(); public Rating() {} public void add(Review review) { reviews.add(review); computeRating(); } private double computeRating() { double totalPoints = reviews.stream().map(Review::getPoints).reduce(0, Integer::sum); this.points = totalPoints / reviews.size(); return this.points; } public static Rating average(Rating r1, Rating r2) {
Rating combined = new Rating(); combined.reviews = new ArrayList<>(r1.reviews); combined.reviews.addAll(r2.reviews); combined.computeRating(); return combined; } public double getPoints() { return points; } public List<Review> getReviews() { return reviews; } }
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\reduce\entities\Rating.java
1
请完成以下Java代码
public static <T> CommonResult<T> failed(IErrorCode errorCode,String message) { return new CommonResult<T>(errorCode.getCode(), message, null); } /** * 失败返回结果 * @param message 提示信息 */ public static <T> CommonResult<T> failed(String message) { return new CommonResult<T>(ResultCode.FAILED.getCode(), message, null); } /** * 失败返回结果 */ public static <T> CommonResult<T> failed() { return failed(ResultCode.FAILED); } /** * 参数验证失败返回结果 */ public static <T> CommonResult<T> validateFailed() { return failed(ResultCode.VALIDATE_FAILED); } /** * 参数验证失败返回结果 * @param message 提示信息 */ public static <T> CommonResult<T> validateFailed(String message) { return new CommonResult<T>(ResultCode.VALIDATE_FAILED.getCode(), message, null); } /** * 未登录返回结果 */ public static <T> CommonResult<T> unauthorized(T data) {
return new CommonResult<T>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data); } /** * 未授权返回结果 */ public static <T> CommonResult<T> forbidden(T data) { return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data); } public long getCode() { return code; } public void setCode(long code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\api\CommonResult.java
1
请完成以下Java代码
public Class<?> embeddable() { return PhoneNumber.class; } @Override public Class returnedClass() { return PhoneNumber.class; } @Override public boolean equals(PhoneNumber x, PhoneNumber y) { if (x == y) { return true; } if (Objects.isNull(x) || Objects.isNull(y)) { return false; } return x.equals(y); } @Override public int hashCode(PhoneNumber x) { return x.hashCode(); } @Override public PhoneNumber deepCopy(PhoneNumber value) { if (Objects.isNull(value)) { return null; }
return new PhoneNumber(value.getCountryCode(), value.getCityCode(), value.getNumber()); } @Override public boolean isMutable() { return false; } @Override public Serializable disassemble(PhoneNumber value) { return (Serializable) value; } @Override public PhoneNumber assemble(Serializable cached, Object owner) { return (PhoneNumber) cached; } @Override public PhoneNumber replace(PhoneNumber detached, PhoneNumber managed, Object owner) { return detached; } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\PhoneNumberType.java
1
请完成以下Java代码
public class GS1Elements { private final ImmutableList<GS1Element> elements; private final ImmutableMap<String, GS1Element> byKey; private final ImmutableMap<GS1ApplicationIdentifier, GS1Element> byApplicationIdentifier; private GS1Elements(@NonNull final List<GS1Element> list) { this.elements = ImmutableList.copyOf(list); this.byKey = list.stream().collect(ImmutableMap.toImmutableMap(GS1Element::getKey, element -> element)); this.byApplicationIdentifier = list.stream() .filter(element -> element.getIdentifier() != null) .collect(ImmutableMap.toImmutableMap(GS1Element::getIdentifier, element -> element)); } public static GS1Elements ofList(final List<GS1Element> list) { return new GS1Elements(list); } public List<GS1Element> toList() {return elements;} public Optional<GTIN> getGTIN() { final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.GTIN); if (element == null) { return Optional.empty(); } return GTIN.optionalOfNullableString(element.getValueAsString()); } public Optional<BigDecimal> getWeightInKg()
{ final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.ITEM_NET_WEIGHT_KG); if (element == null) { return Optional.empty(); } return Optional.of(element.getValueAsBigDecimal()); } public Optional<LocalDate> getBestBeforeDate() { final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.BEST_BEFORE_DATE); if (element == null) { return Optional.empty(); } return Optional.of(element.getValueAsLocalDate()); } public Optional<String> getLotNumber() { final GS1Element element = byApplicationIdentifier.get(GS1ApplicationIdentifier.BATCH_OR_LOT_NUMBER); if (element == null) { return Optional.empty(); } return Optional.of(element.getValueAsString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GS1Elements.java
1
请完成以下Java代码
public void createTable(String tableName) throws TableExistsException, AccumuloException, AccumuloSecurityException { client.tableOperations().create(tableName); } public void performBatchWrite(String tableName) throws TableNotFoundException, MutationsRejectedException { try (BatchWriter writer = client.createBatchWriter(tableName, new BatchWriterConfig())) { Mutation mutation1 = new Mutation("row1"); mutation1.at() .family("column family 1") .qualifier("column family 1 qualifier 1") .visibility("public").put("value 1"); Mutation mutation2 = new Mutation("row2"); mutation2.at() .family("column family 1") .qualifier("column family 1 qualifier 2") .visibility("private").put("value 2"); writer.addMutation(mutation1);
writer.addMutation(mutation2); } } public void scanTableData(String tableName) throws TableNotFoundException { try (var scanner = client.createScanner(tableName, new Authorizations("public"))) { String keyValue = ""; scanner.setRange(new Range()); for (Map.Entry<Key, Value> entry : scanner) { keyValue = entry.getKey() + " -> " + entry.getValue(); } } } }
repos\tutorials-master\apache-libraries-3\src\main\java\com\baeldung\apache\accumulo\AccumuloDataOperations.java
1
请完成以下Java代码
public class ElasticsearchRestClientHealthIndicator extends AbstractHealthIndicator { private static final String RED_STATUS = "red"; private final Rest5Client client; private final JsonParser jsonParser; public ElasticsearchRestClientHealthIndicator(Rest5Client client) { super("Elasticsearch health check failed"); this.client = client; this.jsonParser = JsonParserFactory.getJsonParser(); } @Override protected void doHealthCheck(Health.Builder builder) throws Exception { Response response = this.client.performRequest(new Request("GET", "/_cluster/health/")); if (response.getStatusCode() != HttpStatus.SC_OK) { builder.down(); builder.withDetail("statusCode", response.getStatusCode()); builder.withDetail("warnings", response.getWarnings());
return; } try (InputStream inputStream = response.getEntity().getContent()) { doHealthCheck(builder, StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8)); } } private void doHealthCheck(Health.Builder builder, String json) { Map<String, Object> response = this.jsonParser.parseMap(json); String status = (String) response.get("status"); builder.status((RED_STATUS.equals(status)) ? Status.OUT_OF_SERVICE : Status.UP); builder.withDetails(response); } }
repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\health\ElasticsearchRestClientHealthIndicator.java
1
请完成以下Java代码
public VariableAggregationDefinition clone() { VariableAggregationDefinition aggregation = new VariableAggregationDefinition(); aggregation.setValues(this); return aggregation; } public void setValues(VariableAggregationDefinition otherVariableDefinitionAggregation) { setImplementationType(otherVariableDefinitionAggregation.getImplementationType()); setImplementation(otherVariableDefinitionAggregation.getImplementation()); setTarget(otherVariableDefinitionAggregation.getTarget()); setTargetExpression(otherVariableDefinitionAggregation.getTargetExpression()); List<Variable> otherDefinitions = otherVariableDefinitionAggregation.getDefinitions(); if (otherDefinitions != null) { List<Variable> newDefinitions = new ArrayList<>(otherDefinitions.size()); for (Variable otherDefinition : otherDefinitions) { newDefinitions.add(otherDefinition.clone()); } setDefinitions(newDefinitions); } setStoreAsTransientVariable(otherVariableDefinitionAggregation.isStoreAsTransientVariable()); setCreateOverviewVariable(otherVariableDefinitionAggregation.isCreateOverviewVariable()); } public static class Variable { protected String source; protected String target; protected String targetExpression; protected String sourceExpression; public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target;
} public String getTargetExpression() { return targetExpression; } public void setTargetExpression(String targetExpression) { this.targetExpression = targetExpression; } public String getSourceExpression() { return sourceExpression; } public void setSourceExpression(String sourceExpression) { this.sourceExpression = sourceExpression; } @Override public Variable clone() { Variable definition = new Variable(); definition.setValues(this); return definition; } public void setValues(Variable otherDefinition) { setSource(otherDefinition.getSource()); setSourceExpression(otherDefinition.getSourceExpression()); setTarget(otherDefinition.getTarget()); setTargetExpression(otherDefinition.getTargetExpression()); } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\VariableAggregationDefinition.java
1
请完成以下Java代码
public Builder annotate(ClassName className, Consumer<Annotation.Builder> annotation) { this.annotations.add(className, annotation); return this; } /** * Annotate the parameter with the specified single annotation. * @param className the class of the annotation * @return this for method chaining */ public Builder singleAnnotate(ClassName className) { return singleAnnotate(className, null); } /** * Annotate the parameter with the specified single annotation, customized by the * specified consumer. * @param className the class of the annotation * @param annotation a consumer of the builder * @return this for method chaining */ public Builder singleAnnotate(ClassName className, Consumer<Annotation.Builder> annotation) { this.annotations.addSingle(className, annotation); return this; } /** * Annotate the parameter with the specified repeatable annotation. * @param className the class of the annotation * @return this for method chaining */ public Builder repeatableAnnotate(ClassName className) { return repeatableAnnotate(className, null); } /** * Annotate the parameter with the specified repeatable annotation, customized by
* the specified consumer. * @param className the class of the annotation * @param annotation a consumer of the builder * @return this for method chaining */ public Builder repeatableAnnotate(ClassName className, Consumer<Annotation.Builder> annotation) { this.annotations.addRepeatable(className, annotation); return this; } public Parameter build() { return new Parameter(this); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\Parameter.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonProduct { @ApiModelProperty( // dataType = "java.lang.Integer", // value = "This translates to `M_Product.M_Product_ID`.") @NonNull @JsonProperty("id") JsonMetasfreshId id; @ApiModelProperty("This translates to `M_Product.M_Product_Category_ID`.") @NonNull @JsonProperty("productCategoryId") JsonMetasfreshId productCategoryId; @ApiModelProperty("This translates to `M_Product.Value`.") @NonNull @JsonProperty("productNo") String productNo; @NonNull @JsonProperty("name") String name; @Nullable @JsonProperty("description") String description; @ApiModelProperty(value = "This translates to `M_Product.UPC`.<br>Note that different bPartners may assign different EANs to the same product") @Nullable @JsonInclude(Include.NON_EMPTY) @JsonProperty("ean") String ean; @ApiModelProperty("This translates to `M_Product.ExternalId`.") @Nullable @JsonInclude(Include.NON_EMPTY) @JsonProperty("externalId") String externalId; @ApiModelProperty("This is the `C_UOM.UOMSymbol` of the product's unit of measurement.") @NonNull @JsonProperty("uom") String uom; @ApiModelProperty("This is the `C_UOM.X12DE355` of the product's unit of measurement.") @NonNull @JsonProperty("uomX12DE355") String uomX12DE355; @ApiModelProperty( // allowEmptyValue = true, // dataType = "java.lang.Integer", // value = "This translates to `M_Product.Manufacturer_ID`.") @Nullable @JsonProperty("manufacturerId") JsonMetasfreshId manufacturerId; @ApiModelProperty( // allowEmptyValue = true, // dataType = "java.lang.String", // value = "This translates to `C_BPartner.Name` of the product's manufacturer.") @Nullable @JsonProperty("manufacturerName") String manufacturerName; @ApiModelProperty( // allowEmptyValue = true, //
dataType = "java.lang.String", // value = "This translates to `M_Product.ManufacturerArticleNumber`.") @Nullable @JsonProperty("manufacturerNumber") String manufacturerNumber; @ApiModelProperty( // dataType = "java.time.LocalDate", // value = "This translates to `M_Product.DiscontinuedFrom`.") @Nullable @JsonProperty("discontinuedFrom") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") LocalDate discontinuedFrom; @NonNull @Singular @JsonProperty("bpartners") List<JsonProductBPartner> bpartners; @Nullable @JsonInclude(Include.NON_NULL) @JsonProperty("albertaProductInfo") JsonAlbertaProductInfo albertaProductInfo; @Nullable @Singular @JsonProperty("uomConversions") List<JsonProductUOMConversion> uomConversions; @Nullable @Singular @JsonProperty("mHUPIItemProducts") List<JsonMHUPIItemProduct> mhupiItemProducts; }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\response\JsonProduct.java
2
请完成以下Java代码
public boolean isTableID() { return get_ValueAsBoolean(COLUMNNAME_IsTableID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrefix (final @Nullable java.lang.String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } @Override public java.lang.String getPrefix() { return get_ValueAsString(COLUMNNAME_Prefix); } /** * RestartFrequency AD_Reference_ID=541879 * Reference name: AD_SequenceRestart Frequency */ public static final int RESTARTFREQUENCY_AD_Reference_ID=541879; /** Year = Y */ public static final String RESTARTFREQUENCY_Year = "Y"; /** Month = M */ public static final String RESTARTFREQUENCY_Month = "M"; /** Day = D */ public static final String RESTARTFREQUENCY_Day = "D"; @Override public void setRestartFrequency (final @Nullable java.lang.String RestartFrequency) { set_Value (COLUMNNAME_RestartFrequency, RestartFrequency); } @Override public java.lang.String getRestartFrequency() {
return get_ValueAsString(COLUMNNAME_RestartFrequency); } @Override public void setStartNo (final int StartNo) { set_Value (COLUMNNAME_StartNo, StartNo); } @Override public int getStartNo() { return get_ValueAsInt(COLUMNNAME_StartNo); } @Override public void setSuffix (final @Nullable java.lang.String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } @Override public java.lang.String getSuffix() { return get_ValueAsString(COLUMNNAME_Suffix); } @Override public void setVFormat (final @Nullable java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } @Override public java.lang.String getVFormat() { return get_ValueAsString(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepeatedPassword() { return repeatedPassword; } public void setRepeatedPassword(String repeatedPassword) { this.repeatedPassword = repeatedPassword; } }
repos\tutorials-master\jackson-modules\jackson-annotations\src\main\java\com\baeldung\jackson\jsonignorevstransient\User.java
1
请完成以下Java代码
public void setClassname (java.lang.String Classname) { set_Value (COLUMNNAME_Classname, Classname); } /** Get Java-Klasse. @return Java-Klasse */ @Override public java.lang.String getClassname () { return (java.lang.String)get_Value(COLUMNNAME_Classname); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Interner Name. @param InternalName Generally used to give records a name that can be safely referenced from code. */ @Override public void setInternalName (java.lang.String InternalName) { set_ValueNoCheck (COLUMNNAME_InternalName, InternalName); }
/** Get Interner Name. @return Generally used to give records a name that can be safely referenced from code. */ @Override public java.lang.String getInternalName () { return (java.lang.String)get_Value(COLUMNNAME_InternalName); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\javaclasses\model\X_AD_JavaClass_Type.java
1
请完成以下Java代码
public boolean isMandatory() { return m_mandatory; } // isMandatory /** * Enable Editor * @param rw true, if you can enter/select data */ @Override public void setReadWrite (boolean rw) { if (super.isEnabled() != rw) super.setEnabled(rw); } // setReadWrite /** * Is it possible to edit * @return true, if editable */ @Override public boolean isReadWrite() { return super.isEnabled(); } // isReadWrite /** * Set Editor to value * @param value value of the editor */ @Override public void setValue (Object value) { if (value == null) setText("");
else setText(value.toString()); } // setValue /** * Return Editor value * @return current value */ @Override public Object getValue() { return getText(); } // getValue /** * Return Display Value * @return displayed String value */ @Override public String getDisplay() { return getText(); } // getDisplay } // CToggleButton
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CToggleButton.java
1
请完成以下Java代码
private void createValues(DSLContext context) { ArticleRecord article = context.newRecord(Article.ARTICLE); article.setId(2); article.setTitle("jOOQ examples"); article.setDescription("A few examples of jOOQ CRUD operations"); article.setAuthorId(1); save(article); AuthorRecord author = context.newRecord(Author.AUTHOR); author.setId(1); author.setFirstName("John"); author.setLastName("Smith"); author.setAge(40); save(author); } private void readValues(DSLContext context) { Result<Record> authors = getAll( context, Author.AUTHOR ); authors.forEach(author -> { Integer id = author.getValue(Author.AUTHOR.ID); String firstName = author.getValue(Author.AUTHOR.FIRST_NAME); String lastName = author.getValue(Author.AUTHOR.LAST_NAME); Integer age = author.getValue(Author.AUTHOR.AGE); System.out.printf("Author %s %s has id: %d and age: %d%n", firstName, lastName, id, age); }); Result<Record> articles = getFields( context, Author.AUTHOR, Article.ARTICLE.ID, Article.ARTICLE.TITLE ); AuthorRecord author = getOne( context, Author.AUTHOR, Author.AUTHOR.ID.eq(1) ); } private void updateValues(DSLContext context) { HashMap<Field<String>, String> fieldsToUpdate = new HashMap<>();
fieldsToUpdate.put(Author.AUTHOR.FIRST_NAME, "David"); fieldsToUpdate.put(Author.AUTHOR.LAST_NAME, "Brown"); update( context, Author.AUTHOR, fieldsToUpdate, Author.AUTHOR.ID.eq(1) ); ArticleRecord article = context.fetchOne(Article.ARTICLE, Article.ARTICLE.ID.eq(1)); article.setTitle("A New Article Title"); update(article); } private void deleteValues(DSLContext context) { delete( context, Article.ARTICLE, Article.ARTICLE.ID.eq(1) ); AuthorRecord author = context.fetchOne(Author.AUTHOR, Author.AUTHOR.ID.eq(1)); delete(author); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\CrudExamples.java
1
请完成以下Java代码
public Mono<Void> saveSessionInformation(ReactiveSessionInformation information) { this.sessionById.put(information.getSessionId(), information); this.sessionIdsByPrincipal.computeIfAbsent(information.getPrincipal(), (key) -> new CopyOnWriteArraySet<>()) .add(information.getSessionId()); return Mono.empty(); } @Override public Mono<ReactiveSessionInformation> getSessionInformation(String sessionId) { return Mono.justOrEmpty(this.sessionById.get(sessionId)); } @Override public Mono<ReactiveSessionInformation> removeSessionInformation(String sessionId) { return getSessionInformation(sessionId).doOnNext((sessionInformation) -> { this.sessionById.remove(sessionId); Set<String> sessionsUsedByPrincipal = this.sessionIdsByPrincipal.get(sessionInformation.getPrincipal()); if (sessionsUsedByPrincipal != null) {
sessionsUsedByPrincipal.remove(sessionId); if (sessionsUsedByPrincipal.isEmpty()) { this.sessionIdsByPrincipal.remove(sessionInformation.getPrincipal()); } } }); } @Override public Mono<ReactiveSessionInformation> updateLastAccessTime(String sessionId) { ReactiveSessionInformation session = this.sessionById.get(sessionId); if (session != null) { return session.refreshLastRequest().thenReturn(session); } return Mono.empty(); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\session\InMemoryReactiveSessionRegistry.java
1
请在Spring Boot框架中完成以下Java代码
public class JSONInvoiceDetailItem { Integer seqNo; String label; String description; LocalDate date; BigDecimal price; String note; @JsonCreator @Builder public JSONInvoiceDetailItem(
@JsonProperty("seqNo") @Nullable final Integer seqNo, @JsonProperty("label") @Nullable final String label, @JsonProperty("description") @Nullable final String description, @JsonProperty("date") @Nullable final LocalDate date, @JsonProperty("price") @Nullable final BigDecimal price, @JsonProperty("note") @Nullable final String note) { this.seqNo = seqNo; this.label = label; this.description = description; this.date = date; this.price = price; this.note = note; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api\src\main\java\de\metas\rest_api\invoicecandidates\request\JSONInvoiceDetailItem.java
2
请完成以下Java代码
default boolean isChildRunning() { return isRunning(); } /** * Return true if the container is running, has never been started, or has been * stopped. * @return true if the state is as expected. * @since 2.8 * @see #stopAbnormally(Runnable) */ default boolean isInExpectedState() { return true; } /** * Stop the container after some exception so that {@link #isInExpectedState()} will * return false. * @param callback the callback. * @since 2.8 * @see #isInExpectedState() */ default void stopAbnormally(Runnable callback) { stop(callback); } /** * If this container has child containers, return the child container that is assigned * the topic/partition. Return this when there are no child containers. * @param topic the topic. * @param partition the partition. * @return the container. */ default MessageListenerContainer getContainerFor(String topic, int partition) { return this; } /** * Notify a parent container that a child container has stopped. * @param child the container. * @param reason the reason. * @since 2.9.7
*/ default void childStopped(MessageListenerContainer child, ConsumerStoppedEvent.Reason reason) { } /** * Notify a parent container that a child container has started. * @param child the container. * @since 3.3 */ default void childStarted(MessageListenerContainer child) { } @Override default void destroy() { stop(); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\MessageListenerContainer.java
1
请在Spring Boot框架中完成以下Java代码
public class UserDbConfig { @Bean @Primary public DataSource userDataSource() { return DataSourceBuilder.create() .url("jdbc:h2:mem:userdb") .username("sa") .password("") .driverClassName("org.h2.Driver") .build(); } @Bean @Primary public LocalContainerEntityManagerFactoryBean userEntityManagerFactory( EntityManagerFactoryBuilder builder) { return builder .dataSource(userDataSource()) .packages("com.baeldung.entity")
.persistenceUnit("userPU") .properties(Map.of("hibernate.hbm2ddl.auto", "none")) .build(); } @Bean @Primary public PlatformTransactionManager userTransactionManager( EntityManagerFactory userEntityManagerFactory) { return new JpaTransactionManager(userEntityManagerFactory); } @PostConstruct public void migrateUserDb() { Flyway.configure() .dataSource(userDataSource()) .locations("classpath:db/migration/userdb") .load() .migrate(); } }
repos\tutorials-master\spring-boot-modules\flyway-multidb-springboot\src\main\java\com\baeldung\config\UserDbConfig.java
2
请完成以下Java代码
public void setCopyProperties(boolean copyProperties) { this.copyProperties = copyProperties; } /** * Set a delimiter to be added between the compression type and the original encoding, * if any. Defaults to {@code ", "} (since 2.3); for compatibility with consumers * using versions of spring-amqp earlier than 2.2.12, set it to {@code ":"} (no * trailing space). * @param encodingDelimiter the delimiter. * @since 2.2.12 */ public void setEncodingDelimiter(String encodingDelimiter) { Assert.notNull(encodingDelimiter, "'encodingDelimiter' cannot be null"); this.encodingDelimiter = encodingDelimiter; } @Override public Message postProcessMessage(Message message) throws AmqpException { try { ByteArrayOutputStream zipped = new ByteArrayOutputStream(); OutputStream zipper = getCompressorStream(zipped); FileCopyUtils.copy(new ByteArrayInputStream(message.getBody()), zipper); byte[] compressed = zipped.toByteArray(); if (this.logger.isTraceEnabled()) { this.logger.trace("Compressed " + message.getBody().length + " to " + compressed.length); } MessageProperties originalProperties = message.getMessageProperties(); MessagePropertiesBuilder messagePropertiesBuilder = this.copyProperties ? MessagePropertiesBuilder.fromClonedProperties(originalProperties) : MessagePropertiesBuilder.fromProperties(originalProperties); if (this.autoDecompress) { messagePropertiesBuilder.setHeader(MessageProperties.SPRING_AUTO_DECOMPRESS, true); } MessageProperties messageProperties = messagePropertiesBuilder.setContentEncoding(getEncoding() + (!StringUtils.hasText(originalProperties.getContentEncoding()) ? ""
: this.encodingDelimiter + originalProperties.getContentEncoding())) .build(); return new Message(compressed, messageProperties); } catch (IOException e) { throw new AmqpIOException(e); } } @Override public int getOrder() { return this.order; } /** * Set the order. * @param order the order, default 0. * @see Ordered */ protected void setOrder(int order) { this.order = order; } /** * Get the stream. * @param stream The output stream to write the compressed data to. * @return the compressor output stream. * @throws IOException IOException */ protected abstract OutputStream getCompressorStream(OutputStream stream) throws IOException; /** * Get the encoding. * @return the content-encoding header. */ protected abstract String getEncoding(); }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\postprocessor\AbstractCompressingPostProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public void setQuotation_OrderLine(final org.compiere.model.I_C_OrderLine Quotation_OrderLine) { set_ValueFromPO(COLUMNNAME_Quotation_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, Quotation_OrderLine); } @Override public void setQuotation_OrderLine_ID (final int Quotation_OrderLine_ID) { if (Quotation_OrderLine_ID < 1) set_Value (COLUMNNAME_Quotation_OrderLine_ID, null); else set_Value (COLUMNNAME_Quotation_OrderLine_ID, Quotation_OrderLine_ID); } @Override public int getQuotation_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_Quotation_OrderLine_ID); } /** * Type AD_Reference_ID=541251 * Reference name: C_Project_Repair_CostCollector_Type */ public static final int TYPE_AD_Reference_ID=541251; /** SparePartsToBeInvoiced = SP+ */ public static final String TYPE_SparePartsToBeInvoiced = "SP+"; /** SparePartsOwnedByCustomer = SPC */ public static final String TYPE_SparePartsOwnedByCustomer = "SPC"; /** RepairProductToReturn = RPC */ public static final String TYPE_RepairProductToReturn = "RPC"; /** RepairingConsumption = RP+ */ public static final String TYPE_RepairingConsumption = "RP+"; @Override public void setType (final java.lang.String Type)
{ set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_ValueNoCheck (COLUMNNAME_VHU_ID, null); else set_ValueNoCheck (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_CostCollector.java
2
请完成以下Java代码
public static class Html40Frameset extends Doctype { /** * */ private static final long serialVersionUID = 5442355270707253725L; public Html40Frameset() { this.name = "HTML"; this.visibility = PUBLIC; this.identifier = "\"-//W3C//DTD HTML 4.0 Frameset//EN\""; this.uri = "\"http://www.w3.org/TR/REC-html40/frameset.dtd\""; this.updateElementType(); } } /** * The XHTML 1.0 Strict DTD * This is the same as HTML 4.0 Strict except for changes due * to the differences between XML and SGML. * <p> * See: <a href="http://www.w3.org/TR/xhtml1"> * http://www.w3.org/TR/xhtml1</a> */ public static class XHtml10Strict extends Doctype { /** * */ private static final long serialVersionUID = 906251485117803601L; public XHtml10Strict() { this.name = "html"; this.visibility = PUBLIC; this.identifier = "\"-//W3C//DTD XHTML 1.0 Strict//EN\""; this.uri = "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\""; this.updateElementType(); } } /** * The XHTML 1.0 Transitional DTD * This is the same as HTML 4.0 Transitional except for changes due * to the differences between XML and SGML. * <p> * See: <a href="http://www.w3.org/TR/xhtml1">
* http://www.w3.org/TR/xhtml1</a> */ public static class XHtml10Transitional extends Doctype { /** * */ private static final long serialVersionUID = -79107605400685902L; public XHtml10Transitional() { this.name = "html"; this.visibility = PUBLIC; this.identifier = "\"-//W3C//DTD XHTML 1.0 Transitional//EN\""; this.uri = "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\""; this.updateElementType(); } } /** * The XHTML 1.0 Frameset DTD * This is the same as HTML 4.0 Frameset except for changes due * to the differences between XML and SGML. * <p> * See: <a href="http://www.w3.org/TR/xhtml1"> * http://www.w3.org/TR/xhtml1</a> */ public static class XHtml10Frameset extends Doctype { /** * */ private static final long serialVersionUID = 4590750316568237831L; public XHtml10Frameset() { this.name = "html"; this.visibility = PUBLIC; this.identifier = "\"-//W3C//DTD XHTML 1.0 Frameset//EN\""; this.uri = "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\""; this.updateElementType(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\Doctype.java
1
请完成以下Java代码
public Integer getForwardCount() { return forwardCount; } public void setForwardCount(Integer forwardCount) { this.forwardCount = forwardCount; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", categoryId=").append(categoryId); sb.append(", title=").append(title); sb.append(", pic=").append(pic); sb.append(", productCount=").append(productCount);
sb.append(", recommendStatus=").append(recommendStatus); sb.append(", createTime=").append(createTime); sb.append(", collectCount=").append(collectCount); sb.append(", readCount=").append(readCount); sb.append(", commentCount=").append(commentCount); sb.append(", albumPics=").append(albumPics); sb.append(", description=").append(description); sb.append(", showStatus=").append(showStatus); sb.append(", forwardCount=").append(forwardCount); sb.append(", categoryName=").append(categoryName); sb.append(", content=").append(content); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubject.java
1
请完成以下Java代码
public GetWeightResponse handleRequest(final IDeviceRequest<GetWeightResponse> request) { final String endpointResultStr = endpoint.sendCmd(cmd.getCmd()); logger.trace("Received result string {} from endpoint {}; command: {}", endpointResultStr, endpoint, cmd); final String endPointWeight = parser.parse(cmd, endpointResultStr, weightFieldName, String.class); logger.trace("Parsed weight number string {} from the result string; will round according to roundWeightToPrecision={}", endPointWeight, roundWeightToPrecision); final BigDecimal weight; try { final String formattedEndpointWeight = endPointWeight.replace(",", "."); weight = new BigDecimal(formattedEndpointWeight); } catch (final NumberFormatException e) { throw new DeviceException("The weight string '" + endPointWeight + "' which was parsed from the device's response string '" + endpointResultStr + "' is not a number ", e); } final String endPointUom = parser.parse(cmd, endpointResultStr, uomFieldName, String.class); logger.trace("Parsed uom string {} from the result string", endPointUom); return new GetWeightResponse( roundWeightToPrecision < 0 // task 09207: only round if a precision >=0 was supplied ? weight : weight.setScale(roundWeightToPrecision, RoundingMode.HALF_UP), endPointUom); } public ScalesGetWeightHandler<C> setEndpoint(final ITcpConnectionEndPoint endpoint) { this.endpoint = endpoint; return this; } public ScalesGetWeightHandler<C> setParser(final IParser<C> parser) { this.parser = parser; return this; } public ScalesGetWeightHandler<C> setCmd(final C cmd) { this.cmd = cmd; return this; } public ScalesGetWeightHandler<C> setWeightFieldName(final String fieldName) {
this.weightFieldName = fieldName; return this; } public ScalesGetWeightHandler<C> setUOMFieldName(final String fieldName) { this.uomFieldName = fieldName; return this; } /** * The weighing result number will be round to the given precision using {@link RoundingMode#HALF_UP}.<br> * If called with a value less than zero, or not called at all, then no rounding will be done. * * @param roundWeightToPrecision * @task http://dewiki908/mediawiki/index.php/09207_Wiegen_nur_eine_Nachkommastelle_%28101684670982%29 */ public ScalesGetWeightHandler<C> setroundWeightToPrecision(final int roundWeightToPrecision) { this.roundWeightToPrecision = roundWeightToPrecision; return this; } @Override public String toString() { return String.format( "ScalesGetWeightHandler [endpoint=%s, parser=%s, cmd=%s, weightFieldName=%s, uomFieldName=%s, weightRoundToPrecision=%s]", endpoint, parser, cmd, weightFieldName, uomFieldName, roundWeightToPrecision); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\ScalesGetWeightHandler.java
1
请完成以下Java代码
public I_S_Resource getPlant() { return plant; } @Override public int getPlant_ID() { return plantId; } @Override public IMRPSegment setPlant(final I_S_Resource plant) { final int plantIdNew; if (plant == null || plant.getS_Resource_ID() <= 0) { plantIdNew = -1; } else { plantIdNew = plant.getS_Resource_ID(); } // No change => return this if (plantIdNew == this.plantId) { return this; } final MRPSegment mrpSegmentNew = new MRPSegment(this); mrpSegmentNew.plantId = plantIdNew; mrpSegmentNew.plant = plant; return mrpSegmentNew; } @Override public I_M_Product getM_Product() { return product; } @Override public int getM_Product_ID() { return productId;
} @Override public IMRPSegment setM_Product(final I_M_Product product) { final int productIdNew; if (product == null || product.getM_Product_ID() <= 0) { productIdNew = -1; } else { productIdNew = product.getM_Product_ID(); } // No change => return this if (productIdNew == this.productId) { return this; } final MRPSegment mrpSegmentNew = new MRPSegment(this); mrpSegmentNew.productId = productIdNew; mrpSegmentNew.product = product; return mrpSegmentNew; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPSegment.java
1
请完成以下Java代码
public <T> T sendAndReceive( @NonNull final JAXBElement<?> messagePayload, @NonNull final Class<? extends T> expectedResponseClass) { final String uri = config.getBaseUrl() + urlPrefix; final JAXBElement<?> responseElement = (JAXBElement<?>)webServiceTemplate.marshalSendAndReceive(uri, messagePayload); final Object responseValue = responseElement.getValue(); if (expectedResponseClass.isInstance(responseValue)) { return expectedResponseClass.cast(responseValue); } final FaultInfo faultInfo = faultInfoExtractor.extractFaultInfoOrNull(responseValue); if (faultInfo != null) { throw Msv3ClientException.builder() .msv3FaultInfo(faultInfo) .build() .setParameter("uri", uri) .setParameter("config", config); } else {
throw new AdempiereException("Webservice returned unexpected response") .appendParametersToMessage() .setParameter("uri", uri) .setParameter("config", config) .setParameter("response", responseValue); } } @VisibleForTesting public WebServiceTemplate getWebServiceTemplate() { return webServiceTemplate; } @FunctionalInterface public static interface FaultInfoExtractor { FaultInfo extractFaultInfoOrNull(Object value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\MSV3Client.java
1
请完成以下Java代码
public String getCustomerTypeString() { return customerTypeString; } public void setCustomerTypeString(String customerTypeString) { this.customerTypeString = customerTypeString; } public CustomerType getCustomerTypeOfSubset() { return customerTypeOfSubset; } public void setCustomerTypeOfSubset(CustomerType customerTypeOfSubset) { this.customerTypeOfSubset = customerTypeOfSubset; } public CustomerType getCustomerTypeMatchesPattern() { return customerTypeMatchesPattern; } public void setCustomerTypeMatchesPattern(CustomerType customerTypeMatchesPattern) { this.customerTypeMatchesPattern = customerTypeMatchesPattern; } public static class Builder { private String customerTypeString; private CustomerType customerTypeOfSubset = CustomerType.NEW; private CustomerType customerTypeMatchesPattern;
public Builder withCustomerTypeString(String customerTypeString) { this.customerTypeString = customerTypeString; return this; } public Builder withCustomerTypeOfSubset(CustomerType customerTypeOfSubset) { this.customerTypeOfSubset = customerTypeOfSubset; return this; } public Builder withCustomerTypeMatchesPattern(CustomerType customerTypeMatchesPattern) { this.customerTypeMatchesPattern = customerTypeMatchesPattern; return this; } public Customer build() { return new Customer(customerTypeString, customerTypeOfSubset, customerTypeMatchesPattern); } } }
repos\tutorials-master\javaxval\src\main\java\com\baeldung\javaxval\enums\demo\Customer.java
1
请完成以下Java代码
public boolean isOverwriteSeqOnComplete() { return get_ValueAsBoolean(COLUMNNAME_IsOverwriteSeqOnComplete); } @Override public void setIsPickQAConfirm (final boolean IsPickQAConfirm) { set_Value (COLUMNNAME_IsPickQAConfirm, IsPickQAConfirm); } @Override public boolean isPickQAConfirm() { return get_ValueAsBoolean(COLUMNNAME_IsPickQAConfirm); } @Override public void setIsShipConfirm (final boolean IsShipConfirm) { set_Value (COLUMNNAME_IsShipConfirm, IsShipConfirm); } @Override public boolean isShipConfirm() { return get_ValueAsBoolean(COLUMNNAME_IsShipConfirm); } @Override public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public void setIsSplitWhenDifference (final boolean IsSplitWhenDifference) { set_Value (COLUMNNAME_IsSplitWhenDifference, IsSplitWhenDifference); } @Override public boolean isSplitWhenDifference() { return get_ValueAsBoolean(COLUMNNAME_IsSplitWhenDifference); } @Override public org.compiere.model.I_AD_Sequence getLotNo_Sequence() { return get_ValueAsPO(COLUMNNAME_LotNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setLotNo_Sequence(final org.compiere.model.I_AD_Sequence LotNo_Sequence) { set_ValueFromPO(COLUMNNAME_LotNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, LotNo_Sequence); } @Override public void setLotNo_Sequence_ID (final int LotNo_Sequence_ID) { if (LotNo_Sequence_ID < 1)
set_Value (COLUMNNAME_LotNo_Sequence_ID, null); else set_Value (COLUMNNAME_LotNo_Sequence_ID, LotNo_Sequence_ID); } @Override public int getLotNo_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_LotNo_Sequence_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrintName (final java.lang.String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName); } @Override public java.lang.String getPrintName() { return get_ValueAsString(COLUMNNAME_PrintName); } @Override public org.compiere.model.I_R_RequestType getR_RequestType() { return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class); } @Override public void setR_RequestType(final org.compiere.model.I_R_RequestType R_RequestType) { set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType); } @Override public void setR_RequestType_ID (final int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, R_RequestType_ID); } @Override public int getR_RequestType_ID() { return get_ValueAsInt(COLUMNNAME_R_RequestType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType.java
1
请完成以下Java代码
public IReceiptScheduleWarehouseDestProvider getWarehouseDestProvider() { return warehouseDestProviders; } @Override public IReceiptScheduleProducerFactory registerWarehouseDestProvider(final IReceiptScheduleWarehouseDestProvider provider) { warehouseDestProviders.addProvider(provider); return this; } /** * Mutable composite {@link IReceiptScheduleWarehouseDestProvider} */ private static final class CompositeReceiptScheduleWarehouseDestProvider implements IReceiptScheduleWarehouseDestProvider { private final IReceiptScheduleWarehouseDestProvider defaultProvider; private final CopyOnWriteArrayList<IReceiptScheduleWarehouseDestProvider> providers = new CopyOnWriteArrayList<>(); private CompositeReceiptScheduleWarehouseDestProvider(final IReceiptScheduleWarehouseDestProvider defaultProvider) { super(); Check.assumeNotNull(defaultProvider, "Parameter defaultProvider is not null"); this.defaultProvider = defaultProvider; } @Override public String toString() {
return MoreObjects.toStringHelper(this) .add("providers", providers) .add("defaultProvider", defaultProvider) .toString(); } private void addProvider(final IReceiptScheduleWarehouseDestProvider provider) { Check.assumeNotNull(provider, "Parameter provider is not null"); providers.add(provider); } @Override public Optional<WarehouseId> getWarehouseDest(final IContext context) { return Stream.concat(providers.stream(), Stream.of(defaultProvider)) .map(provider -> provider.getWarehouseDest(context)) .map(warehouseDest -> warehouseDest.orElse(null)) .filter(Objects::nonNull) .findFirst(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleProducerFactory.java
1
请完成以下Java代码
public Group retrieveOrCreateGroup(final RetrieveOrCreateGroupRequest request) { throw new UnsupportedOperationException(); } private List<I_C_Invoice_Candidate> retrieveInvoiceCandidatesForGroup(@NonNull final GroupId groupId) { return retrieveInvoiceCandidatesForGroupQuery(groupId).create().list(I_C_Invoice_Candidate.class); } private IQueryBuilder<I_C_Invoice_Candidate> retrieveInvoiceCandidatesForGroupQuery(@NonNull final GroupId groupId) { final OrderId orderId = OrderGroupRepository.extractOrderIdFromGroupId(groupId); final int orderCompensationGroupId = groupId.getOrderCompensationGroupId(); return queryBL.createQueryBuilder(I_C_Invoice_Candidate.class) .addEqualsFilter(I_C_Invoice_Candidate.COLUMN_C_Order_ID, orderId) .addEqualsFilter(I_C_Invoice_Candidate.COLUMN_C_Order_CompensationGroup_ID, orderCompensationGroupId); } private InvoiceCandidatesStorage retrieveStorage(final GroupId groupId) { final List<I_C_Invoice_Candidate> invoiceCandidates = retrieveInvoiceCandidatesForGroupQuery(groupId) .addEqualsFilter(I_C_Invoice_Candidate.COLUMN_IsGroupCompensationLine, true) .create() .list(I_C_Invoice_Candidate.class); return InvoiceCandidatesStorage.builder() .groupId(groupId) .invoiceCandidates(invoiceCandidates) .performDatabaseChanges(true) .build(); } public Group createPartialGroupFromCompensationLine(@NonNull final I_C_Invoice_Candidate invoiceCandidate) { InvoiceCandidateCompensationGroupUtils.assertCompensationLine(invoiceCandidate);
final GroupCompensationLine compensationLine = createCompensationLine(invoiceCandidate); final GroupRegularLine aggregatedRegularLine = GroupRegularLine.builder() .lineNetAmt(compensationLine.getBaseAmt()) .build(); final I_C_Order order = invoiceCandidate.getC_Order(); if (order == null) { throw new AdempiereException("Invoice candidate has no order: " + invoiceCandidate); } return Group.builder() .groupId(extractGroupId(invoiceCandidate)) .pricePrecision(orderBL.getPricePrecision(order)) .amountPrecision(orderBL.getAmountPrecision(order)) .regularLine(aggregatedRegularLine) .compensationLine(compensationLine) .build(); } public InvoiceCandidatesStorage createNotSaveableSingleOrderLineStorage(@NonNull final I_C_Invoice_Candidate invoiceCandidate) { return InvoiceCandidatesStorage.builder() .groupId(extractGroupId(invoiceCandidate)) .invoiceCandidate(invoiceCandidate) .performDatabaseChanges(false) .build(); } public void invalidateCompensationInvoiceCandidatesOfGroup(final GroupId groupId) { final IQuery<I_C_Invoice_Candidate> query = retrieveInvoiceCandidatesForGroupQuery(groupId) .addEqualsFilter(I_C_Invoice_Candidate.COLUMN_IsGroupCompensationLine, true) // only compensation lines .create(); invoiceCandDAO.invalidateCandsFor(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\compensationGroup\InvoiceCandidateGroupRepository.java
1
请完成以下Java代码
public class WriteoffESRActionHandler extends AbstractESRActionHandler { @Override public boolean process(final I_ESR_ImportLine line, final String message) { super.process(line, message); Check.assumeNotNull(line.getESR_Payment_Action(), "@" + ESRConstants.ERR_ESR_LINE_WITH_NO_PAYMENT_ACTION + "@"); // 04192 : Writeoff the invoice. final I_C_Invoice writeoffInvoice = line.getC_Invoice(); if (writeoffInvoice == null) { // We have nothing to do, but the line should still be flagged as processed. return true; } final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class); final IInvoiceDAO invoiceDAO = Services.get(IInvoiceDAO.class); // sanity check: there must be an payment with a negative OverUnderAmt final PaymentId esrImportLinePaymentId = PaymentId.ofRepoIdOrNull(line.getC_Payment_ID()); final I_C_Payment payment = esrImportLinePaymentId == null ? null : paymentDAO.getById(esrImportLinePaymentId); final ITrxManager trxManager = Services.get(ITrxManager.class); final String trxName = trxManager.getThreadInheritedTrxName(OnTrxMissingPolicy.ReturnTrxNone); InterfaceWrapperHelper.refresh(payment, trxName); // refresh the payment : very important; otherwise the over amount is not seen InterfaceWrapperHelper.refresh(writeoffInvoice, trxName); // refresh the payment : very important; otherwise the over amount is not seen
Check.assumeNotNull(payment, "Null payment for line {}", line.getESR_ImportLine_ID()); Check.errorIf(payment.getOverUnderAmt().signum() > 0, "Exces payment for line {}. Can't write this off", line.getESR_ImportLine_ID()); final BigDecimal writeOffAmt = invoiceDAO.retrieveOpenAmt(writeoffInvoice); trxManager.run(trxName, new TrxRunnable() { @Override public void run(String trxName) throws Exception { // must assure that the invoice has transaction InterfaceWrapperHelper.refresh(writeoffInvoice, trxName); invoiceBL.writeOffInvoice(writeoffInvoice, writeOffAmt, message); } }); return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\actionhandler\impl\WriteoffESRActionHandler.java
1
请在Spring Boot框架中完成以下Java代码
public List<Author> fetchAuthorsByAgeGreaterThanEqual(int age) { List<Author> authors = authorRepository.findByAgeGreaterThanEqual(age); return authors; } @Transactional(readOnly = true) public byte[] fetchAuthorAvatarViaId(long id) { Author author = authorRepository.findById(id).orElseThrow(); return author.getAvatar(); } @Transactional(readOnly = true) public List<Author> fetchAuthorsDetailsByAgeGreaterThanEqual(int age) { List<Author> authors = authorRepository.findByAgeGreaterThanEqual(40);
// don't do this since this is a N+1 case authors.forEach(a -> { a.getAvatar(); }); return authors; } @Transactional(readOnly = true) public List<AuthorDto> fetchAuthorsWithAvatarsByAgeGreaterThanEqual(int age) { List<AuthorDto> authors = authorRepository.findDtoByAgeGreaterThanEqual(40); return authors; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootAttributeLazyLoadingBasic\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public frameset setCols(int cols) { setCols(Integer.toString(cols)); return(this); } /** Sets the cols="" attribute @param cols Sets the cols="" attribute */ public frameset setCols(String cols) { addAttribute("cols",cols); return(this); } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public frameset addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public frameset addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public frameset addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public frameset addElement(String element) { addElementToRegistry(element); return(this);
} /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public frameset removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } /** The onload event occurs when the user agent finishes loading a window or all frames within a frameset. This attribute may be used with body and frameset elements. @param The script */ public void setOnLoad(String script) { addAttribute ( "onload", script ); } /** The onunload event occurs when the user agent removes a document from a window or frame. This attribute may be used with body and frameset elements. @param The script */ public void setOnUnload(String script) { addAttribute ( "onunload", script ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\frameset.java
1
请完成以下Java代码
public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 1) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sortierbegriff pro Benutzer. @param AD_User_SortPref_Hdr_ID Sortierbegriff pro Benutzer */ @Override public void setAD_User_SortPref_Hdr_ID (int AD_User_SortPref_Hdr_ID) { if (AD_User_SortPref_Hdr_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Hdr_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_SortPref_Hdr_ID, Integer.valueOf(AD_User_SortPref_Hdr_ID)); } /** Get Sortierbegriff pro Benutzer. @return Sortierbegriff pro Benutzer */ @Override public int getAD_User_SortPref_Hdr_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_SortPref_Hdr_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class); } @Override public void setAD_Window(org.compiere.model.I_AD_Window AD_Window) { set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window); } /** Set Fenster. @param AD_Window_ID Eingabe- oder Anzeige-Fenster */ @Override public void setAD_Window_ID (int AD_Window_ID) { if (AD_Window_ID < 1) set_Value (COLUMNNAME_AD_Window_ID, null); else set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID)); } /** Get Fenster. @return Eingabe- oder Anzeige-Fenster */ @Override public int getAD_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */
@Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Konferenz. @param IsConference Konferenz */ @Override public void setIsConference (boolean IsConference) { set_Value (COLUMNNAME_IsConference, Boolean.valueOf(IsConference)); } /** Get Konferenz. @return Konferenz */ @Override public boolean isConference () { Object oo = get_Value(COLUMNNAME_IsConference); 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_AD_User_SortPref_Hdr.java
1
请完成以下Java代码
public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; }
public Book getNextBook() { return nextBook; } public void setNextBook(Book nextBook) { this.nextBook = nextBook; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + ", price=" + price + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinFormula\src\main\java\com\bookstore\entity\Book.java
1
请完成以下Java代码
public String getFrontCoverArtUrl() { return frontCoverArtUrl; } public void setFrontCoverArtUrl(String frontCoverArtUrl) { this.frontCoverArtUrl = frontCoverArtUrl; } public String getBackCoverArtUrl() { return backCoverArtUrl; } public void setBackCoverArtUrl(String backCoverArtUrl) { this.backCoverArtUrl = backCoverArtUrl; } public String getUpcCode() { return upcCode; } public void setUpcCode(String upcCode) { this.upcCode = upcCode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((backCoverArtUrl == null) ? 0 : backCoverArtUrl.hashCode()); result = prime * result + ((frontCoverArtUrl == null) ? 0 : frontCoverArtUrl.hashCode()); result = prime * result + ((upcCode == null) ? 0 : upcCode.hashCode()); return result; }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CoverArt other = (CoverArt) obj; if (backCoverArtUrl == null) { if (other.backCoverArtUrl != null) return false; } else if (!backCoverArtUrl.equals(other.backCoverArtUrl)) return false; if (frontCoverArtUrl == null) { if (other.frontCoverArtUrl != null) return false; } else if (!frontCoverArtUrl.equals(other.frontCoverArtUrl)) return false; if (upcCode == null) { if (other.upcCode != null) return false; } else if (!upcCode.equals(other.upcCode)) return false; return true; } }
repos\tutorials-master\persistence-modules\hibernate-libraries\src\main\java\com\baeldung\hibernate\types\CoverArt.java
1
请完成以下Java代码
public String getF_PLATFORM_ID() { return F_PLATFORM_ID; } public void setF_PLATFORM_ID(String f_PLATFORM_ID) { F_PLATFORM_ID = f_PLATFORM_ID; } public String getF_ISENTERPRISES() { return F_ISENTERPRISES; } public void setF_ISENTERPRISES(String f_ISENTERPRISES) { F_ISENTERPRISES = f_ISENTERPRISES; }
public String getF_ISCLEAR() { return F_ISCLEAR; } public void setF_ISCLEAR(String f_ISCLEAR) { F_ISCLEAR = f_ISCLEAR; } public String getF_PARENTID() { return F_PARENTID; } public void setF_PARENTID(String f_PARENTID) { F_PARENTID = f_PARENTID; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollItem.java
1
请完成以下Java代码
public <T> T getDynAttribute(final String attributeName) { return getDocument().getDynAttribute(attributeName); } public Object setDynAttribute(final String attributeName, final Object value) { return getDocument().setDynAttribute(attributeName, value); } public final boolean isOldValues() { return useOldValues; } public static final boolean isOldValues(final Object model) { final DocumentInterfaceWrapper wrapper = getWrapper(model); return wrapper == null ? false : wrapper.isOldValues(); } @Override public Set<String> getColumnNames() { return document.getFieldNames(); } @Override public int getColumnIndex(final String columnName) { throw new UnsupportedOperationException("DocumentInterfaceWrapper has no supported for column indexes"); } @Override public boolean isVirtualColumn(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isReadonlyVirtualField(); } @Override public boolean isKeyColumnName(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isKey(); } @Override public boolean isCalculated(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isCalculated(); } @Override
public boolean setValueNoCheck(final String columnName, final Object value) { return setValue(columnName, value); } @Override public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value) { // TODO: implement throw new UnsupportedOperationException(); } @Override public boolean invokeEquals(final Object[] methodArgs) { // TODO: implement throw new UnsupportedOperationException(); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { // TODO: implement throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentInterfaceWrapper.java
1
请完成以下Java代码
public void validateClassName(@NonNull final I_AD_Process process) { final String classname = process.getClassname(); if (Check.isBlank(classname)) { throw new FillMandatoryException(I_AD_Process.COLUMNNAME_Classname); } final ProcessType processType = ProcessType.ofCode(process.getType()); if (processType.equals(POSTGREST)) { Util.validateJavaClassname(classname, PostgRESTProcessExecutor.class); } else if (processType.equals(Java)) { Util.validateJavaClassname(classname, JavaProcess.class); } // for the other cases, the user can't edit the classname } @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = { I_AD_Process.COLUMNNAME_IsActive, I_AD_Process.COLUMNNAME_Name, I_AD_Process.COLUMNNAME_Description, I_AD_Process.COLUMNNAME_Help }) public void propagateNamesAndTrl(final I_AD_Process adProcess) { final Properties ctx = InterfaceWrapperHelper.getCtx(adProcess); final String trxName = InterfaceWrapperHelper.getTrxName(adProcess); for (final I_AD_Menu menu : MMenu.get(ctx, I_AD_Menu.COLUMNNAME_AD_Process_ID + "=" + adProcess.getAD_Process_ID(), trxName)) { menu.setIsActive(adProcess.isActive()); menu.setName(adProcess.getName()); menu.setDescription(adProcess.getDescription()); InterfaceWrapperHelper.save(menu); } for (final I_AD_WF_Node node : MWindow.getWFNodes(ctx, I_AD_WF_Node.COLUMNNAME_AD_Process_ID + "=" + adProcess.getAD_Process_ID(), trxName))
{ boolean changed = false; if (node.isActive() != adProcess.isActive()) { node.setIsActive(adProcess.isActive()); changed = true; } if (node.isCentrallyMaintained()) { node.setName(adProcess.getName()); node.setDescription(adProcess.getDescription()); node.setHelp(adProcess.getHelp()); changed = true; } // if (changed) { InterfaceWrapperHelper.save(node); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\model\interceptor\AD_Process.java
1
请完成以下Java代码
public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException(); } @Override public boolean contains(Object object) { for (Object element : internal) { if (object.equals(element)) { return true; } } return false; } @Override public boolean containsAll(Collection<?> collection) { for (Object element : collection) if (!contains(element)) { return false; } return true; } @SuppressWarnings("unchecked") @Override public E set(int index, E element) { E oldElement = (E) internal[index]; internal[index] = element; return oldElement; } @Override public void clear() { internal = new Object[0]; } @Override public int indexOf(Object object) { for (int i = 0; i < internal.length; i++) { if (object.equals(internal[i])) { return i; } } return -1; } @Override public int lastIndexOf(Object object) { for (int i = internal.length - 1; i >= 0; i--) { if (object.equals(internal[i])) { return i; } } return -1; } @SuppressWarnings("unchecked") @Override public List<E> subList(int fromIndex, int toIndex) { Object[] temp = new Object[toIndex - fromIndex]; System.arraycopy(internal, fromIndex, temp, 0, temp.length); return (List<E>) Arrays.asList(temp); }
@Override public Object[] toArray() { return Arrays.copyOf(internal, internal.length); } @SuppressWarnings("unchecked") @Override public <T> T[] toArray(T[] array) { if (array.length < internal.length) { return (T[]) Arrays.copyOf(internal, internal.length, array.getClass()); } System.arraycopy(internal, 0, array, 0, internal.length); if (array.length > internal.length) { array[internal.length] = null; } return array; } @Override public Iterator<E> iterator() { return new CustomIterator(); } @Override public ListIterator<E> listIterator() { return null; } @Override public ListIterator<E> listIterator(int index) { // ignored for brevity return null; } private class CustomIterator implements Iterator<E> { int index; @Override public boolean hasNext() { return index != internal.length; } @SuppressWarnings("unchecked") @Override public E next() { E element = (E) CustomList.this.internal[index]; index++; return element; } } }
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\CustomList.java
1
请完成以下Java代码
public static Expression getFieldExpression(DelegateTask task, String fieldName) { if (task.getCurrentActivitiListener() != null) { List<FieldExtension> fieldExtensions = task.getCurrentActivitiListener().getFieldExtensions(); if (fieldExtensions != null && fieldExtensions.size() > 0) { for (FieldExtension fieldExtension : fieldExtensions) { if (fieldName.equals(fieldExtension.getFieldName())) { return createExpressionForField(fieldExtension); } } } } return null; } public static Expression getFlowElementFieldExpression(DelegateExecution execution, String fieldName) {
FieldExtension fieldExtension = getFlowElementField(execution, fieldName); if (fieldExtension != null) { return createExpressionForField(fieldExtension); } return null; } public static Expression getListenerFieldExpression(DelegateExecution execution, String fieldName) { FieldExtension fieldExtension = getListenerField(execution, fieldName); if (fieldExtension != null) { return createExpressionForField(fieldExtension); } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\DelegateHelper.java
1
请完成以下Java代码
class FirewalledResponse extends HttpServletResponseWrapper { private static final String LOCATION_HEADER = "Location"; private static final String SET_COOKIE_HEADER = "Set-Cookie"; FirewalledResponse(HttpServletResponse response) { super(response); } @Override public void sendRedirect(String location) throws IOException { // TODO: implement pluggable validation, instead of simple blocklist. // SEC-1790. Prevent redirects containing CRLF validateCrlf(LOCATION_HEADER, location); super.sendRedirect(location); } @Override public void setHeader(String name, String value) { validateCrlf(name, value); super.setHeader(name, value); } @Override public void addHeader(String name, String value) {
validateCrlf(name, value); super.addHeader(name, value); } @Override public void addCookie(Cookie cookie) { if (cookie != null) { validateCrlf(SET_COOKIE_HEADER, cookie.getName()); validateCrlf(SET_COOKIE_HEADER, cookie.getValue()); validateCrlf(SET_COOKIE_HEADER, cookie.getPath()); validateCrlf(SET_COOKIE_HEADER, cookie.getDomain()); } super.addCookie(cookie); } void validateCrlf(String name, String value) { Assert.isTrue(!hasCrlf(name) && !hasCrlf(value), () -> "Invalid characters (CR/LF) in header " + name); } private boolean hasCrlf(String value) { return value != null && (value.indexOf('\n') != -1 || value.indexOf('\r') != -1); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\FirewalledResponse.java
1
请完成以下Java代码
public int getM_ShipperTransportation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipperTransportation_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_Value (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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-gen\de\metas\shipper\gateway\go\model\X_GO_DeliveryOrder.java
1
请完成以下Java代码
public List<I_M_HU> getAssignedHandlingUnits() { if (assignedHandlingUnits != null) { return assignedHandlingUnits; } final List<I_M_HU> result = new ArrayList<I_M_HU>(); final Set<Integer> seenHuIds = new HashSet<Integer>(); for (final IHUDocumentLine sourceLine : getLines()) { if (sourceLine.getHUAllocations() == null) { continue; // task 07711: avoid NPE } for (final I_M_HU hu : sourceLine.getHUAllocations().getAssignedHUs()) { final int huId = hu.getM_HU_ID(); if (!seenHuIds.add(huId)) { // already added continue; } result.add(hu); } } assignedHandlingUnits = Collections.unmodifiableList(result); return assignedHandlingUnits; }
protected List<IHUDocumentLine> getReversalLines() { final List<IHUDocumentLine> lines = getLines(); final List<IHUDocumentLine> reversalLines = new ArrayList<IHUDocumentLine>(lines.size()); for (final IHUDocumentLine line : lines) { final IHUDocumentLine reversalLine = line.getReversal(); if (reversalLine == null) { continue; } reversalLines.add(reversalLine); } return reversalLines; } @Override public I_M_HU getInnerHandlingUnit() { // this is the default implementation, not an "emtpy method" as the sonar issue thinks return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocument.java
1
请完成以下Java代码
private DocumentPostRequest fromJson(@NonNull final String json) { try { return jsonObjectMapper.readValue(json, DocumentPostRequest.class); } catch (JsonProcessingException e) { throw new AdempiereException("Failed converting from JSON: " + json, e); } } } // // // ------------------------------------------------------------------------- // // @lombok.Builder @lombok.ToString private static final class DocumentPostRequestHandlerAsEventListener implements IEventListener { @NonNull private final DocumentPostRequestHandler handler; @NonNull private final EventConverter eventConverter; @NonNull private final EventLogUserService eventLogUserService; @Override public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event) { final DocumentPostRequest request = eventConverter.extractDocumentPostRequest(event); try (final IAutoCloseable ignored = switchCtx(request); final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(request.getRecord()); final MDCCloseable ignored2 = MDC.putCloseable("eventHandler.className", handler.getClass().getName())) { eventLogUserService.invokeHandlerAndLog(InvokeHandlerAndLogRequest.builder() .handlerClass(handler.getClass()) .invokaction(() -> handleRequest(request)) .build()); }
} private void handleRequest(@NonNull final DocumentPostRequest request) { handler.handleRequest(request); } private IAutoCloseable switchCtx(@NonNull final DocumentPostRequest request) { final Properties ctx = createCtx(request); return Env.switchContext(ctx); } private Properties createCtx(@NonNull final DocumentPostRequest request) { final Properties ctx = Env.newTemporaryCtx(); Env.setClientId(ctx, request.getClientId()); return ctx; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\DocumentPostingBusService.java
1
请完成以下Java代码
public List<EngineDeployer> getDeployers() { return deployers; } public AbstractEngineConfiguration setDeployers(List<EngineDeployer> deployers) { this.deployers = deployers; return this; } public List<EngineDeployer> getCustomPreDeployers() { return customPreDeployers; } public AbstractEngineConfiguration setCustomPreDeployers(List<EngineDeployer> customPreDeployers) { this.customPreDeployers = customPreDeployers; return this; } public List<EngineDeployer> getCustomPostDeployers() { return customPostDeployers; } public AbstractEngineConfiguration setCustomPostDeployers(List<EngineDeployer> customPostDeployers) { this.customPostDeployers = customPostDeployers; return this; } public boolean isEnableConfiguratorServiceLoader() { return enableConfiguratorServiceLoader; } public AbstractEngineConfiguration setEnableConfiguratorServiceLoader(boolean enableConfiguratorServiceLoader) { this.enableConfiguratorServiceLoader = enableConfiguratorServiceLoader; return this; } public List<EngineConfigurator> getConfigurators() { return configurators; } public AbstractEngineConfiguration addConfigurator(EngineConfigurator configurator) { if (configurators == null) { configurators = new ArrayList<>(); } configurators.add(configurator); return this; } /** * @return All {@link EngineConfigurator} instances. Will only contain values after init of the engine. * Use the {@link #getConfigurators()} or {@link #addConfigurator(EngineConfigurator)} methods otherwise. */ public List<EngineConfigurator> getAllConfigurators() { return allConfigurators;
} public AbstractEngineConfiguration setConfigurators(List<EngineConfigurator> configurators) { this.configurators = configurators; return this; } public EngineConfigurator getIdmEngineConfigurator() { return idmEngineConfigurator; } public AbstractEngineConfiguration setIdmEngineConfigurator(EngineConfigurator idmEngineConfigurator) { this.idmEngineConfigurator = idmEngineConfigurator; return this; } public EngineConfigurator getEventRegistryConfigurator() { return eventRegistryConfigurator; } public AbstractEngineConfiguration setEventRegistryConfigurator(EngineConfigurator eventRegistryConfigurator) { this.eventRegistryConfigurator = eventRegistryConfigurator; return this; } public AbstractEngineConfiguration setForceCloseMybatisConnectionPool(boolean forceCloseMybatisConnectionPool) { this.forceCloseMybatisConnectionPool = forceCloseMybatisConnectionPool; return this; } public boolean isForceCloseMybatisConnectionPool() { return forceCloseMybatisConnectionPool; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\AbstractEngineConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.equals(Book.class); } /* Deprecated in JAX RS 2.0 */ @Override public long getSize(Book book, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return 0; } /** * Marsahl Book to OutputStream * * @param book * @param type
* @param genericType * @param annotations * @param mediaType * @param httpHeaders * @param entityStream * @throws IOException * @throws WebApplicationException */ @Override public void writeTo(Book book, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { JsonWriter jsonWriter = Json.createWriter(entityStream); JsonObject jsonObject = BookMapper.map(book); jsonWriter.writeObject(jsonObject); jsonWriter.close(); } }
repos\tutorials-master\microservices-modules\microprofile\src\main\java\com\baeldung\microprofile\providers\BookMessageBodyWriter.java
2
请完成以下Java代码
public class KeepingConversationStateInJava { public static void main(String[] args) { var client = Client.getClient(); List<ChatMessage> history = new ArrayList<>(); history.add(SystemMessage.of( "You are a helpful travel assistant. Answer briefly." )); try (Scanner scanner = new Scanner(System.in)) { while (true) { System.out.print("You: "); String input = scanner.nextLine(); if (input == null || input.isBlank()) { continue; } if ("exit".equalsIgnoreCase(input.trim())) { break; } history.add(UserMessage.of(input));
ChatRequest.ChatRequestBuilder chatRequestBuilder = ChatRequest.builder().model(Client.CHAT_MODEL); for (ChatMessage message : history) { chatRequestBuilder.message(message); } ChatRequest chatRequest = chatRequestBuilder.build(); CompletableFuture<Chat> chatFuture = client.chatCompletions().create(chatRequest); Chat chat = chatFuture.join(); String reply = chat.firstContent().toString(); Client.LOGGER.log(Level.INFO, "Assistant: {0}", reply); history.add(AssistantMessage.of(reply)); } } } }
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\simpleopenai\KeepingConversationStateInJava.java
1
请完成以下Java代码
protected static void createDmnShapeBounds(GraphicInfo graphicInfo, XMLStreamWriter xtw) throws Exception { xtw.writeStartElement(OMGDC_PREFIX, ELEMENT_DI_BOUNDS, OMGDC_NAMESPACE); xtw.writeAttribute(ATTRIBUTE_DI_HEIGHT, String.valueOf(graphicInfo.getHeight())); xtw.writeAttribute(ATTRIBUTE_DI_WIDTH, String.valueOf(graphicInfo.getWidth())); xtw.writeAttribute(ATTRIBUTE_DI_X, String.valueOf(graphicInfo.getX())); xtw.writeAttribute(ATTRIBUTE_DI_Y, String.valueOf(graphicInfo.getY())); xtw.writeEndElement(); } protected static void createDmnDecisionServiceDividerLine(List<GraphicInfo> graphicInfoList, XMLStreamWriter xtw) throws Exception { xtw.writeStartElement(DMNDI_PREFIX, ELEMENT_DI_DECISION_SERVICE_DIVIDER_LINE, DMNDI_NAMESPACE); for (GraphicInfo graphicInfo : graphicInfoList) { xtw.writeStartElement(OMGDI_PREFIX, ELEMENT_DI_WAYPOINT, OMGDI_NAMESPACE); xtw.writeAttribute(ATTRIBUTE_DI_X, String.valueOf(graphicInfo.getX())); xtw.writeAttribute(ATTRIBUTE_DI_Y, String.valueOf(graphicInfo.getY())); xtw.writeEndElement(); }
xtw.writeEndElement(); } protected static void createDmnEdge(String elementId, List<GraphicInfo> graphicInfoList, XMLStreamWriter xtw) throws Exception { xtw.writeStartElement(DMNDI_PREFIX, ELEMENT_DI_EDGE, DMNDI_NAMESPACE); xtw.writeAttribute(ATTRIBUTE_ID, "DMNEdge_" + elementId); xtw.writeAttribute(ATTRIBUTE_DI_DMN_ELEMENT_REF, elementId); for (GraphicInfo graphicInfo : graphicInfoList) { xtw.writeStartElement(OMGDI_PREFIX, ELEMENT_DI_WAYPOINT, OMGDI_NAMESPACE); xtw.writeAttribute(ATTRIBUTE_DI_X, String.valueOf(graphicInfo.getX())); xtw.writeAttribute(ATTRIBUTE_DI_Y, String.valueOf(graphicInfo.getY())); xtw.writeEndElement(); } xtw.writeEndElement(); } }
repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\xml\converter\DMNDIExport.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; private final BookRepository bookRepository; public BookstoreService(AuthorRepository authorRepository, BookRepository bookRepository) { this.authorRepository = authorRepository; this.bookRepository = bookRepository; } public Page<Author> fetchWithBooksByGenreCQ() { return authorRepository.fetchWithBooksByGenreCQ("Anthology", PageRequest.of(0, 2, new Sort(Sort.Direction.ASC, "name"))); } public Page<Author> fetchWithBooksByGenreEG() { return authorRepository.fetchWithBooksByGenreEG("Anthology",
PageRequest.of(0, 2, new Sort(Sort.Direction.ASC, "name"))); } public Page<Book> fetchWithAuthorsByIsbnCQ() { return bookRepository.fetchWithAuthorsByIsbnCQ("001-", PageRequest.of(0, 2, new Sort(Sort.Direction.ASC, "title"))); } public Page<Book> fetchWithAuthorsByIsbnEG() { return bookRepository.fetchWithAuthorsByIsbnEG("001-", PageRequest.of(0, 2, new Sort(Sort.Direction.ASC, "title"))); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinFetchPageable\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
private Mono<Boolean> containsValidCsrfToken(ServerWebExchange exchange, CsrfToken expected) { return this.requestHandler.resolveCsrfTokenValue(exchange, expected) .map((actual) -> equalsConstantTime(actual, expected.getToken())); } private Mono<Void> continueFilterChain(ServerWebExchange exchange, WebFilterChain chain) { return Mono.defer(() -> { Mono<CsrfToken> csrfToken = csrfToken(exchange); this.requestHandler.handle(exchange, csrfToken); return chain.filter(exchange); }); } private Mono<CsrfToken> csrfToken(ServerWebExchange exchange) { return this.csrfTokenRepository.loadToken(exchange).switchIfEmpty(generateToken(exchange)); } /** * Constant time comparison to prevent against timing attacks. * @param expected * @param actual * @return */ private static boolean equalsConstantTime(String expected, String actual) { if (expected == actual) { return true; } if (expected == null || actual == null) { return false; } // Encode after ensure that the string is not null byte[] expectedBytes = Utf8.encode(expected); byte[] actualBytes = Utf8.encode(actual); return MessageDigest.isEqual(expectedBytes, actualBytes);
} private Mono<CsrfToken> generateToken(ServerWebExchange exchange) { return this.csrfTokenRepository.generateToken(exchange) .delayUntil((token) -> this.csrfTokenRepository.saveToken(exchange, token)) .cache(); } private static class DefaultRequireCsrfProtectionMatcher implements ServerWebExchangeMatcher { private static final Set<HttpMethod> ALLOWED_METHODS = new HashSet<>( Arrays.asList(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.TRACE, HttpMethod.OPTIONS)); @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { return Mono.just(exchange.getRequest()) .flatMap((r) -> Mono.justOrEmpty(r.getMethod())) .filter(ALLOWED_METHODS::contains) .flatMap((m) -> MatchResult.notMatch()) .switchIfEmpty(MatchResult.match()); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\CsrfWebFilter.java
1
请完成以下Java代码
public static HttpServletResponse getHttpServletResponse() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); } /** * 获取项目根路径 basePath */ public static String getDomain(){ HttpServletRequest request = getHttpServletRequest(); StringBuffer url = request.getRequestURL(); //1.微服务情况下,获取gateway的basePath String basePath = request.getHeader(ServiceNameConstants.X_GATEWAY_BASE_PATH); if(oConvertUtils.isNotEmpty(basePath)){ return basePath; }else{ String domain = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString(); //2.【兼容】SSL认证之后,request.getScheme()获取不到https的问题 // https://blog.csdn.net/weixin_34376986/article/details/89767950 String scheme = request.getHeader(CommonConstant.X_FORWARDED_SCHEME); if(scheme!=null && !request.getScheme().equals(scheme)){ domain = domain.replace(request.getScheme(),scheme); } return domain; } } public static String getOrigin(){ HttpServletRequest request = getHttpServletRequest(); return request.getHeader("Origin"); } /** * 通过name获取 Bean. * * @param name * @return */ public static Object getBean(String name) { return getApplicationContext().getBean(name); } /** * 通过class获取Bean. *
* @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } /** * 通过name,以及Clazz返回指定的Bean * * @param name * @param clazz * @param <T> * @return */ public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\SpringContextUtils.java
1
请完成以下Java代码
public boolean handleOne(Exception thrownException, ConsumerRecord<?, ?> record, Consumer<?, ?> consumer, MessageListenerContainer container) { try { return getFailureTracker().recovered(record, thrownException, container, consumer); } catch (Exception ex) { if (SeekUtils.isBackoffException(thrownException)) { this.logger.debug(ex, "Failed to handle " + KafkaUtils.format(record) + " with " + thrownException); } else { this.logger.error(ex, "Failed to handle " + KafkaUtils.format(record) + " with " + thrownException); } return false; } } @Override public void handleRemaining(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer, MessageListenerContainer container) { SeekUtils.seekOrRecover(thrownException, records, consumer, container, isCommitRecovered(), // NOSONAR getFailureTracker(), this.logger, getLogLevel()); } @Override public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { doHandle(thrownException, data, consumer, container, invokeListener); } @Override public <K, V> ConsumerRecords<K, V> handleBatchAndReturnRemaining(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container,
Runnable invokeListener) { return handle(thrownException, data, consumer, container, invokeListener); } @Override public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer, MessageListenerContainer container, boolean batchListener) { if (thrownException instanceof SerializationException) { throw new IllegalStateException("This error handler cannot process 'SerializationException's directly; " + "please consider configuring an 'ErrorHandlingDeserializer' in the value and/or key " + "deserializer", thrownException); } else { throw new IllegalStateException("This error handler cannot process '" + thrownException.getClass().getName() + "'s; no record information is available", thrownException); } } @Override public void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions, Runnable publishPause) { getFallbackBatchHandler().onPartitionsAssigned(consumer, partitions, publishPause); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\DefaultErrorHandler.java
1
请完成以下Java代码
public void setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler) { Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null"); this.accessDeniedHandler = accessDeniedHandler; } /** * Specifies a {@link CsrfTokenRequestHandler} that is used to make the * {@link CsrfToken} available as a request attribute. * * <p> * The default is {@link XorCsrfTokenRequestAttributeHandler}. * </p> * @param requestHandler the {@link CsrfTokenRequestHandler} to use * @since 5.8 */ public void setRequestHandler(CsrfTokenRequestHandler requestHandler) { Assert.notNull(requestHandler, "requestHandler cannot be null"); this.requestHandler = requestHandler; } /** * Constant time comparison to prevent against timing attacks. * @param expected * @param actual * @return */ private static boolean equalsConstantTime(String expected, @Nullable String actual) { if (expected == actual) { return true; } if (expected == null || actual == null) { return false; } // Encode after ensure that the string is not null byte[] expectedBytes = Utf8.encode(expected); byte[] actualBytes = Utf8.encode(actual); return MessageDigest.isEqual(expectedBytes, actualBytes);
} private static final class DefaultRequiresCsrfMatcher implements RequestMatcher { private final HashSet<String> allowedMethods = new HashSet<>(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS")); @Override public boolean matches(HttpServletRequest request) { return !this.allowedMethods.contains(request.getMethod()); } @Override public String toString() { return "IsNotHttpMethod " + this.allowedMethods; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CsrfFilter.java
1
请完成以下Java代码
private Function<Health.Builder, Health.Builder> withResourceManagerDetails() { return healthBuilder -> getGemFireCache() .map(GemFireCache::getResourceManager) .map(resourceManager -> healthBuilder .withDetail("geode.resource-manager.critical-heap-percentage", resourceManager.getCriticalHeapPercentage()) .withDetail("geode.resource-manager.critical-off-heap-percentage", resourceManager.getCriticalOffHeapPercentage()) .withDetail("geode.resource-manager.eviction-heap-percentage", resourceManager.getEvictionHeapPercentage()) .withDetail("geode.resource-manager.eviction-off-heap-percentage", resourceManager.getEvictionOffHeapPercentage()) ) .orElse(healthBuilder); } private String emptyIfUnset(String value) { return StringUtils.hasText(value) ? value : ""; }
private String toConnectedNoConnectedString(Boolean connected) { return Boolean.TRUE.equals(connected) ? "Connected" : "Not Connected"; } private int toMemberCount(DistributedSystem distributedSystem) { return CollectionUtils.nullSafeSize(distributedSystem.getAllOtherMembers()) + 1; } private String toString(URL url) { String urlString = url != null ? url.toExternalForm() : null; return emptyIfUnset(urlString); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\GeodeCacheHealthIndicator.java
1
请在Spring Boot框架中完成以下Java代码
protected void validateUpdate(OtaPackageInfo otaPackage, OtaPackageInfo otaPackageOld) { if (!otaPackageOld.getType().equals(otaPackage.getType())) { throw new DataValidationException("Updating type is prohibited!"); } if (!otaPackageOld.getTitle().equals(otaPackage.getTitle())) { throw new DataValidationException("Updating otaPackage title is prohibited!"); } if (!otaPackageOld.getVersion().equals(otaPackage.getVersion())) { throw new DataValidationException("Updating otaPackage version is prohibited!"); } if (!Objects.equals(otaPackage.getTag(), otaPackageOld.getTag())) { throw new DataValidationException("Updating otaPackage tag is prohibited!"); } if (!otaPackageOld.getDeviceProfileId().equals(otaPackage.getDeviceProfileId())) { throw new DataValidationException("Updating otaPackage deviceProfile is prohibited!"); } if (otaPackageOld.getFileName() != null && !otaPackageOld.getFileName().equals(otaPackage.getFileName())) { throw new DataValidationException("Updating otaPackage file name is prohibited!"); } if (otaPackageOld.getContentType() != null && !otaPackageOld.getContentType().equals(otaPackage.getContentType())) { throw new DataValidationException("Updating otaPackage content type is prohibited!"); }
if (otaPackageOld.getChecksumAlgorithm() != null && !otaPackageOld.getChecksumAlgorithm().equals(otaPackage.getChecksumAlgorithm())) { throw new DataValidationException("Updating otaPackage content type is prohibited!"); } if (otaPackageOld.getChecksum() != null && !otaPackageOld.getChecksum().equals(otaPackage.getChecksum())) { throw new DataValidationException("Updating otaPackage content type is prohibited!"); } if (otaPackageOld.getDataSize() != null && !otaPackageOld.getDataSize().equals(otaPackage.getDataSize())) { throw new DataValidationException("Updating otaPackage data size is prohibited!"); } if (otaPackageOld.getUrl() != null && !otaPackageOld.getUrl().equals(otaPackage.getUrl())) { throw new DataValidationException("Updating otaPackage URL is prohibited!"); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\BaseOtaPackageDataValidator.java
2
请完成以下Java代码
protected String doIt() throws Exception { final Iterator<I_M_ReceiptSchedule> schedules = getReceiptSchedules(); if (!schedules.hasNext()) { throw new AdempiereException("@" + MSG_NO_RECEIPT_SCHEDULES_SELECTED + "@"); } final InOutGenerateResult result = Services.get(IInOutCandidateBL.class).createEmptyInOutGenerateResult(false); // storeReceipts=false final IInOutProducer producer = receiptScheduleBL.createInOutProducer(result, p_IsComplete); receiptScheduleBL.generateInOuts(getCtx(), producer, schedules); return "@Created@ @M_InOut_ID@: #" + result.getInOutCount(); } private Iterator<I_M_ReceiptSchedule> getReceiptSchedules() {
final ProcessInfo processInfo = getProcessInfo(); final IQueryBuilder<I_M_ReceiptSchedule> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_M_ReceiptSchedule.class, processInfo); // // Only not processed lines queryBuilder.addEqualsFilter(I_M_ReceiptSchedule.COLUMNNAME_Processed, false); // // From user selection queryBuilder.filter(new ProcessInfoSelectionQueryFilter<I_M_ReceiptSchedule>(processInfo)); final IQuery<I_M_ReceiptSchedule> query = queryBuilder.create() .setClient_ID() .setOnlyActiveRecords(true) .setRequiredAccess(Access.WRITE); return Services.get(IReceiptScheduleDAO.class).retrieve(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ReceiptSchedule_GenerateInOutFromSelection.java
1
请完成以下Java代码
protected Void execute(CommandContext commandContext, TaskEntity task) { CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); if (userId != null) { Clock clock = cmmnEngineConfiguration.getClock(); task.setClaimTime(clock.getCurrentTime()); task.setClaimedBy(userId); task.setState(Task.CLAIMED); if (task.getAssignee() != null) { if (!task.getAssignee().equals(userId)) { // When the task is already claimed by another user, throw // exception. Otherwise, ignore this, post-conditions of method already met. throw new FlowableTaskAlreadyClaimedException(task.getId(), task.getAssignee()); } cmmnEngineConfiguration.getCmmnHistoryManager().recordTaskInfoChange(task, clock.getCurrentTime()); } else { TaskHelper.changeTaskAssignee(task, userId, cmmnEngineConfiguration); if (cmmnEngineConfiguration.getHumanTaskStateInterceptor() != null) { cmmnEngineConfiguration.getHumanTaskStateInterceptor().handleClaim(task, userId); } } } else { if (task.getAssignee() != null) { // Task claim time should be null task.setClaimTime(null); task.setClaimedBy(null); if (task.getInProgressStartTime() != null) {
task.setState(Task.IN_PROGRESS); } else { task.setState(Task.CREATED); } // Task should be assigned to no one TaskHelper.changeTaskAssignee(task, null, cmmnEngineConfiguration); if (cmmnEngineConfiguration.getHumanTaskStateInterceptor() != null) { cmmnEngineConfiguration.getHumanTaskStateInterceptor().handleUnclaim(task, userId); } } } return null; } @Override protected String getSuspendedTaskExceptionPrefix() { return "Cannot claim"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\ClaimTaskCmd.java
1
请在Spring Boot框架中完成以下Java代码
public Quantity allocateQty(@NonNull final ProductId productId, @NonNull final Quantity qtyToDeliver) { return getByProductId(productId) .allocateQty(qtyToDeliver) .toZeroIfNegative(); } private ProductAvailableStock getByProductId(final ProductId productId) { return CollectionUtils.getOrLoad(map, productId, this::loadByProductIds); } public void warmUpByProductIds(final Set<ProductId> productIds) { CollectionUtils.getAllOrLoad(map, productIds, this::loadByProductIds); } private Map<ProductId, ProductAvailableStock> loadByProductIds(final Set<ProductId> productIds) { final HashMap<ProductId, ProductAvailableStock> result = new HashMap<>(); productIds.forEach(productId -> result.put(productId, new ProductAvailableStock())); streamHUProductStorages(productIds) .forEach(huStorageProduct -> result.get(huStorageProduct.getProductId()).addQtyOnHand(huStorageProduct.getQty()));
return result; } private Stream<IHUProductStorage> streamHUProductStorages(final Set<ProductId> productIds) { final List<I_M_HU> hus = handlingUnitsBL.createHUQueryBuilder() .onlyContextClient(false) // fails when running from non-context threads like websockets value producers .addOnlyWithProductIds(productIds) .addOnlyInLocatorIds(pickFromLocatorIds) .setOnlyActiveHUs(true) .list(); final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); return storageFactory.streamHUProductStorages(hus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\hu\ProductAvailableStocks.java
2
请完成以下Java代码
public void captureAmount(@NonNull final PaymentReservationCaptureRequest request) { final PaymentReservation reservation = getBySalesOrderIdNotVoided(request.getSalesOrderId()) .orElse(null); if (reservation == null) { return; } // eagerly fetching the processor to fail fast final PaymentProcessor paymentProcessor = getPaymentProcessor(reservation.getPaymentRule()); final PaymentId paymentId = createPayment(request); final PaymentReservationCapture capture = PaymentReservationCapture.builder() .reservationId(reservation.getId()) .status(PaymentReservationCaptureStatus.NEW) // .orgId(reservation.getOrgId()) .salesOrderId(reservation.getSalesOrderId()) .salesInvoiceId(request.getSalesInvoiceId()) .paymentId(paymentId) // .amount(request.getAmount()) // .build(); capturesRepo.save(capture); paymentProcessor.processCapture(reservation, capture); reservationsRepo.save(reservation); capture.setStatusAsCompleted();
capturesRepo.save(capture); } private PaymentId createPayment(@NonNull final PaymentReservationCaptureRequest request) { final I_C_Payment payment = Services.get(IPaymentBL.class).newInboundReceiptBuilder() .invoiceId(request.getSalesInvoiceId()) .bpartnerId(request.getCustomerId()) .payAmt(request.getAmount().toBigDecimal()) .currencyId(request.getAmount().getCurrencyId()) .tenderType(TenderType.DirectDeposit) .dateTrx(request.getDateTrx()) .createAndProcess(); return PaymentId.ofRepoId(payment.getC_Payment_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\reservation\PaymentReservationService.java
1
请完成以下Java代码
public byte[] combineArraysUsingByteBuffer(byte[] first, byte[] second, byte[] third) { byte[] combined = new byte[first.length + second.length + third.length]; ByteBuffer buffer = ByteBuffer.wrap(combined); buffer.put(first); buffer.put(second); buffer.put(third); return buffer.array(); } public byte[] combineArraysUsingCustomMethod(byte[] first, byte[] second) { byte[] combined = new byte[first.length + second.length]; for (int i = 0; i < combined.length; ++i) { combined[i] = i < first.length ? first[i] : second[i - first.length]; } return combined;
} public byte[] combineArraysUsingGuava(byte[] first, byte[] second, byte[] third) { byte[] combined = Bytes.concat(first, second, third); return combined; } public byte[] combineArraysUsingApacheCommons(byte[] first, byte[] second) { byte[] combined = ArrayUtils.addAll(first, second); return combined; } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\arrayconcat\CombiningByteArrays.java
1