instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class PP_Order_AddSourceHU extends JavaProcess implements IProcessPrecondition
{
private final PPOrderSourceHUService ppOrderSourceHUService = SpringContextHolder.instance.getBean(PPOrderSourceHUService.class);
@Param(parameterName = "M_HU_ID", mandatory = true)
private HuId huId;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal();
}
final PPOrderId ppOrderId = PPOrderId.ofRepoId(context.getSingleSelectedRecordId());
final BooleanWithReason ppOrderEligible = ppOrderSourceHUService.checkEligibleToAddToManufacturingOrder(ppOrderId);
if (ppOrderEligible.isFalse())
|
{
return ProcessPreconditionsResolution.rejectWithInternalReason(ppOrderEligible.getReason());
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final PPOrderId ppOrderId = PPOrderId.ofRepoId(getRecord_ID());
ppOrderSourceHUService.addSourceHU(ppOrderId, huId);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\source_hu\process\PP_Order_AddSourceHU.java
| 1
|
请完成以下Java代码
|
public abstract class HUAssignmentListenerAdapter implements IHUAssignmentListener
{
/**
* Does nothing.
*/
@Override
public void assertAssignable(final I_M_HU hu, final Object model, final String trxName) throws HUNotAssignableException
{
// nothing
}
/**
* Does nothing.
*/
|
@Override
public void onHUAssigned(final I_M_HU hu, final Object model, final String trxName)
{
// nothing
}
/**
* Does nothing.
*/
@Override
public void onHUUnassigned(final IReference<I_M_HU> huRef, final IReference<Object> modelRef, final String trxName)
{
// nothing
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUAssignmentListenerAdapter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected Function<ClientResponse, Mono<Endpoints>> convert(Instance instance, String managementUrl) {
return (response) -> {
if (!response.statusCode().is2xxSuccessful()) {
log.debug("Querying actuator-index for instance {} on '{}' failed with status {}.", instance.getId(),
managementUrl, response.statusCode().value());
return response.releaseBody().then(Mono.empty());
}
if (response.headers().contentType().filter(this.apiMediaTypeHandler::isApiMediaType).isEmpty()) {
log.debug("Querying actuator-index for instance {} on '{}' failed with incompatible Content-Type '{}'.",
instance.getId(), managementUrl,
response.headers().contentType().map(Objects::toString).orElse("(missing)"));
return response.releaseBody().then(Mono.empty());
}
log.debug("Querying actuator-index for instance {} on '{}' successful.", instance.getId(), managementUrl);
return response.bodyToMono(Response.class)
.flatMap(this::convertResponse)
.map(this.alignWithManagementUrl(instance.getId(), managementUrl));
};
}
protected Function<Endpoints, Endpoints> alignWithManagementUrl(InstanceId instanceId, String managementUrl) {
return (endpoints) -> {
if (!managementUrl.startsWith("https:")) {
return endpoints;
}
if (endpoints.stream().noneMatch((e) -> e.getUrl().startsWith("http:"))) {
return endpoints;
}
log.warn(
"Endpoints for instance {} queried from {} are falsely using http. Rewritten to https. Consider configuring this instance to use 'server.forward-headers-strategy=native'.",
instanceId, managementUrl);
return Endpoints.of(endpoints.stream()
.map((e) -> Endpoint.of(e.getId(), e.getUrl().replaceFirst("http:", "https:")))
.toList());
};
}
protected Mono<Endpoints> convertResponse(Response response) {
|
List<Endpoint> endpoints = response.getLinks()
.entrySet()
.stream()
.filter((e) -> !e.getKey().equals("self") && !e.getValue().isTemplated())
.map((e) -> Endpoint.of(e.getKey(), e.getValue().getHref()))
.toList();
return endpoints.isEmpty() ? Mono.empty() : Mono.just(Endpoints.of(endpoints));
}
@Data
protected static class Response {
@JsonProperty("_links")
private Map<String, EndpointRef> links = new HashMap<>();
@Data
protected static class EndpointRef {
private final String href;
private final boolean templated;
@JsonCreator
EndpointRef(@JsonProperty("href") String href, @JsonProperty("templated") boolean templated) {
this.href = href;
this.templated = templated;
}
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\endpoints\QueryIndexEndpointStrategy.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public OptionalBoolean getManualPriceEnabled()
{
return manualPriceEnabled;
}
@Override
public IEditablePricingContext setManualPriceEnabled(final boolean manualPriceEnabled)
{
this.manualPriceEnabled = OptionalBoolean.ofBoolean(manualPriceEnabled);
return this;
}
@Override
@Nullable
public CountryId getCountryId()
{
return countryId;
}
@Override
public IEditablePricingContext setCountryId(@Nullable final CountryId countryId)
{
this.countryId = countryId;
return this;
}
@Override
public boolean isFailIfNotCalculated()
{
return failIfNotCalculated;
}
@Override
public IEditablePricingContext setFailIfNotCalculated()
{
this.failIfNotCalculated = true;
return this;
}
@Override
public IEditablePricingContext setSkipCheckingPriceListSOTrxFlag(final boolean skipCheckingPriceListSOTrxFlag)
{
this.skipCheckingPriceListSOTrxFlag = skipCheckingPriceListSOTrxFlag;
return this;
}
@Nullable
public BigDecimal getManualPrice()
{
return manualPrice;
}
@Override
public IEditablePricingContext setManualPrice(@Nullable final BigDecimal manualPrice)
{
this.manualPrice = manualPrice;
return this;
}
@Override
public boolean isSkipCheckingPriceListSOTrxFlag()
{
return skipCheckingPriceListSOTrxFlag;
}
/** If set to not-{@code null}, then the {@link de.metas.pricing.rules.Discount} rule with go with this break as opposed to look for the currently matching break. */
@Override
public IEditablePricingContext setForcePricingConditionsBreak(@Nullable final PricingConditionsBreak forcePricingConditionsBreak)
{
this.forcePricingConditionsBreak = forcePricingConditionsBreak;
return this;
}
|
@Override
public Optional<IAttributeSetInstanceAware> getAttributeSetInstanceAware()
{
final Object referencedObj = getReferencedObject();
if (referencedObj == null)
{
return Optional.empty();
}
final IAttributeSetInstanceAwareFactoryService attributeSetInstanceAwareFactoryService = Services.get(IAttributeSetInstanceAwareFactoryService.class);
final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(referencedObj);
return Optional.ofNullable(asiAware);
}
@Override
public Quantity getQuantity()
{
final BigDecimal ctxQty = getQty();
if (ctxQty == null)
{
return null;
}
final UomId ctxUomId = getUomId();
if (ctxUomId == null)
{
return null;
}
return Quantitys.of(ctxQty, ctxUomId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingContext.java
| 2
|
请完成以下Java代码
|
public ProductId getProductId()
{
return getProduct().getProductId();
}
public PricingConditionsBreak getPricingConditionsBreakOrNull(final Quantity qtyToDeliver)
{
final PricingConditionsBreakQuery query = createPricingConditionsBreakQuery(qtyToDeliver);
return getPricingConditions().pickApplyingBreak(query);
}
public VendorProductInfo assertThatAttributeSetInstanceIdCompatibleWith(@NonNull final AttributeSetInstanceId otherId)
{
if (AttributeSetInstanceId.NONE.equals(attributeSetInstanceId))
{
return this;
|
}
Check.errorUnless(Objects.equals(otherId, attributeSetInstanceId),
"The given atributeSetInstanceId is not compatible with our id; otherId={}; this={}", otherId, this);
return this;
}
private PricingConditionsBreakQuery createPricingConditionsBreakQuery(final Quantity qtyToDeliver)
{
return PricingConditionsBreakQuery.builder()
.product(getProduct())
// .attributeInstances(attributeInstances)// TODO
.qty(qtyToDeliver.toBigDecimal())
.price(BigDecimal.ZERO) // N/A
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\VendorProductInfo.java
| 1
|
请完成以下Java代码
|
public static String getLocalIpAddressSocket() {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress("google.com", 80));
return socket.getLocalAddress()
.getHostAddress();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String getPublicIpAddressAws() {
try {
String urlString = "http://checkip.amazonaws.com/";
URL url = new URI(urlString).toURL();
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
return br.readLine();
}
} catch (IOException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
public static String getLocalIpAddress() {
try {
return Inet4Address.getLocalHost()
.getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public static List<String> getAllLocalIpAddressUsingNetworkInterface() {
List<String> ipAddress = new ArrayList<>();
Enumeration<NetworkInterface> networkInterfaceEnumeration = null;
try {
networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
|
throw new RuntimeException(e);
}
for (; networkInterfaceEnumeration.hasMoreElements(); ) {
NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();
try {
if (!networkInterface.isUp() || networkInterface.isLoopback()) {
continue;
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
Enumeration<InetAddress> address = networkInterface.getInetAddresses();
for (; address.hasMoreElements(); ) {
InetAddress addr = address.nextElement();
ipAddress.add(addr.getHostAddress());
}
}
return ipAddress;
}
}
|
repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\iplookup\IPAddressLookup.java
| 1
|
请完成以下Java代码
|
public CalloutStatisticsEntry setStatusSkipped(final String skipReasonSummary, final String skipReasonDetails)
{
if (status != Status.Unknown)
{
logger.warn("Callout statistics internal bug: changing status from {} to {} for {}", status, Status.Skipped, this);
}
status = Status.Skipped;
this.skipReasonSummary = skipReasonSummary;
this.skipReasonDetails = skipReasonDetails;
_nodeSummary = null; // reset
return this;
}
public CalloutStatisticsEntry setStatusFailed(final Throwable exception)
{
duration = duration == null ? null : duration.stop();
this.exception = exception;
status = Status.Failed;
_nodeSummary = null; // reset
return this;
}
public CalloutStatisticsEntry getCreateChild(final ICalloutField field, final ICalloutInstance callout)
{
final ArrayKey key = Util.mkKey(field.getColumnName(), callout);
return children.computeIfAbsent(key, (theKey) -> new CalloutStatisticsEntry(indexSupplier, field, callout));
}
public CalloutStatisticsEntry childSkipped(final String columnName, final String reason)
{
logger.trace("Skip executing all callouts for {} because {}", columnName, reason);
countChildFieldsSkipped++;
return this;
}
public CalloutStatisticsEntry childSkipped(final ICalloutField field, final String reason)
{
logger.trace("Skip executing all callouts for {} because {}", field, reason);
countChildFieldsSkipped++;
|
return this;
}
public CalloutStatisticsEntry childSkipped(final ICalloutField field, final ICalloutInstance callout, final String reasonSummary)
{
final String reasonDetails = null;
return childSkipped(field, callout, reasonSummary, reasonDetails);
}
public CalloutStatisticsEntry childSkipped(final ICalloutField field, final ICalloutInstance callout, final String reasonSummary, final String reasonDetails)
{
logger.trace("Skip executing callout {} for field {} because {} ({})", callout, field, reasonSummary, reasonDetails);
getCreateChild(field, callout).setStatusSkipped(reasonSummary, reasonDetails);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\CalloutExecutor.java
| 1
|
请完成以下Java代码
|
public static String convertXmlDocumentToString(DomDocument document) {
StringWriter stringWriter = new StringWriter();
StreamResult result = new StreamResult(stringWriter);
transformDocumentToXml(document, result);
return stringWriter.toString();
}
/**
* Writes a {@link DomDocument} to an {@link OutputStream} by transforming the DOM to XML.
*
* @param document the DOM document to write
* @param outputStream the {@link OutputStream} to write to
*/
public static void writeDocumentToOutputStream(DomDocument document, OutputStream outputStream) {
StreamResult result = new StreamResult(outputStream);
transformDocumentToXml(document, result);
}
/**
* Transforms a {@link DomDocument} to XML output.
*
* @param document the DOM document to transform
* @param result the {@link StreamResult} to write to
*/
public static void transformDocumentToXml(DomDocument document, StreamResult result) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try {
|
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
synchronized(document) {
transformer.transform(document.getDomSource(), result);
}
} catch (TransformerConfigurationException e) {
throw new ModelIoException("Unable to create a transformer for the model", e);
} catch (TransformerException e) {
throw new ModelIoException("Unable to transform model to xml", e);
}
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\IoUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DmnDeployer implements EngineDeployer {
private static final Logger LOGGER = LoggerFactory.getLogger(DmnDeployer.class);
@Override
public void deploy(EngineDeployment deployment, Map<String, Object> deploymentSettings) {
if (!deployment.isNew()) {
return;
}
LOGGER.debug("DmnDeployer: processing deployment {}", deployment.getName());
DmnDeploymentBuilder dmnDeploymentBuilder = null;
Map<String, EngineResource> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
if (DmnResourceUtil.isDmnResource(resourceName)) {
LOGGER.info("DmnDeployer: processing resource {}", resourceName);
if (dmnDeploymentBuilder == null) {
DmnRepositoryService dmnRepositoryService = CommandContextUtil.getDmnRepositoryService();
dmnDeploymentBuilder = dmnRepositoryService.createDeployment().name(deployment.getName());
}
dmnDeploymentBuilder.addDmnBytes(resourceName, resources.get(resourceName).getBytes());
}
}
if (dmnDeploymentBuilder != null) {
dmnDeploymentBuilder.parentDeploymentId(deployment.getId());
if (deployment.getTenantId() != null && deployment.getTenantId().length() > 0) {
|
dmnDeploymentBuilder.tenantId(deployment.getTenantId());
}
dmnDeploymentBuilder.deploy();
}
}
@Override
public void undeploy(EngineDeployment parentDeployment, boolean cascade) {
DmnRepositoryService repositoryService = CommandContextUtil.getDmnRepositoryService();
List<DmnDeployment> deployments = repositoryService
.createDeploymentQuery()
.parentDeploymentId(parentDeployment.getId())
.list();
for (DmnDeployment deployment : deployments) {
repositoryService.deleteDeployment(deployment.getId());
}
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine-configurator\src\main\java\org\flowable\dmn\engine\deployer\DmnDeployer.java
| 2
|
请完成以下Java代码
|
public void onSuccess(R request, T response) {
processRemove.run();
callback.onSuccess(request, response);
}
@Override
public void onValidationError(String params, String msg) {
processRemove.run();
callback.onValidationError(params, msg);
}
@Override
public void onError(String params, Exception e) {
try {
if (e instanceof TimeoutException) {
return;
}
processRemove.run();
} finally {
callback.onError(params, e);
}
}
};
}
|
@Override
public void persistUpdates(String endpoint) {
LwM2MModelConfig modelConfig = currentModelConfigs.get(endpoint);
if (modelConfig != null && !modelConfig.isEmpty()) {
modelStore.put(modelConfig);
}
}
@Override
public void removeUpdates(String endpoint) {
currentModelConfigs.remove(endpoint);
modelStore.remove(endpoint);
}
@PreDestroy
private void destroy() {
currentModelConfigs.values().forEach(model -> {
if (model != null && !model.isEmpty()) {
modelStore.put(model);
}
});
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\model\LwM2MModelConfigServiceImpl.java
| 1
|
请完成以下Java代码
|
public void setHR_Contract_ID (int HR_Contract_ID)
{
if (HR_Contract_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_Contract_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_Contract_ID, Integer.valueOf(HR_Contract_ID));
}
/** Get Payroll Contract.
@return Payroll Contract */
public int getHR_Contract_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Contract_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Net Days.
@param NetDays
Net Days in which payment is due
*/
public void setNetDays (int NetDays)
{
set_Value (COLUMNNAME_NetDays, Integer.valueOf(NetDays));
}
/** Get Net Days.
@return Net Days in which payment is due
*/
public int getNetDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NetDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
|
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Contract.java
| 1
|
请完成以下Java代码
|
public class PrintPackageCtx implements IPrintPackageCtx
{
private String hostKey = null;
private String transactionId = null;
PrintPackageCtx()
{
// nothing
}
@Override
public String getHostKey()
{
return hostKey;
}
public void setHostKey(final String hostKey)
{
this.hostKey = hostKey;
}
|
@Override
public String getTransactionId()
{
return transactionId;
}
@Override
public void setTransactionId(final String transactionId)
{
this.transactionId = transactionId;
}
@Override
public String toString()
{
return "PrintPackageCtx [hostKey=" + hostKey + ", transactionId=" + transactionId + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintPackageCtx.java
| 1
|
请完成以下Java代码
|
public class Customer {
private String firstName;
private String lastName;
private Date dob;
private List<ContactDetails> contactDetailsList;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
|
this.dob = dob;
}
public List<ContactDetails> getContactDetailsList() {
return contactDetailsList;
}
public void setContactDetailsList(List<ContactDetails> contactDetailsList) {
this.contactDetailsList = contactDetailsList;
}
@Override
public String toString() {
return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + ", contactDetailsList=" + contactDetailsList + "]";
}
}
|
repos\tutorials-master\xml-modules\xstream\src\main\java\com\baeldung\complex\pojo\Customer.java
| 1
|
请完成以下Java代码
|
public void exportServerDeploy(HttpServletResponse response, ServerDeployQueryCriteria criteria) throws IOException {
serverDeployService.download(serverDeployService.queryAll(criteria), response);
}
@ApiOperation(value = "查询服务器")
@GetMapping
@PreAuthorize("@el.check('serverDeploy:list')")
public ResponseEntity<PageResult<ServerDeployDto>> queryServerDeploy(ServerDeployQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(serverDeployService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("新增服务器")
@ApiOperation(value = "新增服务器")
@PostMapping
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> createServerDeploy(@Validated @RequestBody ServerDeploy resources){
serverDeployService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改服务器")
@ApiOperation(value = "修改服务器")
@PutMapping
@PreAuthorize("@el.check('serverDeploy:edit')")
public ResponseEntity<Object> updateServerDeploy(@Validated @RequestBody ServerDeploy resources){
serverDeployService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
|
@Log("删除服务器")
@ApiOperation(value = "删除Server")
@DeleteMapping
@PreAuthorize("@el.check('serverDeploy:del')")
public ResponseEntity<Object> deleteServerDeploy(@RequestBody Set<Long> ids){
serverDeployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("测试连接服务器")
@ApiOperation(value = "测试连接服务器")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> testConnectServerDeploy(@Validated @RequestBody ServerDeploy resources){
return new ResponseEntity<>(serverDeployService.testConnect(resources),HttpStatus.CREATED);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\rest\ServerDeployController.java
| 1
|
请完成以下Java代码
|
public class ArrayInverter {
public void invertUsingFor(Object[] array) {
for (int i = 0; i < array.length / 2; i++) {
Object temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}
public void invertUsingCollectionsReverse(Object[] array) {
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
}
public Object[] invertUsingStreams(final Object[] array) {
return IntStream.rangeClosed(1, array.length)
|
.mapToObj(i -> array[array.length - i])
.toArray();
}
public void invertUsingCommonsLang(Object[] array) {
ArrayUtils.reverse(array);
}
public Object[] invertUsingGuava(Object[] array) {
List<Object> list = Arrays.asList(array);
List<Object> reverted = Lists.reverse(list);
return reverted.toArray();
}
}
|
repos\tutorials-master\core-java-modules\core-java-arrays-sorting\src\main\java\com\baeldung\array\ArrayInverter.java
| 1
|
请完成以下Java代码
|
public static boolean equals(@Nullable FAOpenItemKey o1, @Nullable FAOpenItemKey o2) {return Objects.equals(o1, o2);}
@Override
public String toString() {return getAsString();}
public String getAsString()
{
String stringRepresentation = this.stringRepresentation;
if (stringRepresentation == null)
{
stringRepresentation = this.stringRepresentation = buildStringRepresentation();
}
return stringRepresentation;
}
@NonNull
private String buildStringRepresentation()
{
final StringBuilder sb = new StringBuilder();
sb.append(accountConceptualName != null ? accountConceptualName.getAsString() : "-");
sb.append("#").append(tableName);
sb.append("#").append(Math.max(recordId, 0));
if (lineId > 0)
{
sb.append("#").append(lineId);
}
if (subLineId > 0)
{
sb.append("#").append(subLineId);
}
return sb.toString();
}
public Optional<InvoiceId> getInvoiceId()
{
return I_C_Invoice.Table_Name.equals(tableName)
? InvoiceId.optionalOfRepoId(recordId)
: Optional.empty();
}
|
public Optional<PaymentId> getPaymentId()
{
return I_C_Payment.Table_Name.equals(tableName)
? PaymentId.optionalOfRepoId(recordId)
: Optional.empty();
}
public Optional<BankStatementId> getBankStatementId()
{
return I_C_BankStatement.Table_Name.equals(tableName)
? BankStatementId.optionalOfRepoId(recordId)
: Optional.empty();
}
public Optional<BankStatementLineId> getBankStatementLineId()
{
return I_C_BankStatement.Table_Name.equals(tableName)
? BankStatementLineId.optionalOfRepoId(lineId)
: Optional.empty();
}
public Optional<BankStatementLineRefId> getBankStatementLineRefId()
{
return I_C_BankStatement.Table_Name.equals(tableName)
? BankStatementLineRefId.optionalOfRepoId(subLineId)
: Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\open_items\FAOpenItemKey.java
| 1
|
请完成以下Java代码
|
public int getM_ChangeNotice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeNotice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM() throws RuntimeException
{
return (org.eevolution.model.I_PP_Product_BOM)MTable.get(getCtx(), org.eevolution.model.I_PP_Product_BOM.Table_Name)
.getPO(getPP_Product_BOM_ID(), get_TrxName()); }
/** Set BOM & Formula.
@param PP_Product_BOM_ID
BOM & Formula
*/
public void setPP_Product_BOM_ID (int PP_Product_BOM_ID)
{
if (PP_Product_BOM_ID < 1)
set_Value (COLUMNNAME_PP_Product_BOM_ID, null);
else
set_Value (COLUMNNAME_PP_Product_BOM_ID, Integer.valueOf(PP_Product_BOM_ID));
}
/** Get BOM & Formula.
@return BOM & Formula
*/
public int getPP_Product_BOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Product_BOM_ID);
|
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Group.
@param R_Group_ID
Request Group
*/
public void setR_Group_ID (int R_Group_ID)
{
if (R_Group_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Group_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Group_ID, Integer.valueOf(R_Group_ID));
}
/** Get Group.
@return Request Group
*/
public int getR_Group_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Group_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Group.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_S_Resource getS_Resource() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setS_Resource(org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
/** Set Ressource.
@param S_Resource_ID
Resource
*/
@Override
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_Value (COLUMNNAME_S_Resource_ID, null);
else
set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
/** Get Ressource.
@return Resource
*/
@Override
public int getS_Resource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* TypeMRP AD_Reference_ID=53230
* Reference name: _MRP Type
*/
public static final int TYPEMRP_AD_Reference_ID=53230;
/** Demand = D */
public static final String TYPEMRP_Demand = "D";
/** Supply = S */
public static final String TYPEMRP_Supply = "S";
/** Set TypeMRP.
@param TypeMRP TypeMRP */
@Override
public void setTypeMRP (java.lang.String TypeMRP)
{
set_Value (COLUMNNAME_TypeMRP, TypeMRP);
}
/** Get TypeMRP.
@return TypeMRP */
@Override
|
public java.lang.String getTypeMRP ()
{
return (java.lang.String)get_Value(COLUMNNAME_TypeMRP);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
/** Set Version.
@param Version
Version of the table definition
*/
@Override
public void setVersion (java.math.BigDecimal Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.math.BigDecimal getVersion ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Version);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP.java
| 1
|
请完成以下Java代码
|
public IBBANStructureEntryBuilder setCodeType(BBANCodeEntryType codeType)
{
this.codeType = codeType;
return this;
}
@Override
public IBBANStructureEntryBuilder setCharacterType(EntryCharacterType characterType)
{
this.characterType = characterType;
return this;
}
@Override
public IBBANStructureEntryBuilder setLength(int length)
{
this.length = length;
return this;
}
|
@Override
public IBBANStructureEntryBuilder setSeqNo(String seqNo)
{
this.seqNo = seqNo;
return this;
}
public void create(BBANStructure _BBANStructure)
{
_BBANStructure.addEntry(entry);
}
public final IBBANStructureBuilder getParent()
{
return parent;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\BBANStructureEntryBuilder.java
| 1
|
请完成以下Java代码
|
public ParameterValueProvider getBusinessKeyValueProvider() {
return businessKeyValueProvider;
}
public void setBusinessKeyValueProvider(ParameterValueProvider businessKeyValueProvider) {
this.businessKeyValueProvider = businessKeyValueProvider;
}
// inputs //////////////////////////////////////////////////////////////////////
public List<CallableElementParameter> getInputs() {
return inputs;
}
public void addInput(CallableElementParameter input) {
inputs.add(input);
}
public void addInputs(List<CallableElementParameter> inputs) {
this.inputs.addAll(inputs);
}
public VariableMap getInputVariables(VariableScope variableScope) {
List<CallableElementParameter> inputs = getInputs();
return getVariables(inputs, variableScope);
}
// outputs /////////////////////////////////////////////////////////////////////
public List<CallableElementParameter> getOutputs() {
return outputs;
}
public List<CallableElementParameter> getOutputsLocal() {
return outputsLocal;
}
public void addOutput(CallableElementParameter output) {
outputs.add(output);
}
public void addOutputLocal(CallableElementParameter output) {
outputsLocal.add(output);
}
|
public void addOutputs(List<CallableElementParameter> outputs) {
this.outputs.addAll(outputs);
}
public VariableMap getOutputVariables(VariableScope calledElementScope) {
List<CallableElementParameter> outputs = getOutputs();
return getVariables(outputs, calledElementScope);
}
public VariableMap getOutputVariablesLocal(VariableScope calledElementScope) {
List<CallableElementParameter> outputs = getOutputsLocal();
return getVariables(outputs, calledElementScope);
}
// variables //////////////////////////////////////////////////////////////////
protected VariableMap getVariables(List<CallableElementParameter> params, VariableScope variableScope) {
VariableMap result = Variables.createVariables();
for (CallableElementParameter param : params) {
param.applyTo(variableScope, result);
}
return result;
}
// deployment id //////////////////////////////////////////////////////////////
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\CallableElement.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Transaction.class);
return marshaller;
}
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setMaxPoolSize(5);
taskExecutor.setCorePoolSize(5);
taskExecutor.setQueueCapacity(5);
taskExecutor.afterPropertiesSet();
return taskExecutor;
}
@Bean(name = "jobRepository")
public JobRepository getJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource());
factory.setTransactionManager(getTransactionManager());
// JobRepositoryFactoryBean's methods Throws Generic Exception,
// it would have been better to have a specific one
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean(name = "dataSource")
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
.addScript("classpath:org/springframework/batch/core/schema-h2.sql")
.build();
|
}
@Bean(name = "transactionManager")
public PlatformTransactionManager getTransactionManager() {
return new ResourcelessTransactionManager();
}
@Bean(name = "jobLauncher")
public JobLauncher getJobLauncher() throws Exception {
TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher();
// SimpleJobLauncher's methods Throws Generic Exception,
// it would have been better to have a specific one
jobLauncher.setJobRepository(getJobRepository());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
}
|
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\partitioner\SpringBatchPartitionConfig.java
| 2
|
请完成以下Java代码
|
private AttributeListValue getOrCreateSubproducerAttributeValue(@NonNull final I_I_Inventory importRecord)
{
final String subproducerBPartnerValue = importRecord.getSubProducerBPartner_Value();
if (Check.isEmpty(subproducerBPartnerValue, true))
{
return null;
}
final int subproducerBPartnerId = importRecord.getSubProducer_BPartner_ID();
if (subproducerBPartnerId <= 0)
{
return null;
}
final I_M_Attribute subProducerAttribute = attributeDAO.retrieveAttributeByValue(AttributeConstants.ATTR_SubProducerBPartner_Value);
final String subproducerBPartnerIdString = String.valueOf(subproducerBPartnerId);
final AttributeListValue existingAttributeValue = attributeDAO.retrieveAttributeValueOrNull(subProducerAttribute, subproducerBPartnerIdString);
if (existingAttributeValue != null)
{
return existingAttributeValue;
}
else
{
return attributeDAO.createAttributeValue(AttributeListValueCreateRequest.builder()
.attributeId(AttributeId.ofRepoId(subProducerAttribute.getM_Attribute_ID()))
.value(subproducerBPartnerIdString)
.name(subproducerBPartnerValue)
.build());
|
}
}
private void getCreateAttributeInstanceForSubproducer(
@NonNull final I_M_AttributeSetInstance asi,
@NonNull final AttributeListValue attributeValue)
{
// M_Attribute_ID
final AttributeId attributeId = attributeValue.getAttributeId();
//
// Get/Create/Update Attribute Instance
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(asi.getM_AttributeSetInstance_ID());
I_M_AttributeInstance attributeInstance = asiBL.getAttributeInstance(asiId, attributeId);
if (attributeInstance == null)
{
// FIXME use asiBL API
attributeInstance = newInstance(I_M_AttributeInstance.class, asi);
}
attributeInstance.setM_AttributeSetInstance(asi);
attributeInstance.setM_AttributeValue_ID(attributeValue.getId().getRepoId());
attributeInstance.setM_Attribute_ID(attributeId.getRepoId());
// the attribute is a list, but expect to store as number, the id of the partner
attributeInstance.setValueNumber(new BigDecimal(attributeValue.getValue()));
saveRecord(attributeInstance);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inventory\impexp\InventoryImportProcess.java
| 1
|
请完成以下Java代码
|
public class YearCreatePeriods extends JavaProcess
{
private int p_C_Year_ID = 0;
private Timestamp p_StartDate;
private String p_DateFormat;
/**
* Prepare
*/
@Override
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("StartDate"))
p_StartDate = (Timestamp)para[i].getParameter();
else if (name.equals("DateFormat"))
p_DateFormat = (String)para[i].getParameter();
else
|
log.error("Unknown Parameter: " + name);
}
p_C_Year_ID = getRecord_ID();
} // prepare
@Override
protected String doIt()
{
final I_C_Year year = load(p_C_Year_ID, I_C_Year.class);
if (year == null)
{
throw new AdempiereException("@NotFound@: @C_Year_ID@ - " + p_C_Year_ID);
}
log.info("Year: {}", year);
//
final Locale locale = null;
MYear.createStdPeriods(year, locale, p_StartDate, p_DateFormat);
return "@OK@";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\YearCreatePeriods.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
boolean match = false;
List<ConditionMessage> messages = new ArrayList<>(2);
ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnGraphQlSchema.class);
Binder binder = Binder.get(context.getEnvironment());
GraphQlProperties.Schema schema = binder.bind("spring.graphql.schema", GraphQlProperties.Schema.class)
.orElse(new GraphQlProperties.Schema());
ResourcePatternResolver resourcePatternResolver = ResourcePatternUtils
.getResourcePatternResolver(context.getResourceLoader());
List<Resource> schemaResources = resolveSchemaResources(resourcePatternResolver, schema.getLocations(),
schema.getFileExtensions());
if (!schemaResources.isEmpty()) {
match = true;
messages.add(message.found("schema", "schemas").items(ConditionMessage.Style.QUOTE, schemaResources));
}
else {
messages.add(message.didNotFind("schema files in locations")
.items(ConditionMessage.Style.QUOTE, Arrays.asList(schema.getLocations())));
}
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
Assert.state(beanFactory != null, "'beanFactory' must not be null");
String[] customizerBeans = beanFactory.getBeanNamesForType(GraphQlSourceBuilderCustomizer.class, false, false);
if (customizerBeans.length != 0) {
match = true;
messages.add(message.found("customizer", "customizers").items(Arrays.asList(customizerBeans)));
}
else {
messages.add((message.didNotFind("GraphQlSourceBuilderCustomizer").atAll()));
}
String[] graphQlSourceBeanNames = beanFactory.getBeanNamesForType(GraphQlSource.class, false, false);
if (graphQlSourceBeanNames.length != 0) {
match = true;
|
messages.add(message.found("GraphQlSource").items(Arrays.asList(graphQlSourceBeanNames)));
}
else {
messages.add((message.didNotFind("GraphQlSource").atAll()));
}
return new ConditionOutcome(match, ConditionMessage.of(messages));
}
private List<Resource> resolveSchemaResources(ResourcePatternResolver resolver, String[] locations,
String[] extensions) {
List<Resource> resources = new ArrayList<>();
for (String location : locations) {
for (String extension : extensions) {
resources.addAll(resolveSchemaResources(resolver, location + "*" + extension));
}
}
return resources;
}
private List<Resource> resolveSchemaResources(ResourcePatternResolver resolver, String pattern) {
try {
return Arrays.asList(resolver.getResources(pattern));
}
catch (IOException ex) {
return Collections.emptyList();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\DefaultGraphQlSchemaCondition.java
| 2
|
请完成以下Java代码
|
default TableRecordReference getSourceTableReference() {return null;}
@JsonIgnore
String getEventName();
@NonNull
@JsonIgnore
default String getEventId() {return getEventDescriptor().getEventId();}
@NonNull
@JsonIgnore
default ClientId getClientId() {return getEventDescriptor().getClientId();}
@NonNull
@JsonIgnore
default OrgId getOrgId() {return getEventDescriptor().getOrgId();}
|
@NonNull
@JsonIgnore
default ClientAndOrgId getClientAndOrgId() {return getEventDescriptor().getClientAndOrgId();}
@JsonIgnore
default UserId getUserId() {return getEventDescriptor().getUserId(); }
@Nullable
@JsonIgnore
default String getTraceId()
{
return getEventDescriptor().getTraceId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\MaterialEvent.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_ReferenceNo_Type[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Reference No Type.
@param C_ReferenceNo_Type_ID Reference No Type */
@Override
public void setC_ReferenceNo_Type_ID (int C_ReferenceNo_Type_ID)
{
if (C_ReferenceNo_Type_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_Type_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_Type_ID, Integer.valueOf(C_ReferenceNo_Type_ID));
}
/** Get Reference No Type.
@return Reference No Type */
@Override
public int getC_ReferenceNo_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_Type_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Java-Klasse.
@param Classname Java-Klasse */
@Override
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);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
|
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java-gen\de\metas\document\refid\model\X_C_ReferenceNo_Type.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public AppDefinitionQuery orderByAppDefinitionName() {
return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_NAME);
}
@Override
public AppDefinitionQuery orderByTenantId() {
return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_TENANT_ID);
}
// results ////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getAppDefinitionEntityManager(commandContext).findAppDefinitionCountByQueryCriteria(this);
}
@Override
public List<AppDefinition> executeList(CommandContext commandContext) {
return CommandContextUtil.getAppDefinitionEntityManager(commandContext).findAppDefinitionsByQueryCriteria(this);
}
// getters ////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public Set<String> getDeploymentIds() {
return deploymentIds;
}
public String getId() {
return id;
}
public Set<String> getIds() {
return ids;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public Integer getVersion() {
return version;
}
public Integer getVersionGt() {
return versionGt;
}
|
public Integer getVersionGte() {
return versionGte;
}
public Integer getVersionLt() {
return versionLt;
}
public Integer getVersionLte() {
return versionLte;
}
public boolean isLatest() {
return latest;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDefinitionQueryImpl.java
| 2
|
请完成以下Java代码
|
public class FinancialInstitutionIdentificationSEPA3 {
@XmlElement(name = "BIC")
protected String bic;
@XmlElement(name = "Othr")
protected OthrIdentification othr;
/**
* Gets the value of the bic property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBIC() {
return bic;
}
/**
* Sets the value of the bic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBIC(String value) {
this.bic = value;
}
|
/**
* Gets the value of the othr property.
*
* @return
* possible object is
* {@link OthrIdentification }
*
*/
public OthrIdentification getOthr() {
return othr;
}
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link OthrIdentification }
*
*/
public void setOthr(OthrIdentification value) {
this.othr = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\FinancialInstitutionIdentificationSEPA3.java
| 1
|
请完成以下Java代码
|
public void loadData(Object... sqlParams)
{
if (sql == null)
throw new IllegalStateException("Table not initialized. Please use prepareTable method first");
int selectedId = getSelectedId();
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
DB.setParameters(pstmt, sqlParams);
rs = pstmt.executeQuery();
this.loadTable(rs);
}
catch (Exception e)
{
log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
selectById(selectedId);
}
public int getSelectedId()
{
if (idColumnIndex < 0)
return -1;
int row = getSelectedRow();
if (row != -1)
{
Object data = getModel().getValueAt(row, 0);
if (data != null)
{
Integer id = ((IDColumn)data).getRecord_ID();
return id == null ? -1 : id.intValue();
}
}
return -1;
}
public void selectById(int id)
{
selectById(id, true);
}
public void selectById(int id, boolean fireEvent)
{
if (idColumnIndex < 0)
|
return;
boolean fireSelectionEventOld = fireSelectionEvent;
try
{
fireSelectionEvent = fireEvent;
if (id < 0)
{
this.getSelectionModel().removeSelectionInterval(0, this.getRowCount());
return;
}
for (int i = 0; i < this.getRowCount(); i++)
{
IDColumn key = (IDColumn)this.getModel().getValueAt(i, idColumnIndex);
if (key != null && id > 0 && key.getRecord_ID() == id)
{
this.getSelectionModel().setSelectionInterval(i, i);
break;
}
}
}
finally
{
fireSelectionEvent = fireSelectionEventOld;
}
}
private boolean fireSelectionEvent = true;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\ui\swing\MiniTable2.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getCandidateOrAssigned() {
return candidateOrAssigned;
}
public void setCandidateOrAssigned(String candidateOrAssigned) {
this.candidateOrAssigned = candidateOrAssigned;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public List<String> getCategoryIn() {
return categoryIn;
}
public void setCategoryIn(List<String> categoryIn) {
this.categoryIn = categoryIn;
}
public List<String> getCategoryNotIn() {
return categoryNotIn;
}
public void setCategoryNotIn(List<String> categoryNotIn) {
this.categoryNotIn = categoryNotIn;
}
public Boolean getWithoutCategory() {
return withoutCategory;
}
public void setWithoutCategory(Boolean withoutCategory) {
this.withoutCategory = withoutCategory;
}
public String getRootScopeId() {
return rootScopeId;
|
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskQueryRequest.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("IdentityLinkEntity[id=").append(id);
sb.append(", type=").append(type);
if (userId != null) {
sb.append(", userId=").append(userId);
}
if (groupId != null) {
sb.append(", groupId=").append(groupId);
}
if (taskId != null) {
sb.append(", taskId=").append(taskId);
}
if (processInstanceId != null) {
sb.append(", processInstanceId=").append(processInstanceId);
}
|
if (processDefId != null) {
sb.append(", processDefId=").append(processDefId);
}
if (scopeId != null) {
sb.append(", scopeId=").append(scopeId);
}
if (scopeType != null) {
sb.append(", scopeType=").append(scopeType);
}
if (scopeDefinitionId != null) {
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\IdentityLinkEntityImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class AuthenticationApi {
private final UserDetailsService userDetailsService;
private final JwtEncoder encoder;
public AuthenticationApi(UserDetailsService userDetailsService, JwtEncoder encoder) {
this.userDetailsService = userDetailsService;
this.encoder = encoder;
}
/**
* API to Login
*
* @param user The login entity that contains username and password
* @return Returns the JWT token
* @see com.baeldung.jwt.User
*/
@Operation(summary = "User Authentication", description = "Authenticate the user and return a JWT token if the user is valid.")
@io.swagger.v3.oas.annotations.parameters.RequestBody(content = @io.swagger.v3.oas.annotations.media.Content(mediaType = "application/json", examples = @io.swagger.v3.oas.annotations.media.ExampleObject(value = "{\n" + " \"username\": \"jane\",\n"
+ " \"password\": \"password\"\n" + "}", summary = "User Authentication Example")))
@PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> login(@RequestBody User user) {
UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
if (user.getPassword().equalsIgnoreCase(userDetails.getPassword())) {
String token = generateToken(userDetails);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("X-AUTH-TOKEN", token);
return ResponseEntity.ok().headers(httpHeaders).contentType(MediaType.APPLICATION_JSON).body("{\"token\":\"" + token + "\"}");
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).contentType(MediaType.APPLICATION_JSON).body("Invalid username or password");
|
}
}
/**
* Generates the JWT token with claims
*
* @param userDetails The user details
* @return Returns the JWT token
*/
private String generateToken(UserDetails userDetails) {
Instant now = Instant.now();
long expiry = 36000L;
// @formatter:off
String scope = userDetails.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(" "));
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now)
.expiresAt(now.plusSeconds(expiry))
.subject(userDetails.getUsername())
.claim("scope", scope)
.build();
// @formatter:on
return this.encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc\src\main\java\com\baeldung\jwt\AuthenticationApi.java
| 2
|
请完成以下Java代码
|
public void onValidationError(String params, String msg) {
sendRpcReplyOnValidationError(msg);
if (callback != null) {
callback.onValidationError(params, msg);
}
}
@Override
public void onError(String params, Exception e) {
if (e instanceof TimeoutException || e instanceof org.eclipse.leshan.core.request.exception.TimeoutException) {
client.setLastSentRpcId(null);
transportService.process(client.getSession(), this.request, RpcStatus.TIMEOUT, TransportServiceCallback.EMPTY);
} else if (!(e instanceof ClientSleepingException)) {
sendRpcReplyOnError(e);
}
if (callback != null) {
callback.onError(params, e);
}
}
protected void reply(LwM2MRpcResponseBody response) {
TransportProtos.ToDeviceRpcResponseMsg.Builder msg = TransportProtos.ToDeviceRpcResponseMsg.newBuilder().setRequestId(request.getRequestId());
String responseAsString = JacksonUtil.toString(response);
if (StringUtils.isEmpty(response.getError())) {
msg.setPayload(responseAsString);
} else {
msg.setError(responseAsString);
}
|
transportService.process(client.getSession(), msg.build(), null);
}
abstract protected void sendRpcReplyOnSuccess(T response);
protected void sendRpcReplyOnValidationError(String msg) {
reply(LwM2MRpcResponseBody.builder().result(ResponseCode.BAD_REQUEST.getName()).error(msg).build());
}
protected void sendRpcReplyOnError(Exception e) {
String error = e.getMessage();
if (error == null) {
error = e.toString();
}
reply(LwM2MRpcResponseBody.builder().result(ResponseCode.INTERNAL_SERVER_ERROR.getName()).error(error).build());
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\rpc\RpcDownlinkRequestCallbackProxy.java
| 1
|
请完成以下Java代码
|
class MonadBaseExample {
public double multiplyBy2(double n) {
return n * 2;
}
public double divideBy2(double n) {
return n / 2;
}
public double add3(double n) {
return n + 3;
}
public double subtract1(double n) {
return n - 1;
}
}
class MonadSample1 extends MonadBaseExample {
public double apply(double n) {
return subtract1(add3(divideBy2(multiplyBy2(multiplyBy2(2)))));
}
}
class MonadSample2 extends MonadBaseExample {
public double apply(double n) {
double n1 = multiplyBy2(n);
double n2 = multiplyBy2(n1);
double n3 = divideBy2(n2);
double n4 = add3(n3);
return subtract1(n4);
}
}
class MonadSample3 extends MonadBaseExample {
public double apply(double n) {
return Optional.of(n)
.flatMap(value -> Optional.of(multiplyBy2(value)))
.flatMap(value -> Optional.of(multiplyBy2(value)))
.flatMap(value -> Optional.of(divideBy2(value)))
.flatMap(value -> Optional.of(add3(value)))
.flatMap(value -> Optional.of(subtract1(value)))
.get();
}
|
}
class MonadSample4 extends MonadBaseExample {
public boolean leftIdentity() {
Function<Integer, Optional<Integer>> mapping = value -> Optional.of(value + 1);
return Optional.of(3).flatMap(mapping).equals(mapping.apply(3));
}
public boolean rightIdentity() {
return Optional.of(3).flatMap(Optional::of).equals(Optional.of(3));
}
public boolean associativity() {
Function<Integer, Optional<Integer>> mapping = value -> Optional.of(value + 1);
Optional<Integer> leftSide = Optional.of(3).flatMap(mapping).flatMap(Optional::of);
Optional<Integer> rightSide = Optional.of(3).flatMap(v -> mapping.apply(v).flatMap(Optional::of));
return leftSide.equals(rightSide);
}
}
class MonadSample5 extends MonadBaseExample {
public boolean fail() {
Function<Integer, Optional<Integer>> mapping = value -> Optional.of(value == null ? -1 : value + 1);
return Optional.ofNullable((Integer) null).flatMap(mapping).equals(mapping.apply(null));
}
}
|
repos\tutorials-master\core-java-modules\core-java-8\src\main\java\com\baeldung\monad\MonadSamples.java
| 1
|
请完成以下Java代码
|
public static void concatByFormat(String formatStr, String[] data, Blackhole blackhole) {
String concatString = String.format(formatStr, data);
blackhole.consume(concatString);
}
@Benchmark
public static void concatByStreamBy100(Blackhole blackhole) {
concatByStream(DATA_100, blackhole);
}
@Benchmark
public static void concatByStreamBy1000(Blackhole blackhole) {
concatByStream(DATA_1000, blackhole);
}
@Benchmark
public static void concatByStreamBy10000(Blackhole blackhole) {
concatByStream(DATA_10000, blackhole);
}
|
public static void concatByStream(String[] data, Blackhole blackhole) {
String concatString = "";
List<String> strList = List.of(data);
concatString = strList.stream().collect(Collectors.joining(""));
blackhole.consume(concatString);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(BatchConcatBenchmark.class.getSimpleName()).threads(1)
.shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-6\src\main\java\com\baeldung\performance\BatchConcatBenchmark.java
| 1
|
请完成以下Java代码
|
public boolean isVirtualColumn()
{
return (ColumnSQL != null && !ColumnSQL.isEmpty())
|| (ColumnClass != null && !ColumnClass.isEmpty());
} // isColumnVirtual
public boolean isReadOnly()
{
return IsReadOnly;
}
public boolean isUpdateable()
{
return IsUpdateable;
}
public boolean isAlwaysUpdateable()
{
return IsAlwaysUpdateable;
}
|
public boolean isKey()
{
return IsKey;
}
public boolean isEncryptedField()
{
return IsEncryptedField;
}
public boolean isEncryptedColumn()
{
return IsEncryptedColumn;
}
public boolean isSelectionColumn()
{
return defaultFilterDescriptor != null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVO.java
| 1
|
请完成以下Java代码
|
public class Task {
@NotBlank(message = "Task title must be present")
@Size(min = 3, max = 20, message = "Task title size not valid")
private String title;
@Size(min = 3, max = 500, message = "Task description size not valid")
private String description;
public Task(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle() {
|
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
repos\tutorials-master\javaxval-2\src\main\java\com\baeldung\javaxval\childvalidation\Task.java
| 1
|
请完成以下Java代码
|
private boolean isLoaderClass(String className) {
return className.startsWith("org.springframework.boot.loader.");
}
private @Nullable Method getMainMethod(StackTraceElement element) {
try {
Class<?> elementClass = Class.forName(element.getClassName());
Method method = getMainMethod(elementClass);
if (Modifier.isStatic(method.getModifiers())) {
return method;
}
}
catch (Exception ex) {
// Ignore
}
return null;
}
private static Method getMainMethod(Class<?> clazz) throws Exception {
try {
return clazz.getDeclaredMethod("main", String[].class);
}
catch (NoSuchMethodException ex) {
return clazz.getDeclaredMethod("main");
|
}
}
/**
* Returns the actual main method.
* @return the main method
*/
Method getMethod() {
return this.method;
}
/**
* Return the name of the declaring class.
* @return the declaring class name
*/
String getDeclaringClassName() {
return this.method.getDeclaringClass().getName();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\MainMethod.java
| 1
|
请完成以下Java代码
|
public ImmutableMap<String, String> toMap()
{
return tags;
}
/**
* @deprecated Please use {@link #getTagsAsString()}
*/
@Deprecated
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(tags)
.toString();
}
public String getTagsAsString()
{
return TAGS_STRING_JOINER.join(tags);
}
/** @return {@code true} if this attachment has a tag with the given name; the label doesn't need to have a value though. */
public boolean hasTag(@NonNull final String tag)
{
return tags.containsKey(tag);
}
public boolean hasAllTagsSetToTrue(@NonNull final List<String> tagNames)
{
for (final String tagName : tagNames)
{
if (!hasTagSetToTrue(tagName))
{
return false;
}
}
return true;
}
public boolean hasTagSetToTrue(@NonNull final String tagName)
{
return StringUtils.toBoolean(getTagValueOrNull(tagName), false);
}
public boolean hasTagSetToString(@NonNull final String tagName, @NonNull final String tagValue)
{
return Objects.equals(getTagValueOrNull(tagName), tagValue);
}
public String getTagValue(@NonNull final String tagName)
{
return Check.assumeNotEmpty(
getTagValueOrNull(tagName),
"This attachmentEntry needs to have a tag with name={} and a value; this={}", tagName, this);
}
public String getTagValueOrNull(String tagName)
{
return tags.get(tagName);
}
public boolean hasAllTagsSetToAnyValue(@NonNull final List<String> tagNames)
{
for (final String tagName : tagNames)
{
if (getTagValueOrNull(tagName) == null)
|
{
return false;
}
}
return true;
}
public AttachmentTags withTag(@NonNull final String tagName, @NonNull final String tagValue)
{
if (hasTagSetToString(tagName, tagValue))
{
return this;
}
else
{
final HashMap<String, String> map = new HashMap<>(this.tags);
map.put(tagName, tagValue);
return new AttachmentTags(map);
}
}
public AttachmentTags withoutTags(@NonNull final AttachmentTags tagsToRemove)
{
final HashMap<String, String> tmp = new HashMap<>(this.tags);
tmp.keySet().removeAll(tagsToRemove.tags.keySet());
return new AttachmentTags(tmp);
}
public AttachmentTags withTags(@NonNull final AttachmentTags additionalTags)
{
final HashMap<String, String> tmp = new HashMap<>(this.tags);
tmp.putAll(additionalTags.tags);
return new AttachmentTags(tmp);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentTags.java
| 1
|
请完成以下Java代码
|
public class KafkaAppender extends AbstractAppender {
@PluginBuilderFactory
public static Builder newBuilder() {
return new Builder();
}
public static class Builder implements org.apache.logging.log4j.core.util.Builder<KafkaAppender> {
@PluginBuilderAttribute("name")
@Required
private String name;
@PluginBuilderAttribute("ip")
private String ipAddress;
@PluginBuilderAttribute("port")
private int port;
@PluginBuilderAttribute("topic")
private String topic;
@PluginBuilderAttribute("partition")
private String partition;
@PluginElement("Layout")
private Layout<? extends Serializable> layout;
@PluginElement("Filter")
private Filter filter;
public Layout<? extends Serializable> getLayout() {
return layout;
}
public Builder setLayout(Layout<? extends Serializable> layout) {
this.layout = layout;
return this;
}
public Filter getFilter() {
return filter;
}
public String getName() {
return name;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setFilter(Filter filter) {
this.filter = filter;
return this;
}
public String getIpAddress() {
return ipAddress;
}
public Builder setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
return this;
}
public int getPort() {
return port;
}
|
public Builder setPort(int port) {
this.port = port;
return this;
}
public String getTopic() {
return topic;
}
public Builder setTopic(String topic) {
this.topic = topic;
return this;
}
public String getPartition() {
return partition;
}
public Builder setPartition(String partition) {
this.partition = partition;
return this;
}
@Override
public KafkaAppender build() {
return new KafkaAppender(getName(), getFilter(), getLayout(), true, new KafkaBroker(ipAddress, port, topic, partition));
}
}
private KafkaBroker broker;
private KafkaAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions, KafkaBroker broker) {
super(name, filter, layout, ignoreExceptions);
this.broker = broker;
}
@Override
public void append(LogEvent event) {
connectAndSendToKafka(broker, event);
}
private void connectAndSendToKafka(KafkaBroker broker, LogEvent event) {
//send to Kafka
}
}
|
repos\tutorials-master\logging-modules\log4j2\src\main\java\com\baeldung\logging\log4j2\plugins\KafkaAppender.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<JsonError> handleMissingPropertyException(@NonNull final MissingPropertyException e)
{
return logAndCreateError(e, HttpStatus.UNPROCESSABLE_ENTITY);
}
@ExceptionHandler(MissingResourceException.class)
public ResponseEntity<JsonError> handleMissingResourceException(@NonNull final MissingResourceException e)
{
return logAndCreateError(e, HttpStatus.UNPROCESSABLE_ENTITY);
}
@ExceptionHandler(InvalidIdentifierException.class)
public ResponseEntity<JsonError> InvalidIdentifierException(@NonNull final InvalidIdentifierException e)
{
final String msg = "Invalid identifier: " + e.getMessage();
final HttpStatus status = e.getMessage().startsWith("tea")
? HttpStatus.I_AM_A_TEAPOT // whohoo, finally found a reason!
: HttpStatus.NOT_FOUND;
return logAndCreateError(
e,
msg,
status);
}
@ExceptionHandler(DBUniqueConstraintException.class)
public ResponseEntity<JsonError> handleDBUniqueConstraintException(@NonNull final DBUniqueConstraintException e)
{
return logAndCreateError(
e,
"At least one record already existed in the system:" + e.getMessage(),
HttpStatus.UNPROCESSABLE_ENTITY);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<JsonError> handleException(@NonNull final Exception e)
{
final ResponseStatus responseStatus = e.getClass().getAnnotation(ResponseStatus.class);
if (responseStatus != null)
{
return logAndCreateError(e, responseStatus.reason(), responseStatus.code());
}
return logAndCreateError(e, HttpStatus.UNPROCESSABLE_ENTITY);
}
private ResponseEntity<JsonError> logAndCreateError(
@NonNull final Exception e,
@NonNull final HttpStatus status)
|
{
return logAndCreateError(e, null, status);
}
private ResponseEntity<JsonError> logAndCreateError(
@NonNull final Exception e,
@Nullable final String detail,
@NonNull final HttpStatus status)
{
final String logMessage = coalesceSuppliers(
() -> detail,
e::getMessage,
() -> e.getClass().getSimpleName());
Loggables.withFallbackToLogger(logger, Level.ERROR).addLog(logMessage, e);
final String adLanguage = Env.getADLanguageOrBaseLanguage();
final JsonError error = JsonError.builder()
.error(JsonErrors.ofThrowable(e, adLanguage, TranslatableStrings.constant(detail)))
.build();
return new ResponseEntity<>(error, status);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\exception\RestResponseEntityExceptionHandler.java
| 1
|
请完成以下Java代码
|
public int size()
{
return keys.getCurrentSize();
}
public boolean contains(Object element)
{
try
{
elements.location(element);
return(true);
}
catch(org.apache.ecs.storage.NoSuchObjectException noSuchObject)
{
return false;
}
}
public Enumeration keys()
{
return keys;
}
public boolean containsKey(String key)
{
try
{
keys.location(key);
}
catch(org.apache.ecs.storage.NoSuchObjectException noSuchObject)
{
return false;
}
return(true);
}
public Enumeration elements()
|
{
return elements;
}
public Object get(String key)
{
try
{
if( containsKey(key) )
return(elements.get(keys.location(key)));
}
catch(org.apache.ecs.storage.NoSuchObjectException nsoe)
{
}
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\storage\Hash.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
System.out.println("\nfetchBooksAndFormatsJpql: ");
bookstoreService.fetchBooksAndFormatsJpql()
.forEach((e) -> System.out.println(e.getTitle() + " | " + e.getFormatType()));
|
System.out.println("\nfetchBooksAndFormatsSql: ");
bookstoreService.fetchBooksAndFormatsSql()
.forEach((e) -> System.out.println(e.getTitle() + " | " + e.getFormatType()));
System.out.println("\nfetchFormatsAndBooksJpql: ");
bookstoreService.fetchFormatsAndBooksJpql()
.forEach((e) -> System.out.println(e.getTitle() + " | " + e.getFormatType()));
System.out.println("\nfetchFormatsAndBooksSql: ");
bookstoreService.fetchFormatsAndBooksSql()
.forEach((e) -> System.out.println(e.getTitle() + " | " + e.getFormatType()));
};
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaCrossJoins\src\main\java\com\bookstore\MainApplication.java
| 2
|
请完成以下Java代码
|
public class DBRes_nl extends ListResourceBundle
{
/** Data */
static final Object[][] contents = new String[][]
{
{ "CConnectionDialog", "Verbinding met Server" },
{ "Name", "Naam" },
{ "AppsHost", "Applicatie Server" },
{ "AppsPort", "Applicatie Poort" },
{ "TestApps", "Test Applicatie" },
{ "DBHost", "Database Server" },
{ "DBPort", "Database Poort" },
{ "DBName", "Database Naam" },
{ "DBUidPwd", "Gebruikersnaam / Wachtwoord" },
{ "ViaFirewall", "via Firewall" },
{ "FWHost", "Firewall" },
{ "FWPort", "Firewall Poort" },
{ "TestConnection", "Test Database" },
{ "Type", "Database Type" },
{ "BequeathConnection", "Lokale Connectie" },
{ "Overwrite", "Overschrijven" },
|
{ "ConnectionProfile", "Connection" },
{ "LAN", "LAN" },
{ "TerminalServer", "Terminal Server" },
{ "VPN", "VPN" },
{ "WAN", "WAN" },
{ "ConnectionError", "Fout bij verbinden" },
{ "ServerNotActive", "Server Niet Actief" }
};
/**
* Get Contsnts
* @return contents
*/
public Object[][] getContents()
{
return contents;
} // getContent
} // Res
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_nl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private <T extends ActiveMQConnectionFactory> T createEmbeddedConnectionFactory(
Function<ServerLocator, T> factoryCreator) throws Exception {
try {
TransportConfiguration transportConfiguration = new TransportConfiguration(
InVMConnectorFactory.class.getName(), this.properties.getEmbedded().generateTransportParameters());
ServerLocator serverLocator = ActiveMQClient.createServerLocatorWithoutHA(transportConfiguration);
return factoryCreator.apply(serverLocator);
}
catch (NoClassDefFoundError ex) {
throw new IllegalStateException("Unable to create InVM "
+ "Artemis connection, ensure that artemis-jms-server.jar is in the classpath", ex);
}
}
private <T extends ActiveMQConnectionFactory> T createNativeConnectionFactory(Function<String, T> factoryCreator) {
T connectionFactory = newNativeConnectionFactory(factoryCreator);
|
String user = this.connectionDetails.getUser();
if (StringUtils.hasText(user)) {
connectionFactory.setUser(user);
connectionFactory.setPassword(this.connectionDetails.getPassword());
}
return connectionFactory;
}
private <T extends ActiveMQConnectionFactory> T newNativeConnectionFactory(Function<String, T> factoryCreator) {
String brokerUrl = StringUtils.hasText(this.connectionDetails.getBrokerUrl())
? this.connectionDetails.getBrokerUrl() : DEFAULT_BROKER_URL;
return factoryCreator.apply(brokerUrl);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisConnectionFactoryFactory.java
| 2
|
请完成以下Java代码
|
public List<ChannelDefinition> findChannelDefinitionsByQueryCriteria(ChannelDefinitionQueryImpl channelQuery) {
return dataManager.findChannelDefinitionsByQueryCriteria(channelQuery);
}
@Override
public long findChannelDefinitionCountByQueryCriteria(ChannelDefinitionQueryImpl channelQuery) {
return dataManager.findChannelDefinitionCountByQueryCriteria(channelQuery);
}
@Override
public ChannelDefinitionEntity findChannelDefinitionByDeploymentAndKey(String deploymentId, String channelDefinitionKey) {
return dataManager.findChannelDefinitionByDeploymentAndKey(deploymentId, channelDefinitionKey);
}
@Override
public ChannelDefinitionEntity findChannelDefinitionByDeploymentAndKeyAndTenantId(String deploymentId, String channelDefinitionKey, String tenantId) {
return dataManager.findChannelDefinitionByDeploymentAndKeyAndTenantId(deploymentId, channelDefinitionKey, tenantId);
}
@Override
public ChannelDefinitionEntity findLatestChannelDefinitionByKeyAndTenantId(String channelDefinitionKey, String tenantId) {
if (tenantId == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(tenantId)) {
return dataManager.findLatestChannelDefinitionByKey(channelDefinitionKey);
} else {
return dataManager.findLatestChannelDefinitionByKeyAndTenantId(channelDefinitionKey, tenantId);
}
}
@Override
public ChannelDefinitionEntity findChannelDefinitionByKeyAndVersionAndTenantId(String channelDefinitionKey, Integer eventVersion, String tenantId) {
if (tenantId == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(tenantId)) {
return dataManager.findChannelDefinitionByKeyAndVersion(channelDefinitionKey, eventVersion);
} else {
return dataManager.findChannelDefinitionByKeyAndVersionAndTenantId(channelDefinitionKey, eventVersion, tenantId);
|
}
}
@Override
public List<ChannelDefinition> findChannelDefinitionsByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findChannelDefinitionsByNativeQuery(parameterMap);
}
@Override
public long findChannelDefinitionCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findChannelDefinitionCountByNativeQuery(parameterMap);
}
@Override
public void updateChannelDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) {
dataManager.updateChannelDefinitionTenantIdForDeployment(deploymentId, newTenantId);
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\ChannelDefinitionEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public class X_C_Printing_Queue_Recipient extends org.compiere.model.PO implements I_C_Printing_Queue_Recipient, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1550500719L;
/** Standard Constructor */
public X_C_Printing_Queue_Recipient (Properties ctx, int C_Printing_Queue_Recipient_ID, String trxName)
{
super (ctx, C_Printing_Queue_Recipient_ID, trxName);
}
/** Load Constructor */
public X_C_Printing_Queue_Recipient (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_User_ToPrint_ID (int AD_User_ToPrint_ID)
{
if (AD_User_ToPrint_ID < 1)
set_Value (COLUMNNAME_AD_User_ToPrint_ID, null);
else
set_Value (COLUMNNAME_AD_User_ToPrint_ID, Integer.valueOf(AD_User_ToPrint_ID));
}
@Override
public int getAD_User_ToPrint_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ToPrint_ID);
}
@Override
public de.metas.printing.model.I_C_Printing_Queue getC_Printing_Queue()
{
return get_ValueAsPO(COLUMNNAME_C_Printing_Queue_ID, de.metas.printing.model.I_C_Printing_Queue.class);
}
@Override
public void setC_Printing_Queue(de.metas.printing.model.I_C_Printing_Queue C_Printing_Queue)
{
|
set_ValueFromPO(COLUMNNAME_C_Printing_Queue_ID, de.metas.printing.model.I_C_Printing_Queue.class, C_Printing_Queue);
}
@Override
public void setC_Printing_Queue_ID (int C_Printing_Queue_ID)
{
if (C_Printing_Queue_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Printing_Queue_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Printing_Queue_ID, Integer.valueOf(C_Printing_Queue_ID));
}
@Override
public int getC_Printing_Queue_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Printing_Queue_ID);
}
@Override
public void setC_Printing_Queue_Recipient_ID (int C_Printing_Queue_Recipient_ID)
{
if (C_Printing_Queue_Recipient_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Printing_Queue_Recipient_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Printing_Queue_Recipient_ID, Integer.valueOf(C_Printing_Queue_Recipient_ID));
}
@Override
public int getC_Printing_Queue_Recipient_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Printing_Queue_Recipient_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue_Recipient.java
| 1
|
请完成以下Java代码
|
private static LookupValuesList extractLookupValuesList(final DocumentFilterParam filterParam)
{
final Object valueObj = filterParam.getValue();
if (valueObj == null)
{
return LookupValuesList.EMPTY;
}
else if (valueObj instanceof String && ((String)valueObj).isEmpty())
{
return LookupValuesList.EMPTY;
}
else if (valueObj instanceof LookupValuesList)
{
return (LookupValuesList)valueObj;
}
else
{
throw new AdempiereException("Cannot convert " + valueObj + " to " + LookupValuesList.class + " for " + filterParam);
}
}
public static String includedFilterParameterName(@NonNull final DetailId tabId, @NonNull final String filterId, @NonNull final String parameterName)
{
return ParameterNameFQ.of(tabId, filterId, parameterName).getAsString();
}
@Value(staticConstructor = "of")
private static class ParameterNameFQ
{
@Nullable DetailId tabId;
@Nullable String includedFilterId;
@NonNull String parameterName;
private static final Splitter SPLITTER = Splitter.on(".");
public static ParameterNameFQ ofParameterNameFQ(@NonNull String parameterNameFQ)
{
final List<String> parts = SPLITTER.splitToList(parameterNameFQ);
|
if (parts.size() == 1)
{
return of(null, null, parameterNameFQ);
}
else if (parts.size() == 3)
{
return of(
DetailId.fromJson(parts.get(0)),
parts.get(1),
parts.get(2)
);
}
else
{
throw new AdempiereException("Invalid parameter name `" + parameterNameFQ + "`");
}
}
public String getAsString()
{
if (tabId == null)
{
return parameterName;
}
else
{
return tabId.toJson() + "." + includedFilterId + "." + parameterName;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlDefaultDocumentFilterConverter.java
| 1
|
请完成以下Java代码
|
class KotlinMavenFullBuildCustomizer implements BuildCustomizer<MavenBuild> {
private final KotlinProjectSettings settings;
KotlinMavenFullBuildCustomizer(KotlinProjectSettings kotlinProjectSettings) {
this.settings = kotlinProjectSettings;
}
@Override
public void customize(MavenBuild build) {
build.properties().version(KotlinMavenBuildCustomizer.KOTLIN_VERSION_PROPERTY, this.settings.getVersion());
build.settings()
.sourceDirectory("${project.basedir}/src/main/kotlin")
.testSourceDirectory("${project.basedir}/src/test/kotlin");
build.plugins().add("org.jetbrains.kotlin", "kotlin-maven-plugin", (kotlinMavenPlugin) -> {
kotlinMavenPlugin
.versionReference(VersionReference.ofProperty(KotlinMavenBuildCustomizer.KOTLIN_VERSION_PROPERTY));
kotlinMavenPlugin.configuration((configuration) -> {
|
configuration.configure("args",
(args) -> this.settings.getCompilerArgs().forEach((arg) -> args.add("arg", arg)));
configuration.configure("compilerPlugins",
(compilerPlugins) -> compilerPlugins.add("plugin", "spring"));
configuration.add("jvmTarget", this.settings.getJvmTarget());
});
kotlinMavenPlugin.execution("compile", (compile) -> compile.phase("compile").goal("compile"));
kotlinMavenPlugin.execution("test-compile",
(compile) -> compile.phase("test-compile").goal("test-compile"));
kotlinMavenPlugin.dependency("org.jetbrains.kotlin", "kotlin-maven-allopen",
VersionReference.ofProperty(KotlinMavenBuildCustomizer.KOTLIN_VERSION_PROPERTY));
});
}
}
|
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\KotlinMavenFullBuildCustomizer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public EventSubscriptionBuilder scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
@Override
public EventSubscriptionBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public EventSubscriptionBuilder configuration(String configuration) {
this.configuration = configuration;
return this;
}
@Override
public EventSubscription create() {
return eventSubscriptionService.createEventSubscription(this);
}
@Override
public String getEventType() {
return eventType;
}
@Override
public String getEventName() {
return eventName;
}
@Override
public Signal getSignal() {
return signal;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
|
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public String getScopeDefinitionKey() {
return scopeDefinitionKey;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getConfiguration() {
return configuration;
}
}
|
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionBuilderImpl.java
| 2
|
请完成以下Java代码
|
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
|
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SortPref_Line_Product.java
| 1
|
请完成以下Java代码
|
private boolean isEmpty()
{
return fields.isEmpty() && inlineTabId == null;
}
public Set<JSONDocumentLayoutElementField> getFields()
{
return fields;
}
public boolean hasField(@NonNull final String fieldName)
{
return fields.stream().anyMatch(field -> fieldName.equals(field.getField()));
}
public static boolean hasField(@NonNull final List<JSONDocumentLayoutElement> elements, @NonNull final String fieldName)
{
return elements.stream().anyMatch(element -> element.hasField(fieldName));
}
void setInlineTab(@NonNull final JSONDocumentLayoutTab inlineTab)
|
{
if (inlineTabId == null)
{
throw new AdempiereException("Setting inline tab not allowed if inlineTabId was not set before");
}
else if (!DetailId.equals(inlineTabId, inlineTab.getTabId()))
{
throw new AdempiereException("inlineTabId not matching: " + inlineTabId + ", " + inlineTab);
}
else
{
this.inlineTab = inlineTab;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayoutElement.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public UpdateUserResult handle(UpdateUser command) {
var currentUserId = authenticationService.getRequiredCurrentUserId();
var user = userRepository.findById(currentUserId)
.orElseThrow(() -> notFound("user [name=%s] does not exist",
authenticationService.getCurrentUserName()));
if (command.getUsername() != null
&& !command.getUsername().equals(user.username())
&& userRepository.existsByUsername(command.getUsername())) {
throw badRequest("user [name=%s] already exists", command.getUsername());
}
if (command.getEmail() != null
&& !command.getEmail().equals(user.email())
&& userRepository.existsByEmail(command.getEmail())) {
throw badRequest("user [email=%s] already exists", command.getEmail());
}
var alteredUser = user.toBuilder()
|
.email(command.getEmail() == null ? user.email() : command.getEmail())
.username(command.getUsername() == null ? user.username() : command.getUsername())
.password(command.getPassword() == null ? user.password() : encoder.encode(command.getPassword()))
.bio(command.getBio() == null ? user.bio() : command.getBio())
.image(command.getImage() == null ? user.image() : command.getImage())
.build();
var savedUser = userRepository.save(alteredUser);
var token = jwtService.getToken(savedUser);
var data = conversionService.convert(new UserWithToken(savedUser, token), UserDto.class);
return new UpdateUserResult(data);
}
}
|
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\application\command\UpdateUserHandler.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class HuForInventoryLine
{
@NonNull OrgId orgId;
@Nullable HuId huId;
@Nullable HUQRCode huQRCode;
@NonNull Quantity quantityBooked;
@Nullable Quantity quantityCount;
@NonNull ProductId productId;
@NonNull AttributesKey storageAttributesKey;
@NonNull LocatorId locatorId;
boolean markAsCounted;
@Builder
private HuForInventoryLine(
@NonNull final OrgId orgId,
@Nullable final HuId huId,
@Nullable final HUQRCode huQRCode,
@NonNull final Quantity quantityBooked,
@Nullable final Quantity quantityCount,
@NonNull final ProductId productId,
|
@NonNull final AttributesKey storageAttributesKey,
@NonNull final LocatorId locatorId,
boolean markAsCounted)
{
Quantity.getCommonUomIdOfAll(quantityBooked, quantityCount); // make sure we use the same UOM
this.orgId = orgId;
this.huId = huId;
this.huQRCode = huQRCode;
this.quantityBooked = quantityBooked;
this.quantityCount = quantityCount;
this.productId = productId;
this.storageAttributesKey = storageAttributesKey;
this.locatorId = locatorId;
this.markAsCounted = markAsCounted;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\HuForInventoryLine.java
| 2
|
请完成以下Java代码
|
protected void markImported(@NonNull final I_I_DataEntry_Record importRecord)
{
importRecord.setI_IsImported(X_I_Replenish.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
@Builder
@Getter
@ToString
private static class ImportState
{
@NonNull
private final DataEntrySubTab subTab;
@NonNull
private final DataEntryRecord dataEntryRecord;
@NonNull
private final UserId updatedBy;
public boolean isMatching(
@NonNull final TableRecordReference recordRef,
@NonNull final DataEntrySubTabId subTabId)
{
return dataEntryRecord.getMainRecord().equals(recordRef)
&& dataEntryRecord.getDataEntrySubTabId().equals(subTabId);
}
public void setFieldValue(final DataEntryFieldId fieldId, final Object value)
{
final Object valueConv = convertValueToFieldType(value, fieldId);
dataEntryRecord.setRecordField(fieldId, updatedBy, valueConv);
}
private Object convertValueToFieldType(final Object value, @NonNull final DataEntryFieldId fieldId)
{
|
final DataEntryField field = subTab.getFieldById(fieldId);
try
{
return DataEntryRecordField.convertValueToFieldType(value, field);
}
catch (Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.setParameter("field", field)
.appendParametersToMessage();
}
}
public boolean isNewDataEntryRecord()
{
return !dataEntryRecord.getId().isPresent();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\impexp\DataEntryRecordsImportProcess.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void createPPOrderInTrx(
@NonNull final PPOrderAllocator allocator,
@NonNull final PPOrderCandidateProcessRequest ppOrderCandidateProcessRequest)
{
final Consumer<Runnable> runInTrx = createEachPPOrderInOwnTrx
? trxManager::runInNewTrx
: trxManager::runInThreadInheritedTrx;
runInTrx.accept(() ->
{
final PPOrderCreateRequest request = allocator.getPPOrderCreateRequest();
final I_PP_Order ppOrder = ppOrderService.createOrder(request);
createPPOrderAllocations(ppOrder,
allocator.getPpOrderCand2AllocatedQty(),
ppOrderCandidateProcessRequest.isAutoProcessCandidatesAfterProduction(),
ppOrderCandidateProcessRequest.isAutoCloseCandidatesAfterProduction());
ppOrderService.postPPOrderCreatedEvent(ppOrder);
if (shouldCompletePPOrder(request.getProductPlanningId(), ppOrderCandidateProcessRequest.getIsDocCompleteOverride()))
{
ppOrderService.completeDocument(ppOrder);
}
result.addOrder(ppOrder);
ppOrderUserNotificationsProducer.notifyGenerated(ppOrder);
});
}
private void createPPOrderAllocations(
@NonNull final I_PP_Order ppOrder,
@NonNull final Map<PPOrderCandidateId, Quantity> ppOrderCand2QtyToAllocate,
final boolean autoProcessCandidatesAfterProduction,
final boolean autoCloseCandidatesAfterProduction)
{
ppOrderCand2QtyToAllocate.forEach((candidateId, quantity) -> {
ppOrderCandidatesDAO.createProductionOrderAllocation(candidateId, ppOrder, quantity);
ppOrderCandidateService.updateOrderCandidateAfterCommit(PPOrderCandidateUpdateFlagsRequest.builder()
.ppOrderCandidateId(candidateId)
.forceMarkProcessed(autoProcessCandidatesAfterProduction)
.forceClose(autoCloseCandidatesAfterProduction)
|
.build());
});
}
private boolean shouldCompletePPOrder(@Nullable final ProductPlanningId planningId, @Nullable final Boolean completeDocOverride)
{
if (completeDocOverride != null)
{
return completeDocOverride;
}
if (planningId == null)
{
return false;
}
return productPlanningCache.computeIfAbsent(planningId, productPlanningsRepo::getById)
.isDocComplete();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\service\produce\PPOrderProducerFromCandidate.java
| 2
|
请完成以下Java代码
|
public ResponseEntity<String> setExportStatus(@RequestBody @NonNull final JsonRequestSetOrdersExportStatusBulk request)
{
try (final MDC.MDCCloseable ignore = MDC.putCloseable("TransactionIdAPI", request.getTransactionKey()))
{
manufacturingOrderAPIService.setExportStatus(request);
return ResponseEntity.accepted().body("Manufacturing orders updated");
}
}
@PostMapping("/report")
public ResponseEntity<JsonResponseManufacturingOrdersReport> report(@RequestBody @NonNull final JsonRequestManufacturingOrdersReport request)
{
final JsonResponseManufacturingOrdersReport response = manufacturingOrderAPIService.report(request);
return response.isOK()
? ResponseEntity.ok(response)
: ResponseEntity.unprocessableEntity().body(response);
}
@GetMapping("/{ppOrderMetasfreshId}")
|
public ResponseEntity<?> getManufacturingOrderByMetasfreshId(@PathVariable("ppOrderMetasfreshId") final int ppOrderMetasfreshId)
{
try
{
final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrderMetasfreshId);
final JsonResponseManufacturingOrder response = manufacturingOrderAPIService.retrievePPOrder(ppOrderId);
return ResponseEntity.ok(response);
}
catch (final Exception ex)
{
return ResponseEntity
.status(HttpStatus.UNPROCESSABLE_ENTITY)
.body(ex);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v2\ManufacturingOrderRestController.java
| 1
|
请完成以下Java代码
|
public String getRefNb() {
return refNb;
}
/**
* Sets the value of the refNb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRefNb(String value) {
this.refNb = value;
}
/**
* Gets the value of the dt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDt() {
return dt;
}
/**
* Sets the value of the dt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDt(XMLGregorianCalendar value) {
this.dt = value;
}
/**
* Gets the value of the rmtdAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getRmtdAmt() {
return rmtdAmt;
}
/**
* Sets the value of the rmtdAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setRmtdAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.rmtdAmt = value;
}
/**
* Gets the value of the fmlyMdclInsrncInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isFmlyMdclInsrncInd() {
|
return fmlyMdclInsrncInd;
}
/**
* Sets the value of the fmlyMdclInsrncInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setFmlyMdclInsrncInd(Boolean value) {
this.fmlyMdclInsrncInd = value;
}
/**
* Gets the value of the mplyeeTermntnInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isMplyeeTermntnInd() {
return mplyeeTermntnInd;
}
/**
* Sets the value of the mplyeeTermntnInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setMplyeeTermntnInd(Boolean value) {
this.mplyeeTermntnInd = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\Garnishment1.java
| 1
|
请完成以下Java代码
|
public void delete() {
if (commandExecutor != null) {
commandExecutor.execute(new DeleteHistoricDecisionExecutionsByQueryCmd(this));
} else {
new DeleteHistoricDecisionExecutionsByQueryCmd(this).execute(Context.getCommandContext());
}
}
@Override
@Deprecated
public void deleteWithRelatedData() {
delete();
}
// getters ////////////////////////////////////////////
@Override
public String getId() {
return id;
}
public Set<String> getIds() {
return ids;
}
public String getDecisionDefinitionId() {
return decisionDefinitionId;
}
public String getDeploymentId() {
return deploymentId;
}
public String getDecisionKey() {
return decisionKey;
}
public String getInstanceId() {
return instanceId;
}
public String getExecutionId() {
return executionId;
}
public String getActivityId() {
return activityId;
}
|
public String getScopeType() {
return scopeType;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
public String getProcessInstanceIdWithChildren() {
return processInstanceIdWithChildren;
}
public String getCaseInstanceIdWithChildren() {
return caseInstanceIdWithChildren;
}
public Boolean getFailed() {
return failed;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\HistoricDecisionExecutionQueryImpl.java
| 1
|
请完成以下Java代码
|
protected long calculateBackoffTime() {
long backoffTime = 0;
if (backoffLevel <= 0) {
backoffTime = 0;
} else if (backoffLevel >= maxBackoffLevel) {
backoffTime = maxBackoffWaitTime;
}
else {
backoffTime = (long) (baseBackoffWaitTime * Math.pow(backoffIncreaseFactor, backoffLevel - 1));
}
if (applyJitter) {
// add a bounded random jitter to avoid multiple job acquisitions getting exactly the same
// polling interval
backoffTime += Math.random() * (backoffTime / 2);
|
}
return backoffTime;
}
@Override
public int getNumJobsToAcquire(String processEngine) {
Integer numJobsToAcquire = jobsToAcquire.get(processEngine);
if (numJobsToAcquire != null) {
return numJobsToAcquire;
}
else {
return baseNumJobsToAcquire;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\BackoffJobAcquisitionStrategy.java
| 1
|
请完成以下Java代码
|
public void sendMessageUsingThymeleafTemplate(
String to, String subject, Map<String, Object> templateModel)
throws MessagingException {
Context thymeleafContext = new Context();
thymeleafContext.setVariables(templateModel);
String htmlBody = thymeleafTemplateEngine.process("template-thymeleaf.html", thymeleafContext);
sendHtmlMessage(to, subject, htmlBody);
}
@Override
public void sendMessageUsingFreemarkerTemplate(
String to, String subject, Map<String, Object> templateModel)
throws IOException, TemplateException, MessagingException {
Template freemarkerTemplate = freemarkerConfigurer.getConfiguration().getTemplate("template-freemarker.ftl");
String htmlBody = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerTemplate, templateModel);
sendHtmlMessage(to, subject, htmlBody);
|
}
private void sendHtmlMessage(String to, String subject, String htmlBody) throws MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(NOREPLY_ADDRESS);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlBody, true);
helper.addInline("attachment.png", resourceFile);
emailSender.send(message);
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\mail\EmailServiceImpl.java
| 1
|
请完成以下Java代码
|
private CurrencyPrecision getPrecision()
{
if (_precision == null)
{
_precision = currencyDAO.getStdPrecision(getCurrencyId());
}
return _precision;
}
public GLDistributionBuilder setAmountToDistribute(final BigDecimal amountToDistribute)
{
_amountToDistribute = amountToDistribute;
return this;
}
private BigDecimal getAmountToDistribute()
{
Check.assumeNotNull(_amountToDistribute, "amountToDistribute not null");
return _amountToDistribute;
}
public GLDistributionBuilder setAmountSign(@NonNull final Sign amountSign)
{
_amountSign = amountSign;
return this;
}
private Sign getAmountSign()
{
Check.assumeNotNull(_amountSign, "amountSign not null");
return _amountSign;
}
public GLDistributionBuilder setQtyToDistribute(final BigDecimal qtyToDistribute)
{
_qtyToDistribute = qtyToDistribute;
|
return this;
}
private BigDecimal getQtyToDistribute()
{
Check.assumeNotNull(_qtyToDistribute, "qtyToDistribute not null");
return _qtyToDistribute;
}
public GLDistributionBuilder setAccountDimension(final AccountDimension accountDimension)
{
_accountDimension = accountDimension;
return this;
}
private AccountDimension getAccountDimension()
{
Check.assumeNotNull(_accountDimension, "_accountDimension not null");
return _accountDimension;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gldistribution\GLDistributionBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PostController {
private Result result;
private Logger logger = Logger.getLogger(PostController.class.getName());
private PostDao postDao;
private UserInfo userInfo;
private Validator validator;
public PostController() {}
@Inject
public PostController(Result result, PostDao postDao, UserInfo userInfo, Validator validator) {
this.result = result;
this.postDao = postDao;
this.userInfo = userInfo;
this.validator = validator;
}
@Get("/post/add")
public void addForm() {
if(Objects.isNull(userInfo.getUser())) {
result.include("error", "Please Login to Proceed");
result.redirectTo(AuthController.class).loginForm();
return;
}
result.use(FreemarkerView.class).withTemplate("posts/add");
}
@br.com.caelum.vraptor.Post("/post/add")
public void add(Post post) {
post.setAuthor(userInfo.getUser());
validator.validate(post);
if(validator.hasErrors())
|
result.include("errors", validator.getErrors());
validator.onErrorRedirectTo(this).addForm();
Object id = postDao.add(post);
if(Objects.nonNull(id)) {
result.include("status", "Post Added Successfully");
result.redirectTo(IndexController.class).index();
} else {
result.include(
"error", "There was an error creating the post. Try Again");
result.redirectTo(this).addForm();
}
}
@Get("/posts/{id}")
public void view(int id) {
result.include("post", postDao.findById(id));
result.use(FreemarkerView.class).withTemplate("view");
}
}
|
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\controllers\PostController.java
| 2
|
请完成以下Java代码
|
public final IHUAttributeTransferStrategy retrieveTransferStrategy()
{
final Properties ctx = InterfaceWrapperHelper.getCtx(huPIAttribute);
final int adJavaClassId = huPIAttribute.getHU_TansferStrategy_JavaClass_ID();
return attributeStrategyFactory.retrieveStrategy(ctx, adJavaClassId, IHUAttributeTransferStrategy.class);
}
@Override
public final boolean isUseInASI()
{
return huPIAttribute.isUseInASI();
}
@Override
public final boolean isDefinedByTemplate()
{
if (_definedByTemplate == null)
{
synchronized (this)
{
if (_definedByTemplate == null)
{
_definedByTemplate = Services.get(IHUPIAttributesDAO.class).isTemplateAttribute(huPIAttribute);
}
}
}
return _definedByTemplate;
}
public final I_M_HU_PI_Attribute getM_HU_PI_Attribute()
{
return huPIAttribute;
}
@Override
public final I_C_UOM getC_UOM()
{
final int uomId = huPIAttribute.getC_UOM_ID();
if (uomId > 0)
{
return Services.get(IUOMDAO.class).getById(uomId);
}
else
{
// fallback to M_Attribute's UOM
|
return super.getC_UOM();
}
}
@Override
public final boolean isReadonlyUI()
{
return huPIAttribute.isReadOnly();
}
@Override
public final boolean isDisplayedUI()
{
return huPIAttribute.isDisplayed();
}
@Override
public final boolean isMandatory()
{
return huPIAttribute.isMandatory();
}
@Override
public final int getDisplaySeqNo()
{
final int seqNo = huPIAttribute.getSeqNo();
if (seqNo > 0)
{
return seqNo;
}
// Fallback: if SeqNo was not set, return max int (i.e. show them last)
return Integer.MAX_VALUE;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return huPIAttribute.isOnlyIfInProductAttributeSet();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\AbstractHUAttributeValue.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
datasource:
initialize: true
driver-class-name: org.h2.Driver
url: jdbc:h2:~/mybatisplus;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE;
username: "sa"
sql:
init:
schema-locations: classpath:db/schema-h2.sql
data-locations: classpath:db/data-h2.sql
mode: always
myba
|
tis-plus:
global-config:
db-config:
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
|
repos\tutorials-master\mybatis-plus\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public class ProcessDefinitionDto {
protected String id;
protected String name;
protected String key;
protected long version;
protected List<String> calledFromActivityIds;
protected int failedJobs;
public ProcessDefinitionDto() {}
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 getKey() {
return key;
}
public void setKey(String key) {
|
this.key = key;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public List<String> getCalledFromActivityIds() {
return calledFromActivityIds;
}
public void setCalledFromActivityIds(List<String> calledFromActivityIds) {
this.calledFromActivityIds = calledFromActivityIds;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\ProcessDefinitionDto.java
| 1
|
请完成以下Spring Boot application配置
|
soul:
# Soul 针对 SpringMVC 的配置项,对应 SoulHttpConfig 配置类
http:
admin-url: http://127.0.0.1:9095 # Soul Admin 地址
context-path: /sb-demo-api # 设置在 Soul 网关的路由前缀,例如说 /order、/product 等等。
# 后续,网关会根据该 context-path 来进行路由
app-name: sb-de
|
mo-service # 应用名。未配置情况下,默认使用 `spring.application.name` 配置项
zookeeper-url: 127.0.0.1:2181 # 使用 Zookeeper 作为注册中心的地址
|
repos\SpringBoot-Labs-master\lab-60\lab-60-soul-spring-boot-demo\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public void setAD_Window_ID (final int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Window_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Window_ID, AD_Window_ID);
}
@Override
public int getAD_Window_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Window_ID);
}
@Override
public void setErrorMsg (final @Nullable java.lang.String ErrorMsg)
{
set_Value (COLUMNNAME_ErrorMsg, ErrorMsg);
}
@Override
public java.lang.String getErrorMsg()
{
return get_ValueAsString(COLUMNNAME_ErrorMsg);
}
@Override
public void setIsProcessing (final boolean IsProcessing)
{
set_Value (COLUMNNAME_IsProcessing, IsProcessing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_IsProcessing);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
|
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setResult (final int Result)
{
set_Value (COLUMNNAME_Result, Result);
}
@Override
public int getResult()
{
return get_ValueAsInt(COLUMNNAME_Result);
}
@Override
public void setWhereClause (final @Nullable java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
@Override
public java.lang.String getWhereClause()
{
return get_ValueAsString(COLUMNNAME_WhereClause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance.java
| 1
|
请完成以下Java代码
|
public void setPriceActual (java.math.BigDecimal PriceActual)
{
set_Value (COLUMNNAME_PriceActual, PriceActual);
}
/** Get Einzelpreis.
@return Actual Price
*/
@Override
public java.math.BigDecimal getPriceActual ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
|
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RequisitionLine.java
| 1
|
请完成以下Java代码
|
public Details build() {
return new Details(this);
}
}
public String getName() {
return name;
}
public String getLockOwner() {
return lockOwner;
}
public int getLockTimeInMillis() {
return lockTimeInMillis;
}
public int getMaxJobsPerAcquisition() {
return maxJobsPerAcquisition;
}
public int getWaitTimeInMillis() {
|
return waitTimeInMillis;
}
public Set<String> getProcessEngineNames() {
return processEngineNames;
}
@Override
public String toString() {
return "Details [name=" + name + ", lockOwner=" + lockOwner + ", lockTimeInMillis="
+ lockTimeInMillis + ", maxJobsPerAcquisition=" + maxJobsPerAcquisition
+ ", waitTimeInMillis=" + waitTimeInMillis + ", processEngineNames=" + processEngineNames
+ "]";
}
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\actuator\JobExecutorHealthIndicator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PmsPortalProductController {
@Autowired
private PmsPortalProductService portalProductService;
@ApiOperation(value = "综合搜索、筛选、排序")
@ApiImplicitParam(name = "sort", value = "排序字段:0->按相关度;1->按新品;2->按销量;3->价格从低到高;4->价格从高到低",
defaultValue = "0", allowableValues = "0,1,2,3,4", paramType = "query", dataType = "integer")
@RequestMapping(value = "/search", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<PmsProduct>> search(@RequestParam(required = false) String keyword,
@RequestParam(required = false) Long brandId,
@RequestParam(required = false) Long productCategoryId,
@RequestParam(required = false, defaultValue = "0") Integer pageNum,
@RequestParam(required = false, defaultValue = "5") Integer pageSize,
@RequestParam(required = false, defaultValue = "0") Integer sort) {
List<PmsProduct> productList = portalProductService.search(keyword, brandId, productCategoryId, pageNum, pageSize, sort);
return CommonResult.success(CommonPage.restPage(productList));
|
}
@ApiOperation("以树形结构获取所有商品分类")
@RequestMapping(value = "/categoryTreeList", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<PmsProductCategoryNode>> categoryTreeList() {
List<PmsProductCategoryNode> list = portalProductService.categoryTreeList();
return CommonResult.success(list);
}
@ApiOperation("获取前台商品详情")
@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<PmsPortalProductDetail> detail(@PathVariable Long id) {
PmsPortalProductDetail productDetail = portalProductService.detail(id);
return CommonResult.success(productDetail);
}
}
|
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\PmsPortalProductController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class BuildSearchIndex
implements ApplicationListener<ApplicationReadyEvent> {
// ------------------------
// PRIVATE FIELDS
// ------------------------
@PersistenceContext
private EntityManager entityManager;
// ------------------------
// PUBLIC METHODS
// ------------------------
/**
* Create an initial Lucene index for the data already present in the
* database.
* This method is called when Spring's startup.
*/
|
@Override
public void onApplicationEvent(final ApplicationReadyEvent event) {
try {
FullTextEntityManager fullTextEntityManager =
Search.getFullTextEntityManager(entityManager);
fullTextEntityManager.createIndexer().startAndWait();
}
catch (InterruptedException e) {
System.out.println(
"An error occurred trying to build the serach index: " +
e.toString());
}
return;
}
} // class
|
repos\spring-boot-samples-master\spring-boot-hibernate-search\src\main\java\netgloo\BuildSearchIndex.java
| 2
|
请完成以下Java代码
|
public static CloseableHttpClient setTlsVersionPerConnection() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) {
@Override
protected void prepareSocket(SSLSocket socket) {
String hostname = socket.getInetAddress()
.getHostName();
if (hostname.endsWith("internal.system.com")) {
socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" });
} else {
socket.setEnabledProtocols(new String[] { "TLSv1.3" });
}
}
};
HttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslsf)
.build();
return HttpClients.custom()
.setConnectionManager(connManager)
.build();
|
}
// To configure the TLS versions for the client, set the https.protocols system property during runtime.
// For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar
public static CloseableHttpClient setViaSystemProperties() {
return HttpClients.createSystem();
// Alternatively:
//return HttpClients.custom().useSystemProperties().build();
}
public static void main(String[] args) throws IOException {
try (CloseableHttpClient httpClient = setViaSocketFactory(); CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
}
}
|
repos\tutorials-master\apache-httpclient-2\src\main\java\com\baeldung\tlsversion\ClientTlsVersionExamples.java
| 1
|
请完成以下Java代码
|
public void addKeyListener(final KeyListener l)
{
m_text.addKeyListener(l);
}
public int getCaretPosition()
{
return m_text.getCaretPosition();
}
public void setCaretPosition(final int position)
{
m_text.setCaretPosition(position);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
@Override
protected final boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, final int condition, final boolean pressed)
{
// Forward all key events on this component to the text field.
|
// We have to do this for the case when we are embedding this editor in a JTable and the JTable is forwarding the key strokes to editing component.
// Effect of NOT doing this: when in JTable, user presses a key (e.g. a digit) to start editing but the first key he pressed gets lost here.
if (m_text != null && condition == WHEN_FOCUSED)
{
if (m_text.processKeyBinding(ks, e, condition, pressed))
{
return true;
}
}
//
// Fallback to super
return super.processKeyBinding(ks, e, condition, pressed);
}
} // VDate
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VDate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public long contentLength() throws IOException {
return requestBody.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink bufferedSink = Okio.buffer(sink(sink));
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
long bytesWritten = 0L;
|
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength == 0) {
contentLength = contentLength();
}
bytesWritten += byteCount;
progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength);
}
};
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\ProgressRequestBody.java
| 2
|
请完成以下Java代码
|
private static final class DefaultOAuth2DeviceAuthorizationResponseMapConverter
implements Converter<OAuth2DeviceAuthorizationResponse, Map<String, Object>> {
@Override
public Map<String, Object> convert(OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse) {
Map<String, Object> parameters = new HashMap<>();
parameters.put(OAuth2ParameterNames.DEVICE_CODE,
deviceAuthorizationResponse.getDeviceCode().getTokenValue());
parameters.put(OAuth2ParameterNames.USER_CODE, deviceAuthorizationResponse.getUserCode().getTokenValue());
parameters.put(OAuth2ParameterNames.VERIFICATION_URI, deviceAuthorizationResponse.getVerificationUri());
if (StringUtils.hasText(deviceAuthorizationResponse.getVerificationUriComplete())) {
parameters.put(OAuth2ParameterNames.VERIFICATION_URI_COMPLETE,
deviceAuthorizationResponse.getVerificationUriComplete());
}
parameters.put(OAuth2ParameterNames.EXPIRES_IN, getExpiresIn(deviceAuthorizationResponse));
if (deviceAuthorizationResponse.getInterval() > 0) {
parameters.put(OAuth2ParameterNames.INTERVAL, deviceAuthorizationResponse.getInterval());
}
if (!CollectionUtils.isEmpty(deviceAuthorizationResponse.getAdditionalParameters())) {
parameters.putAll(deviceAuthorizationResponse.getAdditionalParameters());
|
}
return parameters;
}
private static long getExpiresIn(OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse) {
if (deviceAuthorizationResponse.getDeviceCode().getExpiresAt() != null) {
Instant issuedAt = (deviceAuthorizationResponse.getDeviceCode().getIssuedAt() != null)
? deviceAuthorizationResponse.getDeviceCode().getIssuedAt() : Instant.now();
return ChronoUnit.SECONDS.between(issuedAt, deviceAuthorizationResponse.getDeviceCode().getExpiresAt());
}
return -1;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\http\converter\OAuth2DeviceAuthorizationResponseHttpMessageConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class SecurityConfig {
private final KeycloakLogoutHandler keycloakLogoutHandler;
SecurityConfig(KeycloakLogoutHandler keycloakLogoutHandler) {
this.keycloakLogoutHandler = keycloakLogoutHandler;
}
@Bean
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Order(1)
@Bean
public SecurityFilterChain clientFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers(new AntPathRequestMatcher("/"))
.permitAll()
.anyRequest()
.authenticated());
http.oauth2Login(Customizer.withDefaults())
.logout(logout -> logout.addLogoutHandler(keycloakLogoutHandler)
.logoutSuccessUrl("/"));
|
return http.build();
}
@Order(2)
@Bean
public SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers(new AntPathRequestMatcher("/customers*", "/users*"))
.hasRole("USER")
.anyRequest()
.authenticated());
http.oauth2ResourceServer((oauth2) -> oauth2
.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.build();
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-adapters\src\main\java\com\baeldung\keycloak\SecurityConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
DefaultDataBufferFactory dataBufferFactory() {
return new DefaultDataBufferFactory();
}
@Bean
@ConditionalOnMissingBean(ReactiveGridFsOperations.class)
ReactiveGridFsTemplate reactiveGridFsTemplate(DataMongoProperties dataProperties,
ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory, MappingMongoConverter mappingMongoConverter,
DataBufferFactory dataBufferFactory) {
return new ReactiveGridFsTemplate(dataBufferFactory,
new GridFsReactiveMongoDatabaseFactory(reactiveMongoDatabaseFactory, dataProperties),
mappingMongoConverter, dataProperties.getGridfs().getBucket());
}
/**
* {@link ReactiveMongoDatabaseFactory} decorator to use {@link Gridfs#getDatabase()}
* from the {@link MongoProperties} when set.
*/
static class GridFsReactiveMongoDatabaseFactory implements ReactiveMongoDatabaseFactory {
private final ReactiveMongoDatabaseFactory delegate;
private final DataMongoProperties properties;
GridFsReactiveMongoDatabaseFactory(ReactiveMongoDatabaseFactory delegate, DataMongoProperties properties) {
this.delegate = delegate;
this.properties = properties;
}
@Override
public boolean hasCodecFor(Class<?> type) {
return this.delegate.hasCodecFor(type);
}
@Override
public Mono<MongoDatabase> getMongoDatabase() throws DataAccessException {
String gridFsDatabase = getGridFsDatabase();
if (StringUtils.hasText(gridFsDatabase)) {
return this.delegate.getMongoDatabase(gridFsDatabase);
}
return this.delegate.getMongoDatabase();
}
private @Nullable String getGridFsDatabase() {
|
return this.properties.getGridfs().getDatabase();
}
@Override
public Mono<MongoDatabase> getMongoDatabase(String dbName) throws DataAccessException {
return this.delegate.getMongoDatabase(dbName);
}
@Override
public <T> Optional<Codec<T>> getCodecFor(Class<T> type) {
return this.delegate.getCodecFor(type);
}
@Override
public PersistenceExceptionTranslator getExceptionTranslator() {
return this.delegate.getExceptionTranslator();
}
@Override
public CodecRegistry getCodecRegistry() {
return this.delegate.getCodecRegistry();
}
@Override
public Mono<ClientSession> getSession(ClientSessionOptions options) {
return this.delegate.getSession(options);
}
@Override
public ReactiveMongoDatabaseFactory withSession(ClientSession session) {
return this.delegate.withSession(session);
}
@Override
public boolean isTransactionActive() {
return this.delegate.isTransactionActive();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoReactiveAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public @Nullable Integer getIdle() {
try {
return getDataSource().getAvailableConnectionsCount();
}
catch (SQLException ex) {
return null;
}
}
@Override
public @Nullable Integer getMax() {
return getDataSource().getMaxPoolSize();
}
@Override
|
public @Nullable Integer getMin() {
return getDataSource().getMinPoolSize();
}
@Override
public @Nullable String getValidationQuery() {
return getDataSource().getSQLForValidateConnection();
}
@Override
public @Nullable Boolean getDefaultAutoCommit() {
String autoCommit = getDataSource().getConnectionProperty("autoCommit");
return StringUtils.hasText(autoCommit) ? Boolean.valueOf(autoCommit) : null;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\metadata\OracleUcpDataSourcePoolMetadata.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public BigDecimal getOrderPrice() {
return orderPrice;
}
public void setOrderPrice(BigDecimal orderPrice) {
this.orderPrice = orderPrice;
}
public String getOrderIp() {
return orderIp;
}
public void setOrderIp(String orderIp) {
this.orderIp = orderIp;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
|
}
public String getPayType() {
return payType;
}
public void setPayType(String payType) {
this.payType = payType;
}
public String getAuthCode() {
return authCode;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
@Override
public String toString() {
return "F2FPayRequestBo{" +
"payKey='" + payKey + '\'' +
", authCode='" + authCode + '\'' +
", productName='" + productName + '\'' +
", orderNo='" + orderNo + '\'' +
", orderPrice=" + orderPrice +
", orderIp='" + orderIp + '\'' +
", orderDate='" + orderDate + '\'' +
", orderTime='" + orderTime + '\'' +
", sign='" + sign + '\'' +
", remark='" + remark + '\'' +
", payType='" + payType + '\'' +
'}';
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\F2FPayRequestBo.java
| 2
|
请完成以下Java代码
|
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy strategy) {
this.securityContextHolderStrategy = strategy;
this.empty = this.securityContextHolderStrategy.createEmptyContext();
}
/**
* Configure an Authentication used for anonymous authentication. Default is: <pre>
* new AnonymousAuthenticationToken("key", "anonymous",
* AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
* </pre>
* @param authentication the Authentication used for anonymous authentication. Cannot
* be null.
*/
public void setAnonymousAuthentication(Authentication authentication) {
Assert.notNull(authentication, "authentication cannot be null");
this.anonymous = authentication;
}
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
if (authentication == null) {
authentication = this.anonymous;
}
return MessageBuilder.fromMessage(message).setHeader(this.authenticationHeaderName, authentication).build();
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
return postReceive(message, channel);
}
@Override
public Message<?> postReceive(Message<?> message, MessageChannel channel) {
setup(message);
return message;
}
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler,
@Nullable Exception ex) {
cleanup();
}
private void setup(Message<?> message) {
Authentication authentication = message.getHeaders().get(this.authenticationHeaderName, Authentication.class);
|
SecurityContext currentContext = this.securityContextHolderStrategy.getContext();
Stack<SecurityContext> contextStack = originalContext.get();
if (contextStack == null) {
contextStack = new Stack<>();
originalContext.set(contextStack);
}
contextStack.push(currentContext);
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
this.securityContextHolderStrategy.setContext(context);
}
private void cleanup() {
Stack<SecurityContext> contextStack = originalContext.get();
if (contextStack == null || contextStack.isEmpty()) {
this.securityContextHolderStrategy.clearContext();
originalContext.remove();
return;
}
SecurityContext context = contextStack.pop();
try {
if (this.empty.equals(context)) {
this.securityContextHolderStrategy.clearContext();
originalContext.remove();
}
else {
this.securityContextHolderStrategy.setContext(context);
}
}
catch (Throwable ex) {
this.securityContextHolderStrategy.clearContext();
}
}
}
|
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\context\SecurityContextPropagationChannelInterceptor.java
| 1
|
请完成以下Java代码
|
public Timestamp getDateAcct ()
{
return (Timestamp)get_Value(COLUMNNAME_DateAcct);
}
/** Set Depreciate.
@param IsDepreciated
The asset will be depreciated
*/
public void setIsDepreciated (boolean IsDepreciated)
{
set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated));
}
/** Get Depreciate.
@return The asset will be depreciated
*/
public boolean isDepreciated ()
{
Object oo = get_Value(COLUMNNAME_IsDepreciated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
|
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Workfile.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<?> stop(@PathVariable(name = "requestId", required = true) String requestId) {
return chatService.stop(requestId);
}
/**
* 上传文件
* for [QQYUN-12135]AI聊天,上传图片提示非法token
*
* @param request
* @param response
* @return
* @throws Exception
* @author chenrui
* @date 2025/4/25 11:04
*/
@IgnoreAuth
@PostMapping(value = "/upload")
public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
String bizPath = "airag";
|
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获取上传文件对象
MultipartFile file = multipartRequest.getFile("file");
String savePath;
if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) {
savePath = CommonUtils.uploadLocal(file, bizPath, uploadpath);
} else {
savePath = CommonUtils.upload(file, bizPath, uploadType);
}
Result<?> result = new Result<>();
result.setMessage(savePath);
result.setSuccess(true);
return result;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\controller\AiragChatController.java
| 2
|
请完成以下Java代码
|
public Long getLongValue() {
JsonNode longNode = node.path("longValue");
if (longNode.isNumber()) {
return longNode.longValue();
}
return null;
}
@Override
public void setLongValue(Long longValue) {
throw new UnsupportedOperationException("Not supported to set long value");
}
@Override
public Double getDoubleValue() {
JsonNode doubleNode = node.path("doubleValue");
if (doubleNode.isNumber()) {
return doubleNode.doubleValue();
}
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {
throw new UnsupportedOperationException("Not supported to set double value");
}
@Override
public byte[] getBytes() {
throw new UnsupportedOperationException("Not supported to get bytes");
}
|
@Override
public void setBytes(byte[] bytes) {
throw new UnsupportedOperationException("Not supported to set bytes");
}
@Override
public Object getCachedValue() {
throw new UnsupportedOperationException("Not supported to set get cached value");
}
@Override
public void setCachedValue(Object cachedValue) {
throw new UnsupportedOperationException("Not supported to set cached value");
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delete\BatchDeleteCaseConfig.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setSUMUP_CardReader_ID (final int SUMUP_CardReader_ID)
{
if (SUMUP_CardReader_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_CardReader_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SUMUP_CardReader_ID, SUMUP_CardReader_ID);
}
@Override
public int getSUMUP_CardReader_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_CardReader_ID);
}
@Override
public de.metas.payment.sumup.repository.model.I_SUMUP_Config getSUMUP_Config()
{
return get_ValueAsPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class);
}
@Override
public void setSUMUP_Config(final de.metas.payment.sumup.repository.model.I_SUMUP_Config SUMUP_Config)
{
set_ValueFromPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class, SUMUP_Config);
|
}
@Override
public void setSUMUP_Config_ID (final int SUMUP_Config_ID)
{
if (SUMUP_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID);
}
@Override
public int getSUMUP_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_CardReader.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Result<?> queryPageList(SysMessage sysMessage, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
QueryWrapper<SysMessage> queryWrapper = QueryGenerator.initQueryWrapper(sysMessage, req.getParameterMap());
Page<SysMessage> page = new Page<SysMessage>(pageNo, pageSize);
IPage<SysMessage> pageList = sysMessageService.page(page, queryWrapper);
return Result.ok(pageList);
}
/**
* 添加
*
* @param sysMessage
* @return
*/
@PostMapping(value = "/add")
public Result<?> add(@RequestBody SysMessage sysMessage) {
sysMessageService.save(sysMessage);
return Result.ok("添加成功!");
}
/**
* 编辑
*
* @param sysMessage
* @return
*/
@PutMapping(value = "/edit")
public Result<?> edit(@RequestBody SysMessage sysMessage) {
sysMessageService.updateById(sysMessage);
return Result.ok("修改成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
sysMessageService.removeById(id);
return Result.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@DeleteMapping(value = "/deleteBatch")
|
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysMessageService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
SysMessage sysMessage = sysMessageService.getById(id);
return Result.ok(sysMessage);
}
/**
* 导出excel
*
* @param request
*/
@GetMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysMessage sysMessage) {
return super.exportXls(request,sysMessage,SysMessage.class, "推送消息模板");
}
/**
* excel导入
*
* @param request
* @param response
* @return
*/
@PostMapping(value = "/importExcel")
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysMessage.class);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\controller\SysMessageController.java
| 2
|
请完成以下Java代码
|
public void setM_HU_Storage_ID (final int M_HU_Storage_ID)
{
if (M_HU_Storage_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Storage_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_Storage_ID, M_HU_Storage_ID);
}
@Override
public int getM_HU_Storage_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Storage_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
|
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Storage.java
| 1
|
请完成以下Java代码
|
public class SingletonScriptScanner extends AbstractScriptScanner
{
private final IFileRef fileRef;
private IScript script;
private boolean consumed = false;
/**
*
* @param fileRef
* @throws ScriptException if the given <code>fileRef</code> is not a regular file.
*/
public SingletonScriptScanner(final IFileRef fileRef)
{
super(fileRef.getScriptScanner());
this.fileRef = fileRef;
// make sure the file exists and is a regular file
if (!fileRef.getFile().exists())
{
throw new ScriptException("Script file doesn't exist: " + fileRef.getFileName());
}
if (!fileRef.getFile().isFile())
{
throw new ScriptException("Script file is not a regular file: " + fileRef.getFileName());
}
}
public SingletonScriptScanner(final IScript script)
{
super(null);
this.fileRef = null;
this.script = script;
}
@Override
|
public boolean hasNext()
{
return !consumed;
}
@Override
public IScript next()
{
if (consumed)
{
throw new NoSuchElementException();
}
consumed = true;
return getScript();
}
private IScript getScript()
{
if (script == null)
{
final IScriptFactory scriptFactory = getScriptFactoryToUse();
script = scriptFactory.createScript(fileRef);
}
return script;
}
@Override
public String toString()
{
return "SingletonScriptScanner [fileRef=" + fileRef + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\SingletonScriptScanner.java
| 1
|
请完成以下Java代码
|
public void putValue(
@NonNull final String dataSetName,
@NonNull final KPIDataSetValuesAggregationKey dataSetValueKey,
@NonNull final String fieldName,
@NonNull final KPIDataValue value)
{
dataSet(dataSetName).putValue(dataSetValueKey, fieldName, value);
}
public void putValueIfAbsent(
@NonNull final String dataSetName,
@NonNull final KPIDataSetValuesAggregationKey dataSetValueKey,
@NonNull final String fieldName,
@NonNull final KPIDataValue value)
{
dataSet(dataSetName).putValueIfAbsent(dataSetValueKey, fieldName, value);
}
public Builder error(@NonNull final Exception exception)
|
{
final ITranslatableString errorMessage = AdempiereException.isUserValidationError(exception)
? AdempiereException.extractMessageTrl(exception)
: TranslatableStrings.adMessage(MSG_FailedLoadingKPI);
this.error = WebuiError.of(exception, errorMessage);
return this;
}
public Builder error(@NonNull final ITranslatableString errorMessage)
{
this.error = WebuiError.of(errorMessage);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataResult.java
| 1
|
请完成以下Java代码
|
public boolean isElementEnabled(@NonNull final AcctSchemaElementType elementType)
{
return elementsByType.get(elementType) != null;
}
@Nullable
public AcctSchemaElement getByElementType(@NonNull final AcctSchemaElementType elementType)
{
return elementsByType.get(elementType);
}
public ImmutableSet<AcctSchemaElementType> getElementTypes()
{
return elementsByType.keySet();
}
@Override
public Iterator<AcctSchemaElement> iterator()
{
return elements.iterator();
}
|
public ChartOfAccountsId getChartOfAccountsId()
{
final AcctSchemaElement accountSchemaElement = getByElementType(AcctSchemaElementType.Account);
if (accountSchemaElement == null)
{
throw new AdempiereException("No schema element of type " + AcctSchemaElementType.Account + " found");
}
final ChartOfAccountsId chartOfAccountsId = accountSchemaElement.getChartOfAccountsId();
if (chartOfAccountsId == null)
{
throw new AdempiereException("No Chart of Accounts defined for " + accountSchemaElement);
}
return chartOfAccountsId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AcctSchemaElementsMap.java
| 1
|
请完成以下Java代码
|
public void setFilterOperator (final java.lang.String FilterOperator)
{
set_Value (COLUMNNAME_FilterOperator, FilterOperator);
}
@Override
public java.lang.String getFilterOperator()
{
return get_ValueAsString(COLUMNNAME_FilterOperator);
}
@Override
public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsMandatory (final boolean IsMandatory)
{
set_Value (COLUMNNAME_IsMandatory, IsMandatory);
}
@Override
public boolean isMandatory()
{
return get_ValueAsBoolean(COLUMNNAME_IsMandatory);
}
@Override
public void setIsPartUniqueIndex (final boolean IsPartUniqueIndex)
{
set_Value (COLUMNNAME_IsPartUniqueIndex, IsPartUniqueIndex);
}
@Override
public boolean isPartUniqueIndex()
{
return get_ValueAsBoolean(COLUMNNAME_IsPartUniqueIndex);
}
@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 setPosition (final int Position)
{
set_Value (COLUMNNAME_Position, Position);
}
@Override
|
public int getPosition()
{
return get_ValueAsInt(COLUMNNAME_Position);
}
/**
* Type AD_Reference_ID=53241
* Reference name: EXP_Line_Type
*/
public static final int TYPE_AD_Reference_ID=53241;
/** XML Element = E */
public static final String TYPE_XMLElement = "E";
/** XML Attribute = A */
public static final String TYPE_XMLAttribute = "A";
/** Embedded EXP Format = M */
public static final String TYPE_EmbeddedEXPFormat = "M";
/** Referenced EXP Format = R */
public static final String TYPE_ReferencedEXPFormat = "R";
@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 setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_FormatLine.java
| 1
|
请完成以下Java代码
|
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
|
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Version No.
@param VersionNo
Version Number
*/
public void setVersionNo (String VersionNo)
{
set_Value (COLUMNNAME_VersionNo, VersionNo);
}
/** Get Version No.
@return Version Number
*/
public String getVersionNo ()
{
return (String)get_Value(COLUMNNAME_VersionNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset.java
| 1
|
请完成以下Java代码
|
public DocumentFilterList extractDocumentFilters(@NonNull final CreateViewRequest request)
{
final DocumentFilterDescriptorsProvider provider = getFilterDescriptors();
return request.getFiltersUnwrapped(provider);
}
public IQuery<I_MD_Cockpit> createQuery(@NonNull final DocumentFilterList filters)
{
final IQueryBuilder<I_MD_Cockpit> queryBuilder = createInitialQueryBuilder();
boolean anyRestrictionAdded = false;
if (augmentQueryBuilder(queryBuilder, DateFilterUtil.extractDateFilterVO(filters)))
{
anyRestrictionAdded = true;
}
if (augmentQueryBuilder(queryBuilder, ProductFilterUtil.extractProductFilterVO(filters)))
{
anyRestrictionAdded = true;
}
if (anyRestrictionAdded)
{
final IQuery<I_MD_Cockpit> query = augmentQueryBuilderWithOrderBy(queryBuilder).create();
return query;
}
else
{
// avoid memory problems in case the filters are accidentally empty
return queryBuilder.filter(ConstantQueryFilter.of(false)).create();
}
}
private IQueryBuilder<I_MD_Cockpit> createInitialQueryBuilder()
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_MD_Cockpit> queryBuilder = queryBL
.createQueryBuilder(I_MD_Cockpit.class)
.addOnlyActiveRecordsFilter();
return queryBuilder;
}
private boolean augmentQueryBuilder(final IQueryBuilder<I_MD_Cockpit> queryBuilder, final DateFilterVO dateFilterVO)
{
if (dateFilterVO == null)
{
return false;
}
final LocalDate date = dateFilterVO.getDate();
if (date == null)
{
return false;
}
queryBuilder.addCompareFilter(I_MD_Cockpit.COLUMN_DateGeneral, CompareQueryFilter.Operator.GREATER_OR_EQUAL, date);
queryBuilder.addCompareFilter(I_MD_Cockpit.COLUMN_DateGeneral, CompareQueryFilter.Operator.LESS, date.plusDays(1));
return true;
}
private boolean augmentQueryBuilder(final IQueryBuilder<I_MD_Cockpit> queryBuilder, final ProductFilterVO productFilterVO)
{
final IQuery<I_M_Product> productQuery = ProductFilterUtil.createProductQueryOrNull(productFilterVO);
if (productQuery == null)
|
{
return false;
}
queryBuilder.addInSubQueryFilter(I_MD_Cockpit.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, productQuery);
return true;
}
private IQueryBuilder<I_MD_Cockpit> augmentQueryBuilderWithOrderBy(@NonNull final IQueryBuilder<I_MD_Cockpit> queryBuilder)
{
return queryBuilder
.orderByDescending(I_MD_Cockpit.COLUMNNAME_QtyStockEstimateSeqNo_AtDate)
.orderBy(I_MD_Cockpit.COLUMNNAME_DateGeneral)
.orderBy(I_MD_Cockpit.COLUMNNAME_M_Product_ID)
.orderBy(I_MD_Cockpit.COLUMNNAME_AttributesKey);
}
public LocalDate getFilterByDate(@NonNull final DocumentFilterList filters)
{
final DateFilterVO dateFilterVO = DateFilterUtil.extractDateFilterVO(filters);
return dateFilterVO.getDate();
}
public Predicate<I_M_Product> toProductFilterPredicate(@NonNull final DocumentFilterList filters)
{
return ProductFilterUtil.toPredicate(filters);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\filters\MaterialCockpitFilters.java
| 1
|
请完成以下Java代码
|
public int getService_Fee_Invoice_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Fee_Invoice_ID);
}
@Override
public void setServiceFeeVatRate (final @Nullable BigDecimal ServiceFeeVatRate)
{
set_Value (COLUMNNAME_ServiceFeeVatRate, ServiceFeeVatRate);
}
@Override
public BigDecimal getServiceFeeVatRate()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeVatRate);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setService_Product_ID (final int Service_Product_ID)
{
if (Service_Product_ID < 1)
set_Value (COLUMNNAME_Service_Product_ID, null);
else
set_Value (COLUMNNAME_Service_Product_ID, Service_Product_ID);
}
|
@Override
public int getService_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Product_ID);
}
@Override
public void setService_Tax_ID (final int Service_Tax_ID)
{
if (Service_Tax_ID < 1)
set_Value (COLUMNNAME_Service_Tax_ID, null);
else
set_Value (COLUMNNAME_Service_Tax_ID, Service_Tax_ID);
}
@Override
public int getService_Tax_ID()
{
return get_ValueAsInt(COLUMNNAME_Service_Tax_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice_Line.java
| 1
|
请完成以下Java代码
|
public class ApiPredicateItemEntity {
private String pattern;
private Integer matchStrategy;
public ApiPredicateItemEntity() {
}
public ApiPredicateItemEntity(String pattern, int matchStrategy) {
this.pattern = pattern;
this.matchStrategy = matchStrategy;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public Integer getMatchStrategy() {
return matchStrategy;
}
public void setMatchStrategy(Integer matchStrategy) {
this.matchStrategy = matchStrategy;
}
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
ApiPredicateItemEntity that = (ApiPredicateItemEntity) o;
return Objects.equals(pattern, that.pattern) &&
|
Objects.equals(matchStrategy, that.matchStrategy);
}
@Override
public int hashCode() {
return Objects.hash(pattern, matchStrategy);
}
@Override
public String toString() {
return "ApiPredicateItemEntity{" +
"pattern='" + pattern + '\'' +
", matchStrategy=" + matchStrategy +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\ApiPredicateItemEntity.java
| 1
|
请完成以下Java代码
|
protected void deleteProcessInstance(final CommandContext commandContext, String processInstanceId) {
ensureNotNull(BadUserRequestException.class, "processInstanceId is null", "processInstanceId", processInstanceId);
// fetch process instance
ExecutionManager executionManager = commandContext.getExecutionManager();
final ExecutionEntity execution = executionManager.findExecutionById(processInstanceId);
if(!failIfNotExists && execution == null) {
return;
}
ensureNotNull(NotFoundException.class, "No process instance found for id '" + processInstanceId + "'",
"processInstance", execution);
checkDeleteProcessInstance(execution, commandContext);
// delete process instance
commandContext
.getExecutionManager()
.deleteProcessInstance(processInstanceId, deleteReason, false, skipCustomListeners,
externallyTerminated, skipIoMappings, skipSubprocesses);
if (skipSubprocesses) {
List<ProcessInstance> superProcesslist = commandContext.getProcessEngineConfiguration().getRuntimeService().createProcessInstanceQuery()
.superProcessInstanceId(processInstanceId).list();
triggerHistoryEvent(superProcesslist);
}
final ExecutionEntity superExecution = execution.getSuperExecution();
if (superExecution != null) {
commandContext.runWithoutAuthorization((Callable<Void>) () -> {
ProcessInstanceModificationBuilderImpl builder = (ProcessInstanceModificationBuilderImpl) new ProcessInstanceModificationBuilderImpl(commandContext, superExecution.getProcessInstanceId(), deleteReason)
.cancellationSourceExternal(externallyTerminated).cancelActivityInstance(superExecution.getActivityInstanceId());
builder.execute(false, skipCustomListeners, skipIoMappings);
return null;
});
|
}
// create user operation log
commandContext.getOperationLogManager()
.logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE, processInstanceId,
null, null, Collections.singletonList(PropertyChange.EMPTY_CHANGE));
}
public void triggerHistoryEvent(List<ProcessInstance> subProcesslist) {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
HistoryLevel historyLevel = configuration.getHistoryLevel();
for (final ProcessInstance processInstance : subProcesslist) {
// TODO: This smells bad, as the rest of the history is done via the
// ParseListener
if (historyLevel.isHistoryEventProduced(HistoryEventTypes.PROCESS_INSTANCE_UPDATE, processInstance)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createProcessInstanceUpdateEvt((DelegateExecution) processInstance);
}
});
}
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractDeleteProcessInstanceCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
|
this.decisionKey = decisionKey;
}
public String getDecisionName() {
return decisionName;
}
public void setDecisionName(String decisionName) {
this.decisionName = decisionName;
}
public String getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(String decisionVersion) {
this.decisionVersion = decisionVersion;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\history\HistoricDecisionExecutionResponse.java
| 2
|
请完成以下Java代码
|
public class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory(Strategy strategy) {
return buildSessionFactory(strategy);
}
private static SessionFactory buildSessionFactory(Strategy strategy) {
try {
ServiceRegistry serviceRegistry = configureServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
for (Class<?> entityClass : strategy.getEntityClasses()) {
metadataSources.addAnnotatedClass(entityClass);
}
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()
.build();
} catch (IOException ex) {
|
throw new ExceptionInInitializerError(ex);
}
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\onetoone\HibernateUtil.java
| 1
|
请完成以下Java代码
|
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Override
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@Override
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
|
@Override
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
@Override
public String getDeleteReason() {
return deleteReason;
}
@Override
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricScopeInstanceEntityImpl.java
| 1
|
请完成以下Java代码
|
public float[] scalarNormOfTwoArrays(float[] arr1, float[] arr2) {
float[] finalResult = new float[arr1.length];
for (int i = 0; i < arr1.length; i++) {
finalResult[i] = (float) Math.sqrt(arr1[i] * arr1[i] + arr2[i] * arr2[i]);
}
return finalResult;
}
public float[] vectorNormalForm(float[] arr1, float[] arr2) {
float[] finalResult = new float[arr1.length];
int i = 0;
int upperBound = SPECIES.loopBound(arr1.length);
for (; i < upperBound; i += SPECIES.length()) {
var va = FloatVector.fromArray(PREFERRED_SPECIES, arr1, i);
var vb = FloatVector.fromArray(PREFERRED_SPECIES, arr2, i);
var vc = va.mul(va)
.add(vb.mul(vb))
.sqrt();
vc.intoArray(finalResult, i);
}
// tail cleanup
|
for (; i < arr1.length; i++) {
finalResult[i] = (float) Math.sqrt(arr1[i] * arr1[i] + arr2[i] * arr2[i]);
}
return finalResult;
}
public double averageOfaVector(int[] arr) {
double sum = 0;
for (int i = 0; i < arr.length; i += SPECIES.length()) {
var mask = SPECIES.indexInRange(i, arr.length);
var V = IntVector.fromArray(SPECIES, arr, i, mask);
sum += V.reduceLanes(VectorOperators.ADD, mask);
}
return sum / arr.length;
}
}
|
repos\tutorials-master\core-java-modules\core-java-19\src\main\java\com\baeldung\vectors\VectorAPIExamples.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.