instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public int[] addTwoScalarArrays(int[] arr1, int[] arr2) {
int[] result = new int[arr1.length];
for (int i = 0; i < arr1.length; i++) {
result[i] = arr1[i] + arr2[i];
}
return result;
}
public int[] addTwoVectorArrays(int[] arr1, int[] arr2) {
var v1 = IntVector.fromArray(SPECIES, arr1, 0);
var v2 = IntVector.fromArray(SPECIES, arr2, 0);
var result = v1.add(v2);
return result.toArray();
}
public int[] addTwoVectorsWIthHigherShape(int[] arr1, int[] arr2) {
int[] finalResult = new int[arr1.length];
for (int i = 0; i < arr1.length; i += SPECIES.length()) {
var v1 = IntVector.fromArray(SPECIES, arr1, i);
var v2 = IntVector.fromArray(SPECIES, arr2, i);
var result = v1.add(v2);
result.intoArray(finalResult, i);
}
return finalResult;
}
public int[] addTwoVectorsWithMasks(int[] arr1, int[] arr2) {
int[] finalResult = new int[arr1.length];
int i = 0;
for (; i < SPECIES.loopBound(arr1.length); i += SPECIES.length()) {
var mask = SPECIES.indexInRange(i, arr1.length);
var v1 = IntVector.fromArray(SPECIES, arr1, i, mask);
var v2 = IntVector.fromArray(SPECIES, arr2, i, mask);
var result = v1.add(v2, mask);
result.intoArray(finalResult, i, mask);
}
// tail cleanup loop
for (; i < arr1.length; i++) {
finalResult[i] = arr1[i] + arr2[i];
}
return finalResult;
}
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
|
请在Spring Boot框架中完成以下Java代码
|
private Optional<Integer> getAPIRequestId(@NonNull final Exchange exchange)
{
final Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
if (!(exception instanceof HttpOperationFailedException))
{
return Optional.empty();
}
final String response = ((HttpOperationFailedException)exception).getResponseBody();
if (Check.isBlank(response))
{
return Optional.empty();
}
try
{
final JsonApiResponse apiResponse = JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(response, JsonApiResponse.class);
return Optional.ofNullable(JsonMetasfreshId.toValue(apiResponse.getRequestId()));
}
catch (final JsonProcessingException e)
{
return Optional.empty();
}
}
private void prepareErrorLogMessage(@NonNull final Exchange exchange)
{
final Integer pInstanceId = exchange.getIn().getHeader(HEADER_PINSTANCE_ID, Integer.class);
|
if (pInstanceId == null)
{
throw new RuntimeException("No PInstanceId available!");
}
final JsonErrorItem errorItem = ErrorProcessor.getErrorItem(exchange);
final StringBuilder logMessageBuilder = new StringBuilder();
getAPIRequestId(exchange)
.ifPresent(apiRequestId -> logMessageBuilder.append("ApiRequestAuditId: ")
.append(apiRequestId)
.append(";"));
logMessageBuilder.append(" Error: ").append(StringUtils.removeCRLF(errorItem.toString()));
final LogMessageRequest logMessageRequest = LogMessageRequest.builder()
.logMessage(logMessageBuilder.toString())
.pInstanceId(JsonMetasfreshId.of(pInstanceId))
.build();
exchange.getIn().setBody(logMessageRequest);
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\ErrorReportRouteBuilder.java
| 2
|
请完成以下Java代码
|
protected Mono<Void> renderInternal(Map<String, Object> model, @Nullable MediaType contentType,
ServerWebExchange exchange) {
Resource resource = resolveResource();
if (resource == null) {
return Mono
.error(new IllegalStateException("Could not find Mustache template with URL [" + getUrl() + "]"));
}
DataBuffer dataBuffer = exchange.getResponse()
.bufferFactory()
.allocateBuffer(DefaultDataBufferFactory.DEFAULT_INITIAL_CAPACITY);
try (Reader reader = getReader(resource)) {
Assert.state(this.compiler != null, "'compiler' must not be null");
Template template = this.compiler.compile(reader);
Charset charset = getCharset(contentType).orElseGet(this::getDefaultCharset);
try (Writer writer = new OutputStreamWriter(dataBuffer.asOutputStream(), charset)) {
template.execute(model, writer);
writer.flush();
}
}
catch (Exception ex) {
DataBufferUtils.release(dataBuffer);
return Mono.error(ex);
}
return exchange.getResponse().writeWith(Flux.just(dataBuffer));
}
private @Nullable Resource resolveResource() {
ApplicationContext applicationContext = getApplicationContext();
|
String url = getUrl();
if (applicationContext == null || url == null) {
return null;
}
Resource resource = applicationContext.getResource(url);
if (resource == null || !resource.exists()) {
return null;
}
return resource;
}
private Reader getReader(Resource resource) throws IOException {
if (this.charset != null) {
return new InputStreamReader(resource.getInputStream(), this.charset);
}
return new InputStreamReader(resource.getInputStream());
}
private Optional<Charset> getCharset(@Nullable MediaType mediaType) {
return Optional.ofNullable((mediaType != null) ? mediaType.getCharset() : null);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\reactive\view\MustacheView.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int hashCode()
{
return Objects.hash(appliedPromotions, deliveryCost, discountedLineItemCost, ebayCollectAndRemitTaxes, giftDetails, itemLocation, legacyItemId, legacyVariationId, lineItemCost, lineItemFulfillmentInstructions, lineItemFulfillmentStatus, lineItemId, listingMarketplaceId, properties, purchaseMarketplaceId, quantity, refunds, sku, soldFormat, taxes, title, total);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class LineItem {\n");
sb.append(" appliedPromotions: ").append(toIndentedString(appliedPromotions)).append("\n");
sb.append(" deliveryCost: ").append(toIndentedString(deliveryCost)).append("\n");
sb.append(" discountedLineItemCost: ").append(toIndentedString(discountedLineItemCost)).append("\n");
sb.append(" ebayCollectAndRemitTaxes: ").append(toIndentedString(ebayCollectAndRemitTaxes)).append("\n");
sb.append(" giftDetails: ").append(toIndentedString(giftDetails)).append("\n");
sb.append(" itemLocation: ").append(toIndentedString(itemLocation)).append("\n");
sb.append(" legacyItemId: ").append(toIndentedString(legacyItemId)).append("\n");
sb.append(" legacyVariationId: ").append(toIndentedString(legacyVariationId)).append("\n");
sb.append(" lineItemCost: ").append(toIndentedString(lineItemCost)).append("\n");
sb.append(" lineItemFulfillmentInstructions: ").append(toIndentedString(lineItemFulfillmentInstructions)).append("\n");
sb.append(" lineItemFulfillmentStatus: ").append(toIndentedString(lineItemFulfillmentStatus)).append("\n");
sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).append("\n");
sb.append(" listingMarketplaceId: ").append(toIndentedString(listingMarketplaceId)).append("\n");
sb.append(" properties: ").append(toIndentedString(properties)).append("\n");
sb.append(" purchaseMarketplaceId: ").append(toIndentedString(purchaseMarketplaceId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" refunds: ").append(toIndentedString(refunds)).append("\n");
sb.append(" sku: ").append(toIndentedString(sku)).append("\n");
sb.append(" soldFormat: ").append(toIndentedString(soldFormat)).append("\n");
sb.append(" taxes: ").append(toIndentedString(taxes)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" total: ").append(toIndentedString(total)).append("\n");
sb.append("}");
return sb.toString();
|
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\LineItem.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class FileRecordController {
private final FileRecordService fileRecordService;
public FileRecordController(FileRecordService fileRecordService) {
this.fileRecordService = fileRecordService;
}
@PostMapping("/upload-files")
public Mono<String> uploadFileWithoutEntity(@RequestPart("files") Flux<FilePart> filePartFlux) {
return filePartFlux.flatMap(file -> file.transferTo(Paths.get(file.filename())))
.then(Mono.just("OK"))
.onErrorResume(error -> Mono.just("Error uploading files"));
}
@PostMapping("/upload-files-entity")
public Mono<FileRecord> uploadFileWithEntity(@RequestPart("files") Flux<FilePart> filePartFlux) {
FileRecord fileRecord = new FileRecord();
|
return filePartFlux.flatMap(filePart -> filePart.transferTo(Paths.get(filePart.filename()))
.then(Mono.just(filePart.filename())))
.collectList()
.flatMap(filenames -> {
fileRecord.setFilenames(filenames);
return fileRecordService.save(fileRecord);
})
.onErrorResume(error -> Mono.error(error));
}
@GetMapping("/files/{id}")
public Mono<FileRecord> geFilesById(@PathVariable("id") int id) {
return fileRecordService.findById(id)
.onErrorResume(error -> Mono.error(error));
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-webflux-2\src\main\java\com\baeldung\webflux\filerecord\FileRecordController.java
| 2
|
请完成以下Java代码
|
public String getName() {
return name;
}
@Override
public FormType getType() {
return type;
}
@Override
public String getValue() {
return value;
}
@Override
public boolean isRequired() {
|
return isRequired;
}
@Override
public boolean isReadable() {
return isReadable;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean isWritable() {
return isWritable;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\FormPropertyImpl.java
| 1
|
请完成以下Java代码
|
private synchronized void appendNow(final String sqlStatements)
{
if (sqlStatements == null || sqlStatements.isEmpty())
{
return;
}
try
{
final Path path = getCreateFilePath();
FileUtil.writeString(path, sqlStatements, CHARSET, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
catch (final IOException ex)
{
logger.error("Failed writing to {}:\n {}", this, sqlStatements, ex);
|
close(); // better to close the file ... so, next time a new one will be created
}
}
/**
* Close underling file.
* <p>
* Next time, {@link #appendSqlStatement(Sql)} will be called, a new file will be created, so it's safe to call this method as many times as needed.
*/
public synchronized void close()
{
watcher.addLog("Closed migration script: " + _path);
_path = null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\MigrationScriptFileLogger.java
| 1
|
请完成以下Java代码
|
private SOTrx computeRecordSOTrxEffective()
{
final String tableName = getTableInfo().getTableName();
final String sqlWhereClause = getRecordWhereClause(); // might be null
if (sqlWhereClause == null || Check.isBlank(sqlWhereClause))
{
return SOTrx.SALES;
}
return DB.retrieveRecordSOTrx(tableName, sqlWhereClause).orElse(SOTrx.SALES);
}
private Optional<TableRecordReference> retrieveParentRecordRef()
{
final GenericZoomIntoTableInfo tableInfo = getTableInfo();
if (tableInfo.getParentTableName() == null
|| tableInfo.getParentLinkColumnName() == null)
{
return Optional.empty();
}
final String sqlWhereClause = getRecordWhereClause(); // might be null
if (sqlWhereClause == null || Check.isBlank(sqlWhereClause))
{
return Optional.empty();
}
final String sql = "SELECT " + tableInfo.getParentLinkColumnName()
+ " FROM " + tableInfo.getTableName()
+ " WHERE " + sqlWhereClause;
try
{
final int parentRecordId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql);
if (parentRecordId < InterfaceWrapperHelper.getFirstValidIdByColumnName(tableInfo.getParentTableName() + "_ID"))
{
return Optional.empty();
}
final TableRecordReference parentRecordRef = TableRecordReference.of(tableInfo.getParentTableName(), parentRecordId);
return Optional.of(parentRecordRef);
}
|
catch (final Exception ex)
{
logger.warn("Failed retrieving parent record ID from current record. Returning empty. \n\tthis={} \n\tSQL: {}", this, sql, ex);
return Optional.empty();
}
}
@NonNull
private static CustomizedWindowInfoMapRepository getCustomizedWindowInfoMapRepository()
{
return !Adempiere.isUnitTestMode()
? SpringContextHolder.instance.getBean(CustomizedWindowInfoMapRepository.class)
: NullCustomizedWindowInfoMapRepository.instance;
}
@Value
@Builder
private static class TableInfoCacheKey
{
@NonNull String tableName;
boolean ignoreExcludeFromZoomTargetsFlag;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\RecordWindowFinder.java
| 1
|
请完成以下Java代码
|
private void validateRouteId(RouteDefinition routeDefinition) {
if (routeDefinition.getId() == null) {
handleError("Saving multiple routes require specifying the ID for every route");
}
}
private void validateRouteDefinition(RouteDefinition routeDefinition) {
Set<String> unavailableFilterDefinitions = routeDefinition.getFilters()
.stream()
.filter(rd -> !isAvailable(rd))
.map(FilterDefinition::getName)
.collect(Collectors.toSet());
Set<String> unavailablePredicatesDefinitions = routeDefinition.getPredicates()
.stream()
.filter(rd -> !isAvailable(rd))
.map(PredicateDefinition::getName)
.collect(Collectors.toSet());
if (!unavailableFilterDefinitions.isEmpty()) {
handleUnavailableDefinition(FilterDefinition.class.getSimpleName(), unavailableFilterDefinitions);
}
else if (!unavailablePredicatesDefinitions.isEmpty()) {
handleUnavailableDefinition(PredicateDefinition.class.getSimpleName(), unavailablePredicatesDefinitions);
}
validateRouteUri(routeDefinition.getUri());
}
private void validateRouteUri(URI uri) {
if (uri == null) {
handleError("The URI can not be empty");
}
if (!StringUtils.hasText(uri.getScheme())) {
handleError(String.format("The URI format [%s] is incorrect, scheme can not be empty", uri));
}
}
private void handleUnavailableDefinition(String simpleName, Set<String> unavailableDefinitions) {
final String errorMessage = String.format("Invalid %s: %s", simpleName, unavailableDefinitions);
log.warn(errorMessage);
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errorMessage);
}
private void handleError(String errorMessage) {
log.warn(errorMessage);
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errorMessage);
}
private boolean isAvailable(FilterDefinition filterDefinition) {
|
return GatewayFilters.stream()
.anyMatch(gatewayFilterFactory -> filterDefinition.getName().equals(gatewayFilterFactory.name()));
}
private boolean isAvailable(PredicateDefinition predicateDefinition) {
return routePredicates.stream()
.anyMatch(routePredicate -> predicateDefinition.getName().equals(routePredicate.name()));
}
@DeleteMapping("/routes/{id}")
public Mono<ResponseEntity<Object>> delete(@PathVariable String id) {
return this.routeDefinitionWriter.delete(Mono.just(id)).then(Mono.defer(() -> {
publisher.publishEvent(new RouteDeletedEvent(this, id));
return Mono.just(ResponseEntity.ok().build());
})).onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build()));
}
@GetMapping("/routes/{id}/combinedfilters")
public Mono<HashMap<String, Object>> combinedfilters(@PathVariable String id) {
// TODO: missing global filters
return this.routeLocator.getRoutes()
.filter(route -> route.getId().equals(id))
.reduce(new HashMap<>(), this::putItem);
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\actuate\AbstractGatewayControllerEndpoint.java
| 1
|
请完成以下Java代码
|
public static PickingJobCandidateList ofList(final List<PickingJobCandidate> list)
{
return !list.isEmpty() ? new PickingJobCandidateList(list) : EMPTY;
}
public static Collector<PickingJobCandidate, ?, PickingJobCandidateList> collect()
{
return GuavaCollectors.collectUsingListAccumulator(PickingJobCandidateList::ofList);
}
public boolean isEmpty() {return list.isEmpty();}
public Stream<PickingJobCandidate> stream() {return list.stream();}
public PickingJobCandidateList removeIf(@NonNull Predicate<PickingJobCandidate> predicate)
{
final ImmutableList<PickingJobCandidate> changedList = CollectionUtils.removeIf(list, predicate);
return list.size() == changedList.size() ? this : ofList(changedList);
}
|
public PickingJobCandidateList updateEach(@NonNull UnaryOperator<PickingJobCandidate> updater)
{
if (list.isEmpty()) {return this;}
final ImmutableList<PickingJobCandidate> changedList = CollectionUtils.map(list, updater);
return list == changedList ? this : ofList(changedList);
}
public Set<ProductId> getProductIds()
{
return list.stream()
.flatMap(job -> job.getProductIds().stream())
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobCandidateList.java
| 1
|
请完成以下Java代码
|
protected BigDecimal getAmount(final I_C_Dunning_Candidate candidate)
{
final BigDecimal amt = candidate.getDunningInterestAmt().add(candidate.getFeeAmt());
return amt;
}
protected int getSalesRep_ID(final I_C_Dunning_Candidate candidate)
{
// TODO: at this moment we consider that the SalesRep_ID is the user which is executing this process
// for future: we shall use de.metas.workflow.model.I_C_Doc_Responsible
final Properties ctx = getDunningContext().getCtx();
return Env.getAD_User_ID(ctx);
}
protected void completeDunningDoc()
{
if (dunningDoc == null)
{
return;
}
completeDunningDocLine();
final IDunningDAO dunningDAO = Services.get(IDunningDAO.class);
final IDocumentBL documentBL = Services.get(IDocumentBL.class);
dunningDAO.save(dunningDoc);
// If ProcessDunningDoc option is set in context, we need to automatically process the dunningDoc too
if (getDunningContext().isProperty(CONTEXT_ProcessDunningDoc, DEFAULT_ProcessDunningDoc))
{
documentBL.processEx(dunningDoc, IDocument.ACTION_Complete, IDocument.STATUS_Completed);
}
dunningDoc = null;
dunningDocLine = null;
}
protected void completeDunningDocLine()
{
for (final I_C_DunningDoc_Line_Source source : dunningDocLineSources)
{
completeDunningDocLineSource(source);
}
dunningDocLineSources.clear();
if (dunningDocLine == null)
{
return;
}
final IDunningDAO dunningDAO = Services.get(IDunningDAO.class);
dunningDAO.save(dunningDocLine);
|
dunningDocLine = null;
}
protected void completeDunningDocLineSource(final I_C_DunningDoc_Line_Source source)
{
final I_C_Dunning_Candidate candidate = source.getC_Dunning_Candidate();
candidate.setProcessed(true);
InterfaceWrapperHelper.save(candidate);
}
@Override
public void finish()
{
completeDunningDoc();
}
@Override
public void addAggregator(final IDunningAggregator aggregator)
{
dunningAggregators.addAggregator(aggregator);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DefaultDunningProducer.java
| 1
|
请完成以下Java代码
|
public class NoteDelete extends JavaProcess
{
private int p_AD_User_ID = -1;
private int p_KeepLogDays = 0;
/**
* Prepare - e.g., get Parameters.
*/
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("AD_User_ID"))
p_AD_User_ID = ((BigDecimal)para[i].getParameter()).intValue();
else if (name.equals("KeepLogDays"))
p_KeepLogDays = ((BigDecimal)para[i].getParameter()).intValue();
else
log.error("prepare - Unknown Parameter: " + name);
}
} // prepare
/**
* Perform process.
|
* @return Message (clear text)
* @throws Exception if not successful
*/
protected String doIt() throws Exception
{
log.info("doIt - AD_User_ID=" + p_AD_User_ID);
String sql = "DELETE FROM AD_Note WHERE AD_Client_ID=" + getAD_Client_ID();
if (p_AD_User_ID > 0)
sql += " AND AD_User_ID=" + p_AD_User_ID;
if (p_KeepLogDays > 0)
sql += " AND (Created+" + p_KeepLogDays + ") < now()";
//
int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
return "@Deleted@ = " + no;
} // doIt
} // NoteDelete
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\NoteDelete.java
| 1
|
请完成以下Java代码
|
public class TcpConnectionReadLineEndPoint extends TcpConnectionEndPoint
{
private final static transient Logger logger = LogManager.getLogger(TcpConnectionReadLineEndPoint.class);
/**
* see {@link #setReturnLastLine(boolean)}.
*/
private boolean returnLastLine = false;
/**
* If <code>false</code>, then the endpoint will return the first line coming out of the socket.
* If <code>true</code>, if will discard all lines until there is nothing more coming out of the socket, and then return the last line if got.
*/
public TcpConnectionEndPoint setReturnLastLine(final boolean returnLastLine)
{
this.returnLastLine = returnLastLine;
return this;
}
@Override
String readSocketResponse(@NonNull final InputStream in) throws IOException
{
return readLineSocketResponse(in);
}
@Nullable
private String readLineSocketResponse(@NonNull final InputStream in) throws IOException
{
try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, ICmd.DEFAULT_CMD_CHARSET)))
{
String result = null;
String lastReadLine = bufferedReader.readLine();
if (returnLastLine)
{
while (lastReadLine != null)
{
result = lastReadLine;
lastReadLine = readLineWithTimeout(bufferedReader);
}
logger.debug("Result (last line) as read from the socket: {}", result);
}
|
else
{
result = lastReadLine;
logger.debug("Result (first line) as read from the socket: {}", result);
}
return result;
}
}
@Nullable
private String readLineWithTimeout(@NonNull final BufferedReader in) throws IOException
{
try
{
final String lastReadLine = in.readLine();
logger.debug("Read line from the socket: {}", lastReadLine);
return lastReadLine;
}
catch (final SocketTimeoutException e)
{
logger.debug("Socket timeout; return null; exception-message={}", e.getMessage());
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\endpoint\TcpConnectionReadLineEndPoint.java
| 1
|
请完成以下Java代码
|
public void setTransactionOrder(Integer transactionOrder) {
this.transactionOrder = transactionOrder;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@Override
public String getActivityName() {
return activityName;
}
@Override
public void setActivityName(String activityName) {
this.activityName = activityName;
}
@Override
public String getActivityType() {
return activityType;
}
@Override
public void setActivityType(String activityType) {
this.activityType = activityType;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public String getAssignee() {
return assignee;
}
@Override
public void setAssignee(String assignee) {
this.assignee = assignee;
}
|
@Override
public String getCompletedBy() {
return completedBy;
}
@Override
public void setCompletedBy(String completedBy) {
this.completedBy = completedBy;
}
@Override
public String getTaskId() {
return taskId;
}
@Override
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
}
@Override
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getTime() {
return getStartTime();
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "HistoricActivityInstanceEntity[id=" + id + ", activityId=" + activityId + ", activityName=" + activityName + ", executionId= " + executionId + "]";
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricActivityInstanceEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String find(@PathVariable("name") String name) {
long t0 = System.currentTimeMillis();
Person person = this.yellowPages.find(name);
return format(String.format("{ person: %s, cacheMiss: %s, latency: %d ms }",
person, this.yellowPages.isCacheMiss(), (System.currentTimeMillis() - t0)));
}
@GetMapping("/yellow-pages/{name}/update")
public String update(@PathVariable("name") String name,
@RequestParam(name = "email", required = false) String email,
@RequestParam(name = "phoneNumber", required = false) String phoneNumber) {
Person person = this.yellowPages.save(this.yellowPages.find(name), email, phoneNumber);
|
return format(String.format("{ person: %s }", person));
}
@GetMapping("/yellow-pages/{name}/evict")
public String evict(@PathVariable("name") String name) {
this.yellowPages.evict(name);
return format(String.format("Evicted %s", name));
}
private String format(String value) {
return String.format(HTML, value);
}
}
// end::class[]
|
repos\spring-boot-data-geode-main\spring-geode-samples\caching\near\src\main\java\example\app\caching\near\client\controller\YellowPagesController.java
| 2
|
请完成以下Java代码
|
public void setMeters(double meters) {
this.meters = meters;
}
public double getMeters() {
return meters;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
|
@JsonCreator
public static Distance forValues(@JsonProperty("unit") String unit, @JsonProperty("meters") double meters) {
for (Distance distance : Distance.values()) {
if (distance.unit.equals(unit) && Double.compare(distance.meters, meters) == 0) {
return distance;
}
}
return null;
}
}
|
repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\enums\deserialization\jsoncreator\Distance.java
| 1
|
请完成以下Java代码
|
public Optional<ProductBarcodeFilterData> createData(
final @NonNull ProductBarcodeFilterServicesFacade services,
final @NonNull String barcodeParam,
final @NonNull ClientId clientId)
{
Check.assumeNotEmpty(barcodeParam, "barcode not empty");
final String barcodeNorm = barcodeParam.trim();
final ImmutableList<ResolvedScannedProductCode> ediProductLookupList = services.getEDIProductLookupByUPC(barcodeNorm);
final ProductId productId = services.getProductIdByBarcode(barcodeNorm, clientId).orElse(null);
final SqlAndParams sqlWhereClause = createSqlWhereClause(services, ediProductLookupList, productId).orElse(null);
if (sqlWhereClause == null)
{
return Optional.empty();
}
return Optional.of(ProductBarcodeFilterData.builder()
.barcode(barcodeNorm)
.sqlWhereClause(sqlWhereClause)
.build());
}
private static Optional<SqlAndParams> createSqlWhereClause(
@NonNull final ProductBarcodeFilterServicesFacade services,
@NonNull final ImmutableList<ResolvedScannedProductCode> ediProductLookupList,
@Nullable final ProductId productId)
{
if (productId == null && ediProductLookupList.isEmpty())
{
return Optional.empty();
}
final ICompositeQueryFilter<I_M_Packageable_V> resultFilter = services.createCompositeQueryFilter()
.setJoinOr();
|
if (!ediProductLookupList.isEmpty())
{
for (final ResolvedScannedProductCode ediProductLookup : ediProductLookupList)
{
final ICompositeQueryFilter<I_M_Packageable_V> filter = resultFilter.addCompositeQueryFilter()
.setJoinAnd()
.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_M_Product_ID, ediProductLookup.getProductId());
if (ediProductLookup.getBpartnerId() != null)
{
filter.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_C_BPartner_Customer_ID, ediProductLookup.getBpartnerId());
}
}
}
if (productId != null)
{
resultFilter.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_M_Product_ID, productId);
}
return Optional.of(services.toSqlAndParams(resultFilter));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\filters\UPCProductBarcodeFilterDataFactory.java
| 1
|
请完成以下Java代码
|
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final I_DD_OrderLine ddOrderLine = getViewSelectedDDOrderLine();
final String parameterName = parameter.getColumnName();
if (PARAM_M_HU_ID.equals(parameterName))
{
return getRecord_ID();
}
else if (PARAM_DD_ORDER_LINE_ID.equals(parameterName))
{
return ddOrderLine.getDD_OrderLine_ID();
}
else if (PARAM_LOCATOR_TO_ID.equals(parameterName))
{
return ddOrderLine.getM_LocatorTo_ID();
}
else
{
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
}
private I_DD_OrderLine getViewSelectedDDOrderLine()
{
|
final DDOrderLineId ddOrderLineId = getViewSelectedDDOrderLineId();
return ddOrderService.getLineById(ddOrderLineId);
}
@NonNull
private DDOrderLineId getViewSelectedDDOrderLineId()
{
final ViewId parentViewId = getView().getParentViewId();
final DocumentIdsSelection selectedParentRow = DocumentIdsSelection.of(ImmutableList.of(getView().getParentRowId()));
final int selectedOrderLineId = viewsRepository.getView(parentViewId)
.streamByIds(selectedParentRow)
.findFirst()
.orElseThrow(() -> new AdempiereException("No DD_OrderLine was selected!"))
.getFieldValueAsInt(I_DD_OrderLine.COLUMNNAME_DD_OrderLine_ID, -1);
return DDOrderLineId.ofRepoId(selectedOrderLineId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\ddorder\process\WEBUI_DD_OrderLine_MoveSelected_HU.java
| 1
|
请完成以下Java代码
|
protected void addAllPasswordChecker(List<PasswordEncryptor> list) {
for (PasswordEncryptor encryptor : list) {
addPasswordCheckerAndThrowErrorIfAlreadyAvailable(encryptor);
}
}
protected void addPasswordCheckerAndThrowErrorIfAlreadyAvailable(PasswordEncryptor encryptor) {
if(passwordChecker.containsKey(encryptor.hashAlgorithmName())){
throw LOG.hashAlgorithmForPasswordEncryptionAlreadyAvailableException(encryptor.hashAlgorithmName());
}
passwordChecker.put(encryptor.hashAlgorithmName(), encryptor);
}
protected void addDefaultEncryptor(PasswordEncryptor defaultPasswordEncryptor) {
this.defaultPasswordEncryptor = defaultPasswordEncryptor;
passwordChecker.put(defaultPasswordEncryptor.hashAlgorithmName(), defaultPasswordEncryptor);
}
public String encrypt(String password){
String prefix = prefixHandler.generatePrefix(defaultPasswordEncryptor.hashAlgorithmName());
return prefix + defaultPasswordEncryptor.encrypt(password);
}
|
public boolean check(String password, String encrypted){
PasswordEncryptor encryptor = getCorrectEncryptorForPassword(encrypted);
String encryptedPasswordWithoutPrefix = prefixHandler.removePrefix(encrypted);
ensureNotNull("encryptedPasswordWithoutPrefix", encryptedPasswordWithoutPrefix);
return encryptor.check(password, encryptedPasswordWithoutPrefix);
}
protected PasswordEncryptor getCorrectEncryptorForPassword(String encryptedPassword) {
String hashAlgorithmName = prefixHandler.retrieveAlgorithmName(encryptedPassword);
if(hashAlgorithmName == null || !passwordChecker.containsKey(hashAlgorithmName)){
throw LOG.cannotResolveAlgorithmPrefixFromGivenPasswordException(hashAlgorithmName, passwordChecker.keySet());
}
return passwordChecker.get(hashAlgorithmName);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\digest\PasswordManager.java
| 1
|
请完成以下Java代码
|
public MPrintFormatItem copyToClient (int To_Client_ID, int AD_PrintFormat_ID)
{
MPrintFormatItem to = new MPrintFormatItem (getCtx(), 0, null);
MPrintFormatItem.copyValues(this, to);
to.setClientOrg(To_Client_ID, 0);
to.setAD_PrintFormat_ID(AD_PrintFormat_ID);
to.save();
return to;
} // copyToClient
/**
* Before Save
* @param newRecord
* @return true if ok
*/
@Override
protected boolean beforeSave (boolean newRecord)
{
// Order
if (!isOrderBy())
{
setSortNo(0);
setIsGroupBy(false);
setIsPageBreak(false);
}
// Rel Position
if (isRelativePosition())
{
setXPosition(0);
setYPosition(0);
}
else
{
setXSpace(0);
setYSpace(0);
}
// Image
if (isImageField())
{
setImageIsAttached(false);
setImageURL(null);
}
return true;
} // beforeSave
/**
* After Save
|
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
// Set Translation from Element
if (newRecord
// && MClient.get(getCtx()).isMultiLingualDocument()
&& getPrintName() != null && getPrintName().length() > 0)
{
String sql = "UPDATE AD_PrintFormatItem_Trl trl "
+ "SET PrintName = (SELECT e.PrintName "
+ "FROM AD_Element_Trl e, AD_Column c "
+ "WHERE e.AD_Language=trl.AD_Language"
+ " AND e.AD_Element_ID=c.AD_Element_ID"
+ " AND c.AD_Column_ID=" + getAD_Column_ID() + ") "
+ "WHERE AD_PrintFormatItem_ID = " + get_ID()
+ " AND EXISTS (SELECT * "
+ "FROM AD_Element_Trl e, AD_Column c "
+ "WHERE e.AD_Language=trl.AD_Language"
+ " AND e.AD_Element_ID=c.AD_Element_ID"
+ " AND c.AD_Column_ID=" + getAD_Column_ID()
+ " AND trl.AD_PrintFormatItem_ID = " + get_ID() + ")"
+ " AND EXISTS (SELECT * FROM AD_Client "
+ "WHERE AD_Client_ID=trl.AD_Client_ID AND IsMultiLingualDocument='Y')";
int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
log.debug("translations updated #" + no);
}
// metas-tsa: we need to reset the cache if an item value is changed
CacheMgt.get().resetLocalNowAndBroadcastOnTrxCommit(get_TrxName(), CacheInvalidateMultiRequest.rootRecord(I_AD_PrintFormat.Table_Name, getAD_PrintFormat_ID()));
return success;
} // afterSave
} // MPrintFormatItem
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintFormatItem.java
| 1
|
请完成以下Java代码
|
public String getRemark() {
return remark;
}
/**
* Sets the value of the remark property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemark(String value) {
this.remark = value;
}
|
/**
* Gets the value of the status property.
*
*/
public int getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
*/
public void setStatus(int value) {
this.status = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ValidationType.java
| 1
|
请完成以下Java代码
|
public class BetweenRoutePredicateFactory extends AbstractRoutePredicateFactory<BetweenRoutePredicateFactory.Config> {
/**
* DateTime 1 key.
*/
public static final String DATETIME1_KEY = "datetime1";
/**
* DateTime 2 key.
*/
public static final String DATETIME2_KEY = "datetime2";
public BetweenRoutePredicateFactory() {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(DATETIME1_KEY, DATETIME2_KEY);
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
Objects.requireNonNull(config.getDatetime1(), DATETIME1_KEY + " must not be null");
Assert.isTrue(config.getDatetime1().isBefore(config.getDatetime2()),
config.getDatetime1() + " must be before " + config.getDatetime2());
return new GatewayPredicate() {
@Override
public boolean test(ServerWebExchange serverWebExchange) {
final ZonedDateTime now = ZonedDateTime.now();
return now.isAfter(config.getDatetime1()) && now.isBefore(config.getDatetime2());
}
@Override
public Object getConfig() {
return config;
}
|
@Override
public String toString() {
return String.format("Between: %s and %s", config.getDatetime1(), config.getDatetime2());
}
};
}
public static class Config {
@NotNull
private @Nullable ZonedDateTime datetime1;
@NotNull
private @Nullable ZonedDateTime datetime2;
public @Nullable ZonedDateTime getDatetime1() {
return datetime1;
}
public Config setDatetime1(ZonedDateTime datetime1) {
this.datetime1 = datetime1;
return this;
}
public @Nullable ZonedDateTime getDatetime2() {
return datetime2;
}
public Config setDatetime2(ZonedDateTime datetime2) {
this.datetime2 = datetime2;
return this;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\BetweenRoutePredicateFactory.java
| 1
|
请完成以下Java代码
|
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getCompressFileKey() {
return compressFileKey;
}
public void setCompressFileKey(String compressFileKey) {
this.compressFileKey = compressFileKey;
}
public String getName() {
return name;
}
public String getCacheName() {
return cacheName;
}
public String getCacheListName() {
return cacheListName;
}
public String getOutFilePath() {
return outFilePath;
}
public String getOriginFilePath() {
return originFilePath;
}
public boolean isHtmlView() {
return isHtmlView;
}
public void setCacheName(String cacheName) {
this.cacheName = cacheName;
}
public void setCacheListName(String cacheListName) {
this.cacheListName = cacheListName;
}
public void setOutFilePath(String outFilePath) {
this.outFilePath = outFilePath;
}
public void setOriginFilePath(String originFilePath) {
this.originFilePath = originFilePath;
}
public void setHtmlView(boolean isHtmlView) {
this.isHtmlView = isHtmlView;
}
public void setName(String name) {
this.name = name;
|
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Boolean getSkipDownLoad() {
return skipDownLoad;
}
public void setSkipDownLoad(Boolean skipDownLoad) {
this.skipDownLoad = skipDownLoad;
}
public String getTifPreviewType() {
return tifPreviewType;
}
public void setTifPreviewType(String previewType) {
this.tifPreviewType = previewType;
}
public Boolean forceUpdatedCache() {
return forceUpdatedCache;
}
public void setForceUpdatedCache(Boolean forceUpdatedCache) {
this.forceUpdatedCache = forceUpdatedCache;
}
public String getKkProxyAuthorization() {
return kkProxyAuthorization;
}
public void setKkProxyAuthorization(String kkProxyAuthorization) {
this.kkProxyAuthorization = kkProxyAuthorization;
}
}
|
repos\kkFileView-master\server\src\main\java\cn\keking\model\FileAttribute.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Quantity computeQtyToIssueBasedOnFinishedGoodReceipt(@NonNull final RawMaterialsIssueLine rawMaterialsIssueLine)
{
return ppOrderBOMBL.computeQtyToIssueBasedOnFinishedGoodReceipt(
getBomLine(rawMaterialsIssueLine),
rawMaterialsIssueLine.getQtyToIssue().getUOM(),
getDraftPPOrderQuantities()
);
}
@NonNull
private I_PP_Order_BOMLine getBomLine(@NonNull final RawMaterialsIssueLine issueLine)
{
if (_bomLineRecordsById == null)
{
_bomLineRecordsById = Maps.uniqueIndex(ppOrderBOMBL.getOrderBOMLines(ppOrderId), IssueWhatWasReceivedCommand::extractOrderBOMLineId);
}
final I_PP_Order_BOMLine bomLineRecord = _bomLineRecordsById.get(issueLine.getOrderBOMLineId());
if (bomLineRecord == null)
{
throw new AdempiereException("No PP_Order_BOMLine found for " + issueLine);
}
return bomLineRecord;
}
@NonNull
private static PPOrderBOMLineId extractOrderBOMLineId(@NonNull final I_PP_Order_BOMLine record)
{
return PPOrderBOMLineId.ofRepoId(record.getPP_Order_BOMLine_ID());
}
private List<I_M_HU> splitOutCUsFromSourceHUs(@NonNull final ProductId productId, @NonNull final Quantity qtyCU)
{
final SourceHUsCollection sourceHUsCollection = getSourceHUsCollectionProvider().getByProductId(productId);
if (sourceHUsCollection.isEmpty())
{
return ImmutableList.of();
}
return HUTransformService.builder()
.emptyHUListener(
EmptyHUListener.doBeforeDestroyed(hu -> sourceHUsCollection
.getSourceHU(HuId.ofRepoId(hu.getM_HU_ID()))
.ifPresent(sourceHUsService::snapshotSourceHU),
"Create snapshot of source-HU before it is destroyed")
)
.build()
.husToNewCUs(
|
HUsToNewCUsRequest.builder()
.sourceHUs(sourceHUsCollection.getHusThatAreFlaggedAsSource())
.productId(productId)
.qtyCU(qtyCU)
.build()
)
.getNewCUs();
}
private void createIssueSchedule(final I_PP_Order_Qty ppOrderQtyRecord)
{
final Quantity qtyIssued = Quantitys.of(ppOrderQtyRecord.getQty(), UomId.ofRepoId(ppOrderQtyRecord.getC_UOM_ID()));
issueScheduleService.createSchedule(
PPOrderIssueScheduleCreateRequest.builder()
.ppOrderId(ppOrderId)
.ppOrderBOMLineId(PPOrderBOMLineId.ofRepoId(ppOrderQtyRecord.getPP_Order_BOMLine_ID()))
.seqNo(SeqNo.ofInt(0))
.productId(ProductId.ofRepoId(ppOrderQtyRecord.getM_Product_ID()))
.qtyToIssue(qtyIssued)
.issueFromHUId(HuId.ofRepoId(ppOrderQtyRecord.getM_HU_ID()))
.issueFromLocatorId(warehouseDAO.getLocatorIdByRepoId(ppOrderQtyRecord.getM_Locator_ID()))
.isAlternativeIssue(true)
.qtyIssued(qtyIssued)
.build()
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\issue_what_was_received\IssueWhatWasReceivedCommand.java
| 2
|
请完成以下Java代码
|
public boolean hasParameters()
{
return sqlParams != null && !sqlParams.isEmpty();
}
public int getParametersCount()
{
return sqlParams != null ? sqlParams.size() : 0;
}
public Builder appendIfHasParameters(@NonNull final CharSequence sql)
{
if (hasParameters())
{
return append(sql);
}
else
{
return this;
}
}
public Builder appendIfNotEmpty(@NonNull final CharSequence sql, @Nullable final Object... sqlParams)
{
if (!isEmpty())
{
append(sql, sqlParams);
}
return this;
}
public Builder append(@NonNull final CharSequence sql, @Nullable final Object... sqlParams)
{
final List<Object> sqlParamsList = sqlParams != null && sqlParams.length > 0 ? Arrays.asList(sqlParams) : null;
return append(sql, sqlParamsList);
}
public Builder append(@NonNull final CharSequence sql, @Nullable final List<Object> sqlParams)
|
{
if (sql.length() > 0)
{
if (this.sql == null)
{
this.sql = new StringBuilder();
}
this.sql.append(sql);
}
if (sqlParams != null && !sqlParams.isEmpty())
{
if (this.sqlParams == null)
{
this.sqlParams = new ArrayList<>();
}
this.sqlParams.addAll(sqlParams);
}
return this;
}
public Builder append(@NonNull final SqlAndParams other)
{
return append(other.sql, other.sqlParams);
}
public Builder append(@NonNull final SqlAndParams.Builder other)
{
return append(other.sql, other.sqlParams);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlAndParams.java
| 1
|
请完成以下Java代码
|
protected boolean isValidTime(JobEntity timerEntity, Date newTimerDate, VariableScope variableScope) {
BusinessCalendar businessCalendar = getProcessEngineConfiguration()
.getBusinessCalendarManager()
.getBusinessCalendar(
getBusinessCalendarName(
TimerEventHandler.geCalendarNameFromConfiguration(timerEntity.getJobHandlerConfiguration()),
variableScope
)
);
return businessCalendar.validateDuedate(
timerEntity.getRepeat(),
timerEntity.getMaxIterations(),
timerEntity.getEndDate(),
newTimerDate
);
}
protected Date calculateNextTimer(JobEntity timerEntity, VariableScope variableScope) {
BusinessCalendar businessCalendar = getProcessEngineConfiguration()
.getBusinessCalendarManager()
.getBusinessCalendar(
getBusinessCalendarName(
TimerEventHandler.geCalendarNameFromConfiguration(timerEntity.getJobHandlerConfiguration()),
variableScope
)
);
return businessCalendar.resolveDuedate(timerEntity.getRepeat(), timerEntity.getMaxIterations());
}
protected int calculateRepeatValue(JobEntity timerEntity) {
int times = -1;
List<String> expression = asList(timerEntity.getRepeat().split("/"));
|
if (expression.size() > 1 && expression.get(0).startsWith("R") && expression.get(0).length() > 1) {
times = Integer.parseInt(expression.get(0).substring(1));
if (times > 0) {
times--;
}
}
return times;
}
protected String getBusinessCalendarName(String calendarName, VariableScope variableScope) {
String businessCalendarName = CycleBusinessCalendar.NAME;
if (StringUtils.isNotEmpty(calendarName)) {
businessCalendarName = (String) Context.getProcessEngineConfiguration()
.getExpressionManager()
.createExpression(calendarName)
.getValue(variableScope);
}
return businessCalendarName;
}
protected TimerJobDataManager getDataManager() {
return jobDataManager;
}
public void setJobDataManager(TimerJobDataManager jobDataManager) {
this.jobDataManager = jobDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TimerJobEntityManagerImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:table.sql")
.build();
}
@Bean
public DataSourceTransactionManager txManager() {
return new DataSourceTransactionManager(dataSource);
}
public static void main(final String... args) {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(TxIntegrationConfig.class);
context.registerShutdownHook();
final Scanner scanner = new Scanner(System.in);
|
System.out.print("Integration flow is running. Type q + <enter> to quit ");
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
context.close();
scanner.close();
break;
}
}
System.exit(0);
}
}
|
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\tx\TxIntegrationConfig.java
| 2
|
请完成以下Java代码
|
public synchronized int size()
{
// TODO: implement for GridField values too
return ctx.size();
}
@Override
public synchronized String toString()
{
// TODO: implement for GridField values too
return ctx.toString();
}
@Override
public Collection<Object> values()
{
return ctx.values();
}
|
@Override
public String getProperty(String key)
{
// I need to override this method, because Properties.getProperty method
// is calling super.get() instead of get()
Object oval = get(key);
return oval == null ? null : oval.toString();
}
@Override
public String get_ValueAsString(String variableName)
{
final int windowNo = getWindowNo();
final int tabNo = getTabNo();
// Check value at Tab level, fallback to Window level
final String value = Env.getContext(this, windowNo, tabNo, variableName, Scope.Window);
return value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\GridRowCtx.java
| 1
|
请完成以下Java代码
|
public void setM_Picking_Job_Step_ID (final int M_Picking_Job_Step_ID)
{
if (M_Picking_Job_Step_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Step_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Step_ID, M_Picking_Job_Step_ID);
}
@Override
public int getM_Picking_Job_Step_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Step_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU getPickFrom_HU()
{
return get_ValueAsPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setPickFrom_HU(final de.metas.handlingunits.model.I_M_HU PickFrom_HU)
{
set_ValueFromPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class, PickFrom_HU);
}
@Override
public void setPickFrom_HU_ID (final int PickFrom_HU_ID)
{
if (PickFrom_HU_ID < 1)
set_Value (COLUMNNAME_PickFrom_HU_ID, null);
else
set_Value (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID);
}
@Override
public int getPickFrom_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID);
}
@Override
public void setPickFrom_Locator_ID (final int PickFrom_Locator_ID)
{
if (PickFrom_Locator_ID < 1)
set_Value (COLUMNNAME_PickFrom_Locator_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Locator_ID, PickFrom_Locator_ID);
}
@Override
public int getPickFrom_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID);
}
@Override
public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID)
|
{
if (PickFrom_Warehouse_ID < 1)
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID);
}
@Override
public int getPickFrom_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID);
}
@Override
public void setQtyRejectedToPick (final @Nullable BigDecimal QtyRejectedToPick)
{
set_Value (COLUMNNAME_QtyRejectedToPick, QtyRejectedToPick);
}
@Override
public BigDecimal getQtyRejectedToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRejectedToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int REJECTREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D";
@Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_Value (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step_HUAlternative.java
| 1
|
请完成以下Java代码
|
public void setPrintValue_Override (final @Nullable java.lang.String PrintValue_Override)
{
set_Value (COLUMNNAME_PrintValue_Override, PrintValue_Override);
}
@Override
public java.lang.String getPrintValue_Override()
{
return get_ValueAsString(COLUMNNAME_PrintValue_Override);
}
@Override
public void setValue (final java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setValueMax (final @Nullable BigDecimal ValueMax)
{
set_Value (COLUMNNAME_ValueMax, ValueMax);
}
|
@Override
public BigDecimal getValueMax()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMax);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValueMin (final @Nullable BigDecimal ValueMin)
{
set_Value (COLUMNNAME_ValueMin, ValueMin);
}
@Override
public BigDecimal getValueMin()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMin);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Attribute.java
| 1
|
请完成以下Java代码
|
public void onIsOverUnderPaymentChange(final I_C_Payment payment)
{
paymentBL.onIsOverUnderPaymentChange(payment, true);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_C_Payment.COLUMNNAME_PayAmt)
public void onPayAmtChange(final I_C_Payment payment)
{
paymentBL.onPayAmtChange(payment, true);
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_VOID })
public void onBeforeVoid(final I_C_Payment payment)
{
//
// Make sure we are not allowing a payment, which is on bank statement, to be voided.
// It shall be reversed if really needed.
final PaymentId paymentId = PaymentId.ofRepoId(payment.getC_Payment_ID());
if (bankStatementBL.isPaymentOnBankStatement(paymentId))
{
throw new AdempiereException("@void.payment@");
}
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_REVERSECORRECT })
public void onAfterReverse(final I_C_Payment payment)
{
//
// Auto-reconcile the payment and it's reversal if the payment is not present on bank statements
final PaymentId paymentId = PaymentId.ofRepoId(payment.getC_Payment_ID());
if (!bankStatementBL.isPaymentOnBankStatement(paymentId))
{
final PaymentId reversalId = PaymentId.ofRepoId(payment.getReversal_ID());
final ImmutableList<PaymentReconcileRequest> requests = ImmutableList.of(
|
PaymentReconcileRequest.of(paymentId, PaymentReconcileReference.reversal(reversalId)),
PaymentReconcileRequest.of(reversalId, PaymentReconcileReference.reversal(paymentId)));
final Collection<I_C_Payment> preloadedPayments = ImmutableList.of(payment);
paymentBL.markReconciled(requests, preloadedPayments);
}
}
@DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE })
public void createCashStatementLineIfNeeded(final I_C_Payment payment)
{
if (!paymentBL.isCashTrx(payment))
{
return;
}
if (bankStatementBL.isPaymentOnBankStatement(PaymentId.ofRepoId(payment.getC_Payment_ID())))
{
return;
}
cashStatementBL.createCashStatementLine(payment);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_Payment.COLUMNNAME_DateTrx })
public void onDateChange(final I_C_Payment payment)
{
paymentBL.updateDiscountAndPayAmtFromInvoiceIfAny(payment);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\modelvalidator\C_Payment.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public StatsdProtocol getProtocol() {
return this.protocol;
}
public void setProtocol(StatsdProtocol protocol) {
this.protocol = protocol;
}
public Integer getMaxPacketLength() {
return this.maxPacketLength;
}
public void setMaxPacketLength(Integer maxPacketLength) {
this.maxPacketLength = maxPacketLength;
}
public Duration getPollingFrequency() {
return this.pollingFrequency;
}
public void setPollingFrequency(Duration pollingFrequency) {
this.pollingFrequency = pollingFrequency;
}
public Duration getStep() {
|
return this.step;
}
public void setStep(Duration step) {
this.step = step;
}
public boolean isPublishUnchangedMeters() {
return this.publishUnchangedMeters;
}
public void setPublishUnchangedMeters(boolean publishUnchangedMeters) {
this.publishUnchangedMeters = publishUnchangedMeters;
}
public boolean isBuffered() {
return this.buffered;
}
public void setBuffered(boolean buffered) {
this.buffered = buffered;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\statsd\StatsdProperties.java
| 2
|
请完成以下Java代码
|
public List<IHUTransactionCandidate> aggregateTransactions(final List<IHUTransactionCandidate> transactions)
{
final Map<ArrayKey, IHUTransactionCandidate> transactionsAggregateMap = new HashMap<>();
final List<IHUTransactionCandidate> notAggregated = new ArrayList<>();
for (final IHUTransactionCandidate trx : transactions)
{
if (trx.getCounterpart() != null)
{
// we don't want to aggregate paired trxCandidates because we want to discard the trxCandidates this method was called with.
// unless we don't have to, we don't want to delve into those intricacies...
notAggregated.add(trx);
}
// note that we use the ID if we can, because we don't want this to fail e.g. because of two different versions of the "same" VHU-item
final ArrayKey key = Util.mkKey(
// trxCandidate.getCounterpart(),
trx.getDate(),
trx.getHUStatus(),
// trxCandidate.getM_HU(), just delegates to HU_Item
trx.getM_HU_Item() == null ? -1 : trx.getM_HU_Item().getM_HU_Item_ID(),
trx.getLocatorId(),
trx.getProductId() == null ? -1 : trx.getProductId().getRepoId(),
// trxCandidate.getQuantity(),
trx.getReferencedModel() == null ? -1 : TableRecordReference.of(trx.getReferencedModel()),
// trxCandidate.getVHU(), just delegates to VHU_Item
trx.getVHU_Item() == null ? -1 : trx.getVHU_Item().getM_HU_Item_ID(),
trx.isSkipProcessing());
|
transactionsAggregateMap.merge(key,
trx,
(existingCand, newCand) -> {
final HUTransactionCandidate mergedCandidate = new HUTransactionCandidate(existingCand.getReferencedModel(),
existingCand.getM_HU_Item(),
existingCand.getVHU_Item(),
existingCand.getProductId(),
existingCand.getQuantity().add(newCand.getQuantity()),
existingCand.getDate(),
existingCand.getLocatorId(),
existingCand.getHUStatus());
if (existingCand.isSkipProcessing())
{
mergedCandidate.setSkipProcessing();
}
return mergedCandidate;
});
}
return ImmutableList.<IHUTransactionCandidate>builder()
.addAll(notAggregated)
.addAll(transactionsAggregateMap.values())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxBL.java
| 1
|
请完成以下Java代码
|
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
addOriginalRequestUrl(exchange, request.getURI());
String path = request.getURI().getRawPath();
String[] originalParts = StringUtils.tokenizeToStringArray(path, "/");
// all new paths start with /
StringBuilder newPath = new StringBuilder("/");
for (int i = 0; i < originalParts.length; i++) {
if (i >= config.getParts()) {
// only append slash if this is the second part or greater
if (newPath.length() > 1) {
newPath.append('/');
}
newPath.append(originalParts[i]);
}
}
if (newPath.length() > 1 && path.endsWith("/")) {
newPath.append('/');
}
ServerHttpRequest newRequest = request.mutate().path(newPath.toString()).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
return chain.filter(exchange.mutate().request(newRequest).build());
}
@Override
public String toString() {
return filterToStringCreator(StripPrefixGatewayFilterFactory.this).append("parts", config.getParts())
.toString();
|
}
};
}
public static class Config {
private int parts = 1;
public int getParts() {
return parts;
}
public void setParts(int parts) {
this.parts = parts;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\StripPrefixGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
protected PropertySource<?> toSimplePropertySource() {
Properties props = new Properties();
copyIfSet(props, "branch");
String commitId = getProperties().getShortCommitId();
if (commitId != null) {
props.put("commit.id", commitId);
}
copyIfSet(props, "commit.time");
return new PropertiesPropertySource("git", props);
}
/**
* Post-process the content to expose. By default, well known keys representing dates
* are converted to {@link Instant} instances.
* @param content the content to expose
*/
@Override
protected void postProcessContent(Map<String, Object> content) {
replaceValue(getNestedMap(content, "commit"), "time", getProperties().getCommitTime());
|
replaceValue(getNestedMap(content, "build"), "time", getProperties().getInstant("build.time"));
}
static class GitInfoContributorRuntimeHints implements RuntimeHintsRegistrar {
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.bindingRegistrar.registerReflectionHints(hints.reflection(), GitProperties.class);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\info\GitInfoContributor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Mono<Void> changePassword(String currentClearTextPassword, String newPassword) {
return SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.publishOn(Schedulers.boundedElastic())
.map(user -> {
String currentEncryptedPassword = user.getPassword();
if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) {
throw new InvalidPasswordException();
}
String encryptedPassword = passwordEncoder.encode(newPassword);
user.setPassword(encryptedPassword);
return user;
})
.flatMap(this::saveUser)
.doOnNext(user -> log.debug("Changed password for User: {}", user))
.then();
}
@Transactional(readOnly = true)
public Flux<AdminUserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAllWithAuthorities(pageable).map(AdminUserDTO::new);
}
@Transactional(readOnly = true)
public Flux<UserDTO> getAllPublicUsers(Pageable pageable) {
return userRepository.findAllByIdNotNullAndActivatedIsTrue(pageable).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Mono<Long> countManagedUsers() {
return userRepository.count();
}
@Transactional(readOnly = true)
public Mono<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public Mono<User> getUserWithAuthorities() {
return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin);
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p>
|
* This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
removeNotActivatedUsersReactively().blockLast();
}
@Transactional
public Flux<User> removeNotActivatedUsersReactively() {
return userRepository
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(
LocalDateTime.ofInstant(Instant.now().minus(3, ChronoUnit.DAYS), ZoneOffset.UTC)
)
.flatMap(user -> userRepository.delete(user).thenReturn(user))
.doOnNext(user -> log.debug("Deleted User: {}", user));
}
/**
* Gets a list of all the authorities.
* @return a list of all the authorities.
*/
@Transactional(readOnly = true)
public Flux<String> getAuthorities() {
return authorityRepository.findAll().map(Authority::getName);
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\service\UserService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Item {
private String color;
private String grade;
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "ITEM_TYPE_ID")
private ItemType itemType;
private String name;
private BigDecimal price;
@ManyToOne
@JoinColumn(name = "STORE_ID")
private Store store;
public String getColor() {
return color;
}
public String getGrade() {
return grade;
}
public Long getId() {
return id;
}
public ItemType getItemType() {
return itemType;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public Store getStore() {
return store;
}
public void setColor(String color) {
this.color = color;
}
|
public void setGrade(String grade) {
this.grade = grade;
}
public void setId(Long id) {
this.id = id;
}
public void setItemType(ItemType itemType) {
this.itemType = itemType;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setStore(Store store) {
this.store = store;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\boot\domain\Item.java
| 2
|
请完成以下Java代码
|
public void checkAccess(Path path, AccessMode... modes) throws IOException {
Path jarPath = getJarPath(path);
jarPath.getFileSystem().provider().checkAccess(jarPath, modes);
}
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().getFileAttributeView(jarPath, type, options);
}
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options)
throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, type, options);
}
@Override
|
public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, attributes, options);
}
protected Path getJarPath(Path path) {
return NestedPath.cast(path).getJarPath();
}
@Override
public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystemProvider.java
| 1
|
请完成以下Java代码
|
public class TryAndWaitUtil
{
public boolean tryAndWait(
final long maxWaitSeconds,
final long checkingIntervalMs,
@NonNull final Supplier<Boolean> worker,
@Nullable final Runnable logContext) throws InterruptedException
{
final long deadLineMillis = computeDeadLineMillis(maxWaitSeconds);
boolean conditionIsMet = false;
while (deadLineMillis > System.currentTimeMillis() && !conditionIsMet)
{
Thread.sleep(checkingIntervalMs);
conditionIsMet = worker.get();
|
}
if (!conditionIsMet && logContext != null)
{
logContext.run(); // output some helpful logging
}
return conditionIsMet;
}
private long computeDeadLineMillis(final long maxWaitSeconds)
{
final long nowMillis = System.currentTimeMillis(); // don't use SystemTime.millis(); because it's probably "rigged" for testing purposes,
final long deadLineMillis = maxWaitSeconds > 0 ? nowMillis + (maxWaitSeconds * 1000L) : Long.MAX_VALUE;
return deadLineMillis;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\TryAndWaitUtil.java
| 1
|
请完成以下Java代码
|
public String getPostingType()
{
return postingType;
}
@Override
public int getC_Period_ID()
{
return C_Period_ID;
}
@Override
public Date getDateAcct()
{
return new Date(dateAcctMs);
}
@Override
|
public int getAD_Client_ID()
{
return AD_Client_ID;
}
@Override
public int getAD_Org_ID()
{
return AD_Org_ID;
}
@Override
public int getPA_ReportCube_ID()
{
return PA_ReportCube_ID;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\aggregation\legacy\impl\FactAcctSummaryKey.java
| 1
|
请完成以下Java代码
|
void add(ExitCodeGenerator generator) {
Assert.notNull(generator, "'generator' must not be null");
this.generators.add(generator);
AnnotationAwareOrderComparator.sort(this.generators);
}
@Override
public Iterator<ExitCodeGenerator> iterator() {
return this.generators.iterator();
}
/**
* Get the final exit code that should be returned. The final exit code is the first
* non-zero exit code that is {@link ExitCodeGenerator#getExitCode generated}.
* @return the final exit code.
*/
int getExitCode() {
int exitCode = 0;
for (ExitCodeGenerator generator : this.generators) {
try {
int value = generator.getExitCode();
if (value != 0) {
exitCode = value;
break;
}
}
catch (Exception ex) {
exitCode = 1;
ex.printStackTrace();
}
}
return exitCode;
}
|
/**
* Adapts an {@link ExitCodeExceptionMapper} to an {@link ExitCodeGenerator}.
*/
private static class MappedExitCodeGenerator implements ExitCodeGenerator {
private final Throwable exception;
private final ExitCodeExceptionMapper mapper;
MappedExitCodeGenerator(Throwable exception, ExitCodeExceptionMapper mapper) {
this.exception = exception;
this.mapper = mapper;
}
@Override
public int getExitCode() {
return this.mapper.getExitCode(this.exception);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ExitCodeGenerators.java
| 1
|
请完成以下Java代码
|
public int getAD_UI_Element_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_Element_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();
}
/**
* TooltipIconName AD_Reference_ID=540912
* Reference name: TooltipIcon
*/
public static final int TOOLTIPICONNAME_AD_Reference_ID=540912;
/** text = text */
public static final String TOOLTIPICONNAME_Text = "text";
/** Set Tooltip Icon Name.
@param TooltipIconName Tooltip Icon Name */
@Override
public void setTooltipIconName (java.lang.String TooltipIconName)
{
|
set_Value (COLUMNNAME_TooltipIconName, TooltipIconName);
}
/** Get Tooltip Icon Name.
@return Tooltip Icon Name */
@Override
public java.lang.String getTooltipIconName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TooltipIconName);
}
/**
* Type AD_Reference_ID=540910
* Reference name: Type_AD_UI_ElementField
*/
public static final int TYPE_AD_Reference_ID=540910;
/** widget = widget */
public static final String TYPE_Widget = "widget";
/** tooltip = tooltip */
public static final String TYPE_Tooltip = "tooltip";
/** Set Art.
@param Type Art */
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Art */
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementField.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public Double getHighestSystemLoad() {
return highestSystemLoad;
}
public void setHighestSystemLoad(Double highestSystemLoad) {
this.highestSystemLoad = highestSystemLoad;
}
public Long getAvgRt() {
return avgRt;
}
public void setAvgRt(Long avgRt) {
this.avgRt = avgRt;
}
public Long getMaxThread() {
return maxThread;
}
public void setMaxThread(Long maxThread) {
this.maxThread = maxThread;
}
public Double getQps() {
return qps;
}
|
public void setQps(Double qps) {
this.qps = qps;
}
public Double getHighestCpuUsage() {
return highestCpuUsage;
}
public void setHighestCpuUsage(Double highestCpuUsage) {
this.highestCpuUsage = highestCpuUsage;
}
@Override
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
@Override
public SystemRule toRule() {
SystemRule rule = new SystemRule();
rule.setHighestSystemLoad(highestSystemLoad);
rule.setAvgRt(avgRt);
rule.setMaxThread(maxThread);
rule.setQps(qps);
rule.setHighestCpuUsage(highestCpuUsage);
return rule;
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\SystemRuleEntity.java
| 1
|
请完成以下Java代码
|
public String getConditionsType()
{
return X_C_Flatrate_Term.TYPE_CONDITIONS_Refund;
}
/**
* @return an empty iterator; invoice candidates that need to be there are created from {@link CandidateAssignmentService}.
*/
@Override
public Iterator<I_C_Flatrate_Term> retrieveTermsWithMissingCandidates(@Nullable final QueryLimit limit_IGNORED)
{
return ImmutableList
.<I_C_Flatrate_Term> of()
.iterator();
}
@NonNull
@Override
public CandidatesAutoCreateMode isMissingInvoiceCandidate(@Nullable final I_C_Flatrate_Term flatrateTerm)
{
return CandidatesAutoCreateMode.DONT;
}
/**
* Does nothing
*/
@Override
public void setSpecificInvoiceCandidateValues(
@NonNull final I_C_Invoice_Candidate ic,
@NonNull final I_C_Flatrate_Term term)
{
// nothing to do
}
/**
* @return always one, in the respective term's UOM
*/
@Override
public Quantity calculateQtyEntered(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord)
{
final UomId uomId = HandlerTools.retrieveUomId(invoiceCandidateRecord);
final I_C_UOM uomRecord = loadOutOfTrx(uomId, I_C_UOM.class);
|
return Quantity.of(ONE, uomRecord);
}
/**
* @return {@link PriceAndTax#NONE} because the tax remains unchanged and the price is updated in {@link CandidateAssignmentService}.
*/
@Override
public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord)
{
return PriceAndTax.NONE; // no changes to be made
}
@Override
public Consumer<I_C_Invoice_Candidate> getInvoiceScheduleSetterFunction(
@Nullable final Consumer<I_C_Invoice_Candidate> IGNORED_defaultImplementation)
{
return ic -> {
final FlatrateTermId flatrateTermId = FlatrateTermId.ofRepoId(ic.getRecord_ID());
final RefundContractRepository refundContractRepository = SpringContextHolder.instance.getBean(RefundContractRepository.class);
final RefundContract refundContract = refundContractRepository.getById(flatrateTermId);
final NextInvoiceDate nextInvoiceDate = refundContract.computeNextInvoiceDate(asLocalDate(ic.getDeliveryDate()));
ic.setC_InvoiceSchedule_ID(nextInvoiceDate.getInvoiceSchedule().getId().getRepoId());
ic.setDateToInvoice(asTimestamp(nextInvoiceDate.getDateToInvoice()));
};
}
/** Just return the record's current date */
@Override
public Timestamp calculateDateOrdered(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord)
{
return invoiceCandidateRecord.getDateOrdered();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\invoicecandidatehandler\FlatrateTermRefund_Handler.java
| 1
|
请完成以下Java代码
|
public List<User> fetchUsersCorrectApproach() {
ParameterizedTypeReference<List<User>> typeRef = new ParameterizedTypeReference<List<User>>() {
};
ResponseEntity<List<User>> response = restTemplate.exchange(baseUrl + "/api/users", HttpMethod.GET, null, typeRef);
return response.getBody();
}
public User fetchUser(Long id) {
return restTemplate.getForObject(baseUrl + "/api/users/" + id, User.class);
}
public User[] fetchUsersArray() {
return restTemplate.getForObject(baseUrl + "/api/users", User[].class);
}
|
public List<User> fetchUsersList() {
ParameterizedTypeReference<List<User>> typeRef = new ParameterizedTypeReference<List<User>>() {
};
ResponseEntity<List<User>> response = restTemplate.exchange(baseUrl + "/api/users", HttpMethod.GET, null, typeRef);
return response.getBody();
}
public List<User> fetchUsersListWithExistingReference() {
ResponseEntity<List<User>> response = restTemplate.exchange(baseUrl + "/api/users", HttpMethod.GET, null, USER_LIST);
return response.getBody();
}
}
|
repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\parametrizedtypereference\ApiService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ProcessApplicationStopService implements Service<ProcessApplicationStopService> {
private final static Logger LOGGER = Logger.getLogger(ProcessApplicationStopService.class.getName());
// for view-exposing ProcessApplicationComponents
protected final Supplier<ComponentView> paComponentViewSupplier;
protected final Supplier<ProcessApplicationInterface> noViewApplicationSupplier;
protected final Supplier<BpmPlatformPlugins> platformPluginsSupplier;
protected final Consumer<ProcessApplicationStopService> provider;
public ProcessApplicationStopService(Supplier<ComponentView> paComponentViewSupplier,
Supplier<ProcessApplicationInterface> noViewApplicationSupplier,
Supplier<BpmPlatformPlugins> platformPluginsSupplier, Consumer<ProcessApplicationStopService> provider) {
this.paComponentViewSupplier = paComponentViewSupplier;
this.noViewApplicationSupplier = noViewApplicationSupplier;
this.platformPluginsSupplier = platformPluginsSupplier;
this.provider = provider;
}
@Override
public ProcessApplicationStopService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
@Override
public void start(StartContext arg0) throws StartException {
provider.accept(this);
}
@Override
public void stop(StopContext arg0) {
provider.accept(null);
ManagedReference reference = null;
|
try {
// get the process application component
ProcessApplicationInterface processApplication = null;
if(paComponentViewSupplier != null) {
ComponentView componentView = paComponentViewSupplier.get();
reference = componentView.createInstance();
processApplication = (ProcessApplicationInterface) reference.getInstance();
}
else {
processApplication = noViewApplicationSupplier.get();
}
BpmPlatformPlugins bpmPlatformPlugins = platformPluginsSupplier.get();
List<BpmPlatformPlugin> plugins = bpmPlatformPlugins.getPlugins();
for (BpmPlatformPlugin bpmPlatformPlugin : plugins) {
bpmPlatformPlugin.postProcessApplicationUndeploy(processApplication);
}
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception while invoking BpmPlatformPlugin.postProcessApplicationUndeploy", e);
}
finally {
if(reference != null) {
reference.release();
}
}
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ProcessApplicationStopService.java
| 2
|
请完成以下Java代码
|
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
@Override
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_R_StatusCategory getR_StatusCategory() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class);
}
@Override
public void setR_StatusCategory(org.compiere.model.I_R_StatusCategory R_StatusCategory)
{
set_ValueFromPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class, R_StatusCategory);
|
}
/** Set Status Category.
@param R_StatusCategory_ID
Request Status Category
*/
@Override
public void setR_StatusCategory_ID (int R_StatusCategory_ID)
{
if (R_StatusCategory_ID < 1)
set_Value (COLUMNNAME_R_StatusCategory_ID, null);
else
set_Value (COLUMNNAME_R_StatusCategory_ID, Integer.valueOf(R_StatusCategory_ID));
}
/** Get Status Category.
@return Request Status Category
*/
@Override
public int getR_StatusCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_StatusCategory_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_RequestType.java
| 1
|
请完成以下Java代码
|
private WorkflowLauncherCaption computeCaption(@NonNull final DDOrderReference ddOrderReference)
{
return captionProvider.compute(ddOrderReference);
}
public WorkflowLaunchersFacetGroupList getFacets(@NonNull final WorkflowLaunchersFacetQuery query)
{
return getFacets(
newDDOrderReferenceQuery(query.getUserId())
.activeFacetIds(DistributionFacetIdsCollection.ofWorkflowLaunchersFacetIds(query.getActiveFacetIds()))
.build()
)
.toWorkflowLaunchersFacetGroupList(query.getActiveFacetIds());
}
private DistributionFacetsCollection getFacets(@NonNull final DDOrderReferenceQuery query)
{
final DistributionFacetsCollector collector = DistributionFacetsCollector.builder()
.ddOrderService(ddOrderService)
.productService(productService)
.warehouseService(warehouseService)
.sourceDocService(sourceDocService)
.build();
collect(query, collector);
return collector.toFacetsCollection();
}
private <T> void collect(
@NonNull final DDOrderReferenceQuery query,
@NonNull final DistributionOrderCollector<T> collector)
{
//
// Already started jobs
if (!query.isExcludeAlreadyStarted())
{
ddOrderService.streamDDOrders(DistributionJobQueries.ddOrdersAssignedToUser(query))
.forEach(collector::collect);
}
//
// New possible jobs
@NonNull final QueryLimit suggestedLimit = query.getSuggestedLimit();
if (suggestedLimit.isNoLimit() || !suggestedLimit.isLimitHitOrExceeded(collector.getCollectedItems()))
|
{
ddOrderService.streamDDOrders(DistributionJobQueries.toActiveNotAssignedDDOrderQuery(query))
.limit(suggestedLimit.minusSizeOf(collector.getCollectedItems()).toIntOr(Integer.MAX_VALUE))
.forEach(collector::collect);
}
}
@NonNull
private ImmutableSet<String> computeActions(
@NonNull final List<DDOrderReference> jobReferences,
@NonNull final UserId userId)
{
final ImmutableSet.Builder<String> actions = ImmutableSet.builder();
if (hasInTransitSchedules(jobReferences, userId))
{
actions.add(ACTION_DROP_ALL);
if (warehouseService.getTrolleyByUserId(userId).isPresent())
{
actions.add(ACTION_PRINT_IN_TRANSIT_REPORT);
}
}
return actions.build();
}
private boolean hasInTransitSchedules(
@NonNull final List<DDOrderReference> jobReferences,
@NonNull final UserId userId)
{
final LocatorId inTransitLocatorId = warehouseService.getTrolleyByUserId(userId)
.map(LocatorQRCode::getLocatorId)
.orElse(null);
if (inTransitLocatorId != null)
{
return loadingSupportServices.hasInTransitSchedules(inTransitLocatorId);
}
else
{
return jobReferences.stream().anyMatch(DDOrderReference::isInTransit);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DistributionWorkflowLaunchersProvider.java
| 1
|
请完成以下Java代码
|
/* package */ final class JUnitBeansMap
{
private static final Logger logger = LogManager.getLogger(JUnitBeansMap.class);
private final HashMap<ClassReference<?>, ArrayList<Object>> map = new HashMap<>();
public JUnitBeansMap()
{
}
private void assertJUnitMode()
{
if (!Adempiere.isUnitTestMode())
{
throw new AdempiereException("JUnit mode is not active!");
}
}
public synchronized void clear()
{
map.clear();
}
public synchronized <T> void registerJUnitBean(@NonNull final T beanImpl)
{
assertJUnitMode();
@SuppressWarnings("unchecked") final Class<T> beanType = (Class<T>)beanImpl.getClass();
registerJUnitBean(beanType, beanImpl);
}
public synchronized <BT, T extends BT> void registerJUnitBean(
@NonNull final Class<BT> beanType,
@NonNull final T beanImpl)
{
assertJUnitMode();
final ArrayList<Object> beans = map.computeIfAbsent(ClassReference.of(beanType), key -> new ArrayList<>());
if (!beans.contains(beanImpl))
{
beans.add(beanImpl);
logger.info("JUnit testing: Registered bean {}={}", beanType, beanImpl);
}
else
{
logger.info("JUnit testing: Skip registering bean because already registered {}={}", beanType, beanImpl);
}
}
public synchronized <BT, T extends BT> void registerJUnitBeans(
@NonNull final Class<BT> beanType,
@NonNull final List<T> beansToAdd)
{
assertJUnitMode();
final ArrayList<Object> beans = map.computeIfAbsent(ClassReference.of(beanType), key -> new ArrayList<>());
beans.addAll(beansToAdd);
|
logger.info("JUnit testing: Registered beans {}={}", beanType, beansToAdd);
}
public synchronized <T> T getBeanOrNull(@NonNull final Class<T> beanType)
{
assertJUnitMode();
final ArrayList<Object> beans = map.get(ClassReference.of(beanType));
if (beans == null || beans.isEmpty())
{
return null;
}
if (beans.size() > 1)
{
logger.warn("Found more than one bean for {} but returning the first one: {}", beanType, beans);
}
final T beanImpl = castBean(beans.get(0), beanType);
logger.debug("JUnit testing Returning manually registered bean: {}", beanImpl);
return beanImpl;
}
private static <T> T castBean(final Object beanImpl, final Class<T> ignoredBeanType)
{
@SuppressWarnings("unchecked") final T beanImplCasted = (T)beanImpl;
return beanImplCasted;
}
public synchronized <T> ImmutableList<T> getBeansOfTypeOrNull(@NonNull final Class<T> beanType)
{
assertJUnitMode();
List<Object> beanObjs = map.get(ClassReference.of(beanType));
if (beanObjs == null)
{
final List<Object> assignableBeans = map.values()
.stream()
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(impl -> beanType.isAssignableFrom(impl.getClass()))
.collect(Collectors.toList());
if (assignableBeans.isEmpty())
{
return null;
}
beanObjs = assignableBeans;
}
return beanObjs
.stream()
.map(beanObj -> castBean(beanObj, beanType))
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\JUnitBeansMap.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getIncotermText() {
return incotermText;
}
/**
* Sets the value of the incotermText property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIncotermText(String value) {
this.incotermText = value;
}
/**
* Gets the value of the incotermLocation property.
*
* @return
* possible object is
* {@link String }
*
*/
|
public String getIncotermLocation() {
return incotermLocation;
}
/**
* Sets the value of the incotermLocation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIncotermLocation(String value) {
this.incotermLocation = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\IncotermType.java
| 2
|
请完成以下Java代码
|
public final class AgeValues
{
private final ImmutableSet<Integer> agesInMonths;
@NonNull static AgeValues ofAgeInMonths(final Set<Integer> agesInMonths)
{
return new AgeValues(agesInMonths);
}
private AgeValues(final Set<Integer> ageInMonths)
{
this.agesInMonths = ImmutableSet.copyOf(ageInMonths);
}
/**
* Find the highest Age AttributeValue which is <= than the productionDate.
*/
public Age computeAgeInMonths(@NonNull final LocalDateTime productionDate)
{
|
final LocalDateTime now = SystemTime.asLocalDateTime();
final long months = ChronoUnit.MONTHS.between(productionDate, now);
int age = 0;
for (final Integer value : agesInMonths)
{
if (months < value)
{
break;
}
age = value;
}
return Age.ofAgeInMonths(age);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\age\AgeValues.java
| 1
|
请完成以下Java代码
|
private OrderStateEnum getOrderState(OrderProcessContext orderProcessContext) {
// 获取订单ID
String orderId = orderProcessContext.getOrderProcessReq().getOrderId();
if (StringUtils.isEmpty(orderId)) {
throw new CommonBizException(ExpCodeEnum.PROCESSREQ_ORDERID_NULL);
}
// 查询订单
OrderQueryReq orderQueryReq = new OrderQueryReq();
orderQueryReq.setId(orderId);
List<OrdersEntity> ordersEntityList = orderDAO.findOrders(orderQueryReq);
// 订单不存在
if (CollectionUtils.isEmpty(ordersEntityList)) {
throw new CommonBizException(ExpCodeEnum.ORDER_NULL);
}
// 获取订单状态
// TODO 更新订单状态时,要连带更新order表中的状态
|
OrderStateEnum orderStateEnum = ordersEntityList.get(0).getOrderStateEnum();
// 订单存在 & 订单状态不存在
if (orderStateEnum == null) {
throw new CommonBizException(ExpCodeEnum.ORDER_STATE_NULL);
}
// 返回订单状态
return orderStateEnum;
}
/**
* 设置订单允许的状态(子类必须重写这个函数)
*/
protected abstract void setAllowStateList();
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\idempotent\BaseIdempotencyComponent.java
| 1
|
请完成以下Java代码
|
public String getCode() {return code;}
public boolean isDrafted()
{
return this == Drafted;
}
public boolean isDraftedOrInProgress()
{
return this == Drafted
|| this == InProgress;
}
public boolean isReversed()
{
return this == Reversed;
}
public boolean isReversedOrVoided()
{
return this == Reversed
|| this == Voided;
}
public boolean isClosedReversedOrVoided()
{
return this == Closed
|| this == Reversed
|| this == Voided;
}
public boolean isCompleted()
{
return this == Completed;
}
public boolean isClosed()
{
return this == Closed;
}
public boolean isCompletedOrClosed()
{
return COMPLETED_OR_CLOSED_STATUSES.contains(this);
}
public static Set<DocStatus> completedOrClosedStatuses()
{
return COMPLETED_OR_CLOSED_STATUSES;
}
public boolean isCompletedOrClosedOrReversed()
{
return this == Completed
|| this == Closed
|| this == Reversed;
}
|
public boolean isCompletedOrClosedReversedOrVoided()
{
return this == Completed
|| this == Closed
|| this == Reversed
|| this == Voided;
}
public boolean isWaitingForPayment()
{
return this == WaitingPayment;
}
public boolean isInProgress()
{
return this == InProgress;
}
public boolean isInProgressCompletedOrClosed()
{
return this == InProgress
|| this == Completed
|| this == Closed;
}
public boolean isDraftedInProgressOrInvalid()
{
return this == Drafted
|| this == InProgress
|| this == Invalid;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isDraftedInProgressOrCompleted()
{
return this == Drafted
|| this == InProgress
|| this == Completed;
}
public boolean isNotProcessed()
{
return isDraftedInProgressOrInvalid()
|| this == Approved
|| this == NotApproved;
}
public boolean isVoided() {return this == Voided;}
public boolean isAccountable()
{
return this == Completed
|| this == Reversed
|| this == Voided;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocStatus.java
| 1
|
请完成以下Java代码
|
private Optional<DocOutBoundRecipients> getDocOutBoundRecipient(@NonNull final TableRecordReference recordRef)
{
try
{
final Object record = recordRef.getModel(Object.class);
return docOutboundLogMailRecipientRegistry
.getRecipient(
DocOutboundLogMailRecipientRequest.builder()
.recordRef(recordRef)
.clientId(InterfaceWrapperHelper.getClientId(record).orElseThrow(() -> new AdempiereException("Cannot get AD_Client_ID from " + record)))
.orgId(InterfaceWrapperHelper.getOrgId(record).orElseThrow(() -> new AdempiereException("Cannot get AD_Org_ID from " + record)))
.docTypeId(documentBL.getDocTypeId(record).orElse(null))
.build());
}
catch (final Exception ex)
{
logger.warn("Failed retrieving DocOutBoundRecipient from {}. Returning empty.", recordRef, ex);
return Optional.empty();
}
}
private static JSONDocumentPrintingOptions toJSONDocumentPrintingOptions(
@NonNull final DocumentPrintOptionsIncludingDescriptors printOptions,
@NonNull final String adLanguage)
{
final ArrayList<JSONDocumentPrintingOption> jsonOptionsList = new ArrayList<>();
for (final DocumentPrintOptionDescriptor option : printOptions.getOptionDescriptors())
{
final String caption = option.getName().translate(adLanguage);
final String description = option.getDescription().translate(adLanguage);
final String internalName = option.getInternalName();
final DocumentPrintOptionValue value = printOptions.getOptionValue(internalName);
|
jsonOptionsList.add(JSONDocumentPrintingOption.builder()
.caption(caption)
.description(description)
.internalName(internalName)
.value(value.isTrue())
.debugSourceName(value.getSourceName())
.build());
}
return JSONDocumentPrintingOptions.builder()
.caption(TranslatableStrings.adMessage(MSG_PrintOptions_Caption).translate(adLanguage))
.okButtonCaption(TranslatableStrings.adMessage(MSG_PrintOptions_OKButtonCaption).translate(adLanguage))
.options(jsonOptionsList)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\print\WebuiDocumentPrintService.java
| 1
|
请完成以下Java代码
|
protected void onInit(final IModelValidationEngine engine, final I_AD_Client client)
{
final boolean interceptDocValidate = isDocument && (initialCandidatesAutoCreateMode.isDoSomething());
final boolean interceptModelChange = (!isDocument && initialCandidatesAutoCreateMode.isDoSomething());
if (interceptDocValidate)
{
engine.addDocValidate(tableName, this);
}
if (interceptModelChange)
{
engine.addModelChange(tableName, this);
}
}
@Override
public void onDocValidate(@NonNull final Object model, @NonNull final DocTimingType timing)
{
Check.assume(isDocument, "isDocument flag is set"); // shall not happen
//
// Create missing invoice candidates for given document
if (timing == createInvoiceCandidatesTiming)
{
createMissingInvoiceCandidates(model);
}
}
@Override
public void onModelChange(@NonNull final Object model, @NonNull final ModelChangeType changeType)
{
//
|
// Create missing invoice candidates for given pseudo-document
if (!isDocument && changeType.isNewOrChange() && changeType.isAfter())
{
createMissingInvoiceCandidates(model);
}
}
/**
* Creates missing invoice candidates for given model, if this is enabled.
*/
private void createMissingInvoiceCandidates(@NonNull final Object model)
{
final CandidatesAutoCreateMode modeForCurrentModel = handler.getSpecificCandidatesAutoCreateMode(model);
switch (modeForCurrentModel)
{
case DONT: // just for completeness. we actually aren't called in this case
break;
case CREATE_CANDIDATES:
CreateMissingInvoiceCandidatesWorkpackageProcessor.schedule(model);
break;
case CREATE_CANDIDATES_AND_INVOICES:
generateIcsAndInvoices(model);
break;
}
}
private void generateIcsAndInvoices(@NonNull final Object model)
{
final TableRecordReference modelReference = TableRecordReference.of(model);
collector.collect(modelReference);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\ilhandler\ILHandlerModelInterceptor.java
| 1
|
请完成以下Java代码
|
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e))
{
popupMenu.show((Component)e.getSource(), e.getX(), e.getY());
}
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
*/
@Override
public void mouseEntered(MouseEvent e) {
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
*/
@Override
public void mouseExited(MouseEvent e) {
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
*/
@Override
public void mousePressed(MouseEvent e) {
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
@Override
public void mouseReleased(MouseEvent e) {
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == mRefresh)
{
if (m_goals != null)
{
for (MGoal m_goal : m_goals)
{
m_goal.updateGoal(true);
}
}
htmlUpdate(lastUrl);
Container parent = getParent();
if (parent != null)
{
parent.invalidate();
}
invalidate();
if (parent != null)
{
parent.repaint();
}
else
{
repaint();
}
}
}
class PageLoader implements Runnable
{
private JEditorPane html;
|
private URL url;
private Cursor cursor;
PageLoader( JEditorPane html, URL url, Cursor cursor )
{
this.html = html;
this.url = url;
this.cursor = cursor;
}
@Override
public void run()
{
if( url == null )
{
// restore the original cursor
html.setCursor( cursor );
// PENDING(prinz) remove this hack when
// automatic validation is activated.
Container parent = html.getParent();
parent.repaint();
}
else
{
Document doc = html.getDocument();
try {
html.setPage( url );
}
catch( IOException ioe )
{
html.setDocument( doc );
}
finally
{
// schedule the cursor to revert after
// the paint has happended.
url = null;
SwingUtilities.invokeLater( this );
}
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\apps\graph\HtmlDashboard.java
| 1
|
请完成以下Java代码
|
public PostingException addDetailMessage(final String detailMessageToAppend)
{
// If there is nothing to append, do nothing
if (Check.isBlank(detailMessageToAppend))
{
return this;
}
//
// Set append the detail message
if (TranslatableStrings.isEmpty(_detailMessage))
{
_detailMessage = TranslatableStrings.anyLanguage(detailMessageToAppend);
}
else
{
_detailMessage = TranslatableStrings.join("\n", _detailMessage, detailMessageToAppend);
}
resetMessageBuilt();
return this;
}
public PostingException setFact(final Fact fact)
{
_fact = fact;
resetMessageBuilt();
return this;
}
public Fact getFact()
{
return _fact;
}
private FactLine getFactLine()
{
return _factLine;
}
public PostingException setFactLine(final FactLine factLine)
{
this._factLine = factLine;
resetMessageBuilt();
return this;
}
/**
* @return <code>true</code> if the document's "Posted" status shall not been changed.
*/
public boolean isPreserveDocumentPostedStatus()
{
return _preserveDocumentPostedStatus;
}
/**
* If set, the document's "Posted" status shall not been changed.
*/
|
public PostingException setPreserveDocumentPostedStatus()
{
_preserveDocumentPostedStatus = true;
resetMessageBuilt();
return this;
}
public PostingException setDocLine(final DocLine<?> docLine)
{
_docLine = docLine;
resetMessageBuilt();
return this;
}
public DocLine<?> getDocLine()
{
return _docLine;
}
@SuppressWarnings("unused")
public PostingException setLogLevel(@NonNull final Level logLevel)
{
this._logLevel = logLevel;
return this;
}
/**
* @return recommended log level to be used when reporting this issue
*/
public Level getLogLevel()
{
return _logLevel;
}
@Override
public PostingException setParameter(
final @NonNull String parameterName,
final @Nullable Object parameterValue)
{
super.setParameter(parameterName, parameterValue);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\PostingException.java
| 1
|
请完成以下Java代码
|
public CountResultDto getTenantCount(UriInfo uriInfo) {
TenantQueryDto queryDto = new TenantQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
TenantQuery query = queryDto.toQuery(getProcessEngine());
long count = query.count();
return new CountResultDto(count);
}
@Override
public void createTenant(TenantDto dto) {
if (getIdentityService().isReadOnly()) {
throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only.");
}
Tenant newTenant = getIdentityService().newTenant(dto.getId());
dto.update(newTenant);
getIdentityService().saveTenant(newTenant);
}
@Override
public ResourceOptionsDto availableOperations(UriInfo context) {
UriBuilder baseUriBuilder = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(TenantRestService.PATH);
|
ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();
// GET /
URI baseUri = baseUriBuilder.build();
resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");
// GET /count
URI countUri = baseUriBuilder.clone().path("/count").build();
resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");
// POST /create
if (!getIdentityService().isReadOnly() && isAuthorized(CREATE)) {
URI createUri = baseUriBuilder.clone().path("/create").build();
resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
}
return resourceOptionsDto;
}
protected IdentityService getIdentityService() {
return getProcessEngine().getIdentityService();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\TenantRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public static class DefaultKafkaTemplateObservationConvention implements KafkaTemplateObservationConvention {
/**
* A singleton instance of the convention.
*/
public static final DefaultKafkaTemplateObservationConvention INSTANCE =
new DefaultKafkaTemplateObservationConvention();
@Override
public KeyValues getLowCardinalityKeyValues(KafkaRecordSenderContext context) {
return KeyValues.of(
TemplateLowCardinalityTags.BEAN_NAME.withValue(context.getBeanName()),
TemplateLowCardinalityTags.MESSAGING_SYSTEM.withValue("kafka"),
TemplateLowCardinalityTags.MESSAGING_OPERATION.withValue("publish"),
TemplateLowCardinalityTags.MESSAGING_DESTINATION_KIND.withValue("topic"),
TemplateLowCardinalityTags.MESSAGING_DESTINATION_NAME.withValue(context.getDestination()));
}
|
@Override
public String getContextualName(KafkaRecordSenderContext context) {
return context.getDestination() + " send";
}
@Override
@NonNull
public String getName() {
return "spring.kafka.template";
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaTemplateObservation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setPointcutMap(Map<String, List<ConfigAttribute>> map) {
Assert.notEmpty(map, "configAttributes cannot be empty");
for (String expression : map.keySet()) {
List<ConfigAttribute> value = map.get(expression);
addPointcut(expression, value);
}
}
private void addPointcut(String pointcutExpression, List<ConfigAttribute> definition) {
Assert.hasText(pointcutExpression, "An AspectJ pointcut expression is required");
Assert.notNull(definition, "A List of ConfigAttributes is required");
pointcutExpression = replaceBooleanOperators(pointcutExpression);
this.pointcutMap.put(pointcutExpression, definition);
// Parse the presented AspectJ pointcut expression and add it to the cache
this.pointCutExpressions.add(this.parser.parsePointcutExpression(pointcutExpression));
if (logger.isDebugEnabled()) {
logger.debug("AspectJ pointcut expression '" + pointcutExpression
|
+ "' registered for security configuration attribute '" + definition + "'");
}
}
/**
* @see org.springframework.aop.aspectj.AspectJExpressionPointcut#replaceBooleanOperators
*/
private String replaceBooleanOperators(String pcExpr) {
pcExpr = StringUtils.replace(pcExpr, " and ", " && ");
pcExpr = StringUtils.replace(pcExpr, " or ", " || ");
pcExpr = StringUtils.replace(pcExpr, " not ", " ! ");
return pcExpr;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\ProtectPointcutPostProcessor.java
| 2
|
请完成以下Java代码
|
protected DeadLetterJobEntityManager getDeadLetterJobEntityManager() {
return getProcessEngineConfiguration().getDeadLetterJobEntityManager();
}
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager();
}
protected HistoricDetailEntityManager getHistoricDetailEntityManager() {
return getProcessEngineConfiguration().getHistoricDetailEntityManager();
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager();
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricVariableInstanceEntityManager();
}
|
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricTaskInstanceEntityManager();
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getProcessEngineConfiguration().getHistoricIdentityLinkEntityManager();
}
protected AttachmentEntityManager getAttachmentEntityManager() {
return getProcessEngineConfiguration().getAttachmentEntityManager();
}
protected CommentEntityManager getCommentEntityManager() {
return getProcessEngineConfiguration().getCommentEntityManager();
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java
| 1
|
请完成以下Java代码
|
public void verifyClaims(Map claims) {
int exp = (int) claims.get("exp");
Date expireDate = new Date(exp * 1000L);
Date now = new Date();
if (expireDate.before(now) || !claims.get("iss").equals(issuer) || !claims.get("aud").equals(clientId)) {
throw new RuntimeException("Invalid claims");
}
}
private RsaVerifier verifier(String kid) throws Exception {
JwkProvider provider = new UrlJwkProvider(new URI(jwkUrl).toURL());
Jwk jwk = provider.get(kid);
return new RsaVerifier((RSAPublicKey) jwk.getPublicKey());
}
|
public void setRestTemplate(OAuth2RestTemplate restTemplate2) {
restTemplate = restTemplate2;
}
private static class NoopAuthenticationManager implements AuthenticationManager {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager");
}
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\java\com\baeldung\openid\oidc\OpenIdConnectFilter.java
| 1
|
请完成以下Java代码
|
public final DefaultPaymentBuilder orderId(@Nullable final OrderId orderId)
{
assertNotBuilt();
if (orderId != null)
{
payment.setC_Order_ID(orderId.getRepoId());
}
return this;
}
public final DefaultPaymentBuilder orderExternalId(@Nullable final String orderExternalId)
{
assertNotBuilt();
if (Check.isNotBlank(orderExternalId))
{
payment.setExternalOrderId(orderExternalId);
}
return this;
}
public final DefaultPaymentBuilder isAutoAllocateAvailableAmt(final boolean isAutoAllocateAvailableAmt)
|
{
assertNotBuilt();
payment.setIsAutoAllocateAvailableAmt(isAutoAllocateAvailableAmt);
return this;
}
private DefaultPaymentBuilder fromOrder(@NonNull final I_C_Order order)
{
adOrgId(OrgId.ofRepoId(order.getAD_Org_ID()));
orderId(OrderId.ofRepoId(order.getC_Order_ID()));
bpartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID()));
currencyId(CurrencyId.ofRepoId(order.getC_Currency_ID()));
final SOTrx soTrx = SOTrx.ofBoolean(order.isSOTrx());
direction(PaymentDirection.ofSOTrxAndCreditMemo(soTrx, false));
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\DefaultPaymentBuilder.java
| 1
|
请完成以下Java代码
|
private boolean InjectError() {
// We create ~5% error.
return ThreadLocalRandom.current().nextInt(0, 99) >= 95;
}
@Override
public void unaryRpc(UnaryRequest request,
StreamObserver<UnaryResponse> responseObserver) {
if (InjectError()) {
responseObserver.onError(Status.INTERNAL.asException());
} else {
responseObserver.onNext(UnaryResponse.newBuilder().setMessage(request.getMessage()).build());
responseObserver.onCompleted();
}
}
@Override
public StreamObserver<ClientStreamingRequest> clientStreamingRpc(
StreamObserver<ClientStreamingResponse> responseObserver) {
return new StreamObserver<>() {
@Override
public void onNext(ClientStreamingRequest value) {
responseObserver.onNext(
ClientStreamingResponse.newBuilder().setMessage(value.getMessage()).build());
}
@Override
public void onError(Throwable t) {
responseObserver.onError(t);
}
@Override
public void onCompleted() {
if (InjectError()) {
responseObserver.onError(Status.INTERNAL.asException());
} else {
responseObserver.onCompleted();
}
}
};
}
|
@Override
public void serverStreamingRpc(ServerStreamingRequest request,
StreamObserver<ServerStreamingResponse> responseObserver) {
if (InjectError()) {
responseObserver.onError(Status.INTERNAL.asException());
} else {
responseObserver.onNext(
ServerStreamingResponse.newBuilder().setMessage(request.getMessage()).build());
responseObserver.onCompleted();
}
}
@Override
public StreamObserver<BidiStreamingRequest> bidiStreamingRpc(
StreamObserver<BidiStreamingResponse> responseObserver) {
return new StreamObserver<>() {
@Override
public void onNext(BidiStreamingRequest value) {
responseObserver.onNext(
BidiStreamingResponse.newBuilder().setMessage(value.getMessage()).build());
}
@Override
public void onError(Throwable t) {
responseObserver.onError(t);
}
@Override
public void onCompleted() {
if (InjectError()) {
responseObserver.onError(Status.INTERNAL.asException());
} else {
responseObserver.onCompleted();
}
}
};
}
}
|
repos\grpc-spring-master\examples\grpc-observability\backend\src\main\java\net\devh\boot\grpc\examples\observability\backend\ExampleServiceImpl.java
| 1
|
请完成以下Java代码
|
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";
}
@Override
public int hashCode() {
|
return Objects.hash(id, name, score);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
return id == other.id && Objects.equals(name, other.name) && score == other.score;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\spring\data\persistence\search\Student.java
| 1
|
请完成以下Java代码
|
private String toJson(ProjectRequestDocument stats) {
try {
return this.objectMapper.writeValueAsString(stats);
}
catch (JsonProcessingException ex) {
throw new IllegalStateException("Cannot convert to JSON", ex);
}
}
private static ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper;
}
// For testing purposes only
protected RestTemplate getRestTemplate() {
return this.restTemplate;
}
protected void updateRequestUrl(URI requestUrl) {
this.requestUrl = requestUrl;
}
private static RestTemplateBuilder configureAuthorization(RestTemplateBuilder restTemplateBuilder, Elastic elastic,
UriComponentsBuilder uriComponentsBuilder) {
String userInfo = uriComponentsBuilder.build().getUserInfo();
if (StringUtils.hasText(userInfo)) {
|
String[] credentials = userInfo.split(":");
return restTemplateBuilder.basicAuthentication(credentials[0], credentials[1]);
}
else if (StringUtils.hasText(elastic.getUsername())) {
return restTemplateBuilder.basicAuthentication(elastic.getUsername(), elastic.getPassword());
}
return restTemplateBuilder;
}
private static URI determineEntityUrl(Elastic elastic) {
String entityUrl = elastic.getUri() + "/" + elastic.getIndexName() + "/_doc/";
try {
return new URI(entityUrl);
}
catch (URISyntaxException ex) {
throw new IllegalStateException("Cannot create entity URL: " + entityUrl, ex);
}
}
}
|
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectGenerationStatPublisher.java
| 1
|
请完成以下Java代码
|
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_PrintFont[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Print Font.
@param AD_PrintFont_ID
Maintain Print Font
*/
public void setAD_PrintFont_ID (int AD_PrintFont_ID)
{
if (AD_PrintFont_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_PrintFont_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_PrintFont_ID, Integer.valueOf(AD_PrintFont_ID));
}
/** Get Print Font.
@return Maintain Print Font
*/
public int getAD_PrintFont_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintFont_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Validation code.
@param Code
Validation Code
*/
public void setCode (String Code)
{
set_Value (COLUMNNAME_Code, Code);
}
/** Get Validation code.
@return Validation Code
*/
public String getCode ()
{
return (String)get_Value(COLUMNNAME_Code);
}
/** Set Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
|
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintFont.java
| 1
|
请完成以下Java代码
|
public static void validateOnBeforeSave(@NonNull final I_AD_PrinterHW printerRecord)
{
fromRecord(printerRecord, ImmutableListMultimap.of());
}
@NonNull
private static HardwarePrinter fromRecord(
@NonNull final I_AD_PrinterHW printerRecord,
@NonNull final ImmutableListMultimap<HardwarePrinterId, HardwareTray> traysByPrinterId)
{
final HardwarePrinterId id = HardwarePrinterId.ofRepoId(printerRecord.getAD_PrinterHW_ID());
return HardwarePrinter.builder()
.id(id)
.name(printerRecord.getName())
.outputType(OutputType.ofCode(printerRecord.getOutputType()))
.externalSystemParentConfigId(ExternalSystemParentConfigId.ofRepoIdOrNull(printerRecord.getExternalSystem_Config_ID()))
.ippUrl(extractIPPUrl(printerRecord))
.trays(traysByPrinterId.get(id))
.build();
}
@Nullable
private static URI extractIPPUrl(final @NonNull I_AD_PrinterHW printerRecord)
{
final String ippUrl = StringUtils.trimBlankToNull(printerRecord.getIPP_URL());
if (ippUrl == null)
{
return null;
}
return URI.create(ippUrl);
}
@NonNull
private static HardwareTray fromRecord(@NonNull final I_AD_PrinterHW_MediaTray trayRecord)
{
final HardwareTrayId trayId = HardwareTrayId.ofRepoId(trayRecord.getAD_PrinterHW_ID(), trayRecord.getAD_PrinterHW_MediaTray_ID());
return new HardwareTray(trayId, trayRecord.getName(), trayRecord.getTrayNumber());
}
public void deleteCalibrations(@NonNull final HardwarePrinterId printerId) {printingDAO.deleteCalibrations(printerId);}
public void deleteMediaTrays(@NonNull final HardwarePrinterId hardwarePrinterId) {printingDAO.deleteMediaTrays(hardwarePrinterId);}
public void deleteMediaSizes(@NonNull final HardwarePrinterId hardwarePrinterId) {printingDAO.deleteMediaSizes(hardwarePrinterId);}
//
//
//
//
//
private static class HardwarePrinterMap
{
private final ImmutableMap<HardwarePrinterId, HardwarePrinter> byId;
private HardwarePrinterMap(final List<HardwarePrinter> list)
{
this.byId = Maps.uniqueIndex(list, HardwarePrinter::getId);
}
|
public HardwarePrinter getById(@NonNull final HardwarePrinterId id)
{
final HardwarePrinter hardwarePrinter = byId.get(id);
if (hardwarePrinter == null)
{
throw new AdempiereException("No active hardware printer found for id " + id);
}
return hardwarePrinter;
}
public Collection<HardwarePrinter> getByIds(final @NonNull Collection<HardwarePrinterId> ids)
{
return streamByIds(ids).collect(ImmutableList.toImmutableList());
}
public Stream<HardwarePrinter> streamByIds(final @NonNull Collection<HardwarePrinterId> ids)
{
if (ids.isEmpty())
{
return Stream.empty();
}
return ids.stream()
.map(byId::get)
.filter(Objects::nonNull);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\HardwarePrinterRepository.java
| 1
|
请完成以下Java代码
|
public class XssProtectionProvider extends HeaderSecurityProvider {
public static final String HEADER_NAME = "X-XSS-Protection";
public static final XssProtectionOption HEADER_DEFAULT_VALUE = XssProtectionOption.BLOCK;
public static final String DISABLED_PARAM = "xssProtectionDisabled";
public static final String OPTION_PARAM = "xssProtectionOption";
public static final String VALUE_PARAM = "xssProtectionValue";
public Map<String, String> initParams() {
initParams.put(DISABLED_PARAM, null);
initParams.put(OPTION_PARAM, null);
initParams.put(VALUE_PARAM, null);
return initParams;
}
public void parseParams() {
String disabled = initParams.get(DISABLED_PARAM);
if (ServletFilterUtil.isEmpty(disabled)) {
setDisabled(false);
} else {
setDisabled(Boolean.parseBoolean(disabled));
}
String value = initParams.get(VALUE_PARAM);
String option = initParams.get(OPTION_PARAM);
if (!isDisabled()) {
if (!ServletFilterUtil.isEmpty(value) && !ServletFilterUtil.isEmpty(option)) {
throw new ProcessEngineException(this.getClass().getSimpleName() + ": cannot set both " + VALUE_PARAM + " and " + OPTION_PARAM + ".");
}
if (!ServletFilterUtil.isEmpty(value)) {
setValue(value);
} else if (!ServletFilterUtil.isEmpty(option)) {
|
setValue(parseValue(option).getHeaderValue());
} else {
setValue(HEADER_DEFAULT_VALUE.getHeaderValue());
}
}
}
protected XssProtectionOption parseValue(String optionValue) {
for (XssProtectionOption option : XssProtectionOption.values()) {
if (option.getName().equalsIgnoreCase(optionValue)) {
return option;
}
}
throw new ProcessEngineException(this.getClass().getSimpleName() + ": cannot set non-existing option " + optionValue + " for " + OPTION_PARAM + ".");
}
public String getHeaderName() {
return HEADER_NAME;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\headersec\provider\impl\XssProtectionProvider.java
| 1
|
请完成以下Java代码
|
public class LockChangeFailedException extends LockException
{
/**
*
*/
private static final long serialVersionUID = -6916683766355333023L;
public LockChangeFailedException(final String message, final Throwable cause)
{
super(message, cause);
}
@Override
public LockChangeFailedException setParameter(@NonNull String name, Object value)
{
super.setParameter(name, value);
return this;
}
@Override
public LockChangeFailedException setRecord(final @NonNull TableRecordReference record)
{
|
super.setRecord(record);
return this;
}
@Override
public LockChangeFailedException setSql(String sql, Object[] sqlParams)
{
super.setSql(sql, sqlParams);
return this;
}
public LockChangeFailedException setLock(final ILock lock)
{
return setParameter("Lock", lock);
}
public LockChangeFailedException setLockCommand(final ILockCommand lockCommand)
{
setParameter("Lock command", lockCommand);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\exceptions\LockChangeFailedException.java
| 1
|
请完成以下Java代码
|
private IPricingResult computeBasePriceOrNull()
{
final PriceLimitRestrictions priceLimitRestrictions = getPriceLimitRestrictions();
final IEditablePricingContext basePricingContext = context.getPricingContext().copy();
basePricingContext.setPricingSystemId(priceLimitRestrictions.getBasePricingSystemId());
basePricingContext.setPriceListId(null); // will be recomputed
basePricingContext.setPriceListVersionId(null); // will be recomputed
basePricingContext.setDisallowDiscount(true);
final IPricingResult basePriceResult = pricingBL.calculatePrice(basePricingContext);
if (!basePriceResult.isCalculated())
{
return null;
}
return basePriceResult;
}
private BigDecimal getPaymentTermDiscountPercent()
{
final PaymentTermId paymentTermId = context.getPaymentTermId();
if (paymentTermId == null)
{
return BigDecimal.ZERO;
}
return paymentTermsRepo.getById(paymentTermId)
.getDiscount()
.toBigDecimal();
}
@lombok.Value
private static class PriceLimit
{
BigDecimal valueAsBigDecimal;
BigDecimal basePrice;
BigDecimal priceAddAmt;
BigDecimal discountPercentToSubtract;
BigDecimal paymentTermDiscountPercentToAdd;
|
CurrencyPrecision precision;
@lombok.Builder
private PriceLimit(
@lombok.NonNull final BigDecimal basePrice,
@lombok.NonNull final BigDecimal priceAddAmt,
@lombok.NonNull final BigDecimal discountPercentToSubtract,
@lombok.NonNull final BigDecimal paymentTermDiscountPercentToAdd,
@lombok.NonNull final CurrencyPrecision precision)
{
this.basePrice = NumberUtils.stripTrailingDecimalZeros(basePrice);
this.priceAddAmt = NumberUtils.stripTrailingDecimalZeros(priceAddAmt);
this.discountPercentToSubtract = NumberUtils.stripTrailingDecimalZeros(discountPercentToSubtract);
this.paymentTermDiscountPercentToAdd = NumberUtils.stripTrailingDecimalZeros(paymentTermDiscountPercentToAdd);
this.precision = precision;
//
// Formula:
// PriceLimit = (basePrice + priceAddAmt) - discountPercentToSubtract% + paymentTermDiscountPercentToAdd%
BigDecimal value = basePrice.add(priceAddAmt);
final BigDecimal multiplier = Env.ONEHUNDRED.subtract(discountPercentToSubtract).add(paymentTermDiscountPercentToAdd)
.divide(Env.ONEHUNDRED, 12, RoundingMode.HALF_UP);
if (multiplier.compareTo(Env.ONEHUNDRED) != 0)
{
value = precision.round(value.multiply(multiplier));
}
valueAsBigDecimal = value;
}
public ITranslatableString toFormulaString()
{
return TranslatableStrings.builder()
.append("(").append(basePrice, DisplayType.CostPrice).append(" + ").append(priceAddAmt, DisplayType.CostPrice).append(")")
.append(" - ").append(discountPercentToSubtract, DisplayType.Number).append("%")
.append(" + ").append(paymentTermDiscountPercentToAdd, DisplayType.Number).append("%")
.append(" (precision: ").append(precision.toInt()).append(")")
.build();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\pricing\PharmaPriceLimitRuleInstance.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getTypeName() {
return TYPE_TRANSIENT;
}
@Override
public void setTypeName(String typeName) {
// Not relevant
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getTaskId() {
return taskId;
}
@Override
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@Override
public String getMetaInfo() {
return metaInfo;
}
@Override
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
// The methods below are not relevant, as getValue() is used directly to return the value set during the transaction
@Override
public String getTextValue() {
return null;
}
@Override
public void setTextValue(String textValue) {
}
@Override
public String getTextValue2() {
return null;
}
|
@Override
public void setTextValue2(String textValue2) {
}
@Override
public Long getLongValue() {
return null;
}
@Override
public void setLongValue(Long longValue) {
}
@Override
public Double getDoubleValue() {
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {
}
@Override
public byte[] getBytes() {
return null;
}
@Override
public void setBytes(byte[] bytes) {
}
@Override
public Object getCachedValue() {
return null;
}
@Override
public void setCachedValue(Object cachedValue) {
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\TransientVariableInstance.java
| 2
|
请完成以下Java代码
|
public String toString()
{
StringBuilder sb = new StringBuilder ("X_M_QualityInsp_LagerKonf[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Lagerkonferenz.
@param M_QualityInsp_LagerKonf_ID Lagerkonferenz */
@Override
public void setM_QualityInsp_LagerKonf_ID (int M_QualityInsp_LagerKonf_ID)
{
if (M_QualityInsp_LagerKonf_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_ID, Integer.valueOf(M_QualityInsp_LagerKonf_ID));
}
/** Get Lagerkonferenz.
@return Lagerkonferenz */
@Override
public int getM_QualityInsp_LagerKonf_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityInsp_LagerKonf_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
|
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf.java
| 1
|
请完成以下Java代码
|
public void setServerUrl(final String serverUrl)
{
this.serverUrl = serverUrl;
}
protected Map<String, String> createInitialUrlParams()
{
final Map<String, String> params = new HashMap<String, String>();
params.put(IArchiveEndpoint.PARAM_SessionId, Integer.toString(getAD_Session_ID()));
return params;
}
private URL getURL(final String relativePath, final Map<String, String> params)
{
final String serverUrl = getServerUrl();
final StringBuilder urlStrBuf = new StringBuilder();
urlStrBuf.append(serverUrl);
if (!urlStrBuf.toString().endsWith("/") && !IArchiveEndpoint.PATH_Service.startsWith("/"))
{
urlStrBuf.append("/");
}
urlStrBuf.append(IArchiveEndpoint.PATH_Service);
if (!urlStrBuf.toString().endsWith("/") && !relativePath.startsWith("/"))
{
urlStrBuf.append("/");
}
urlStrBuf.append(relativePath);
final String urlStr = MapFormat.format(urlStrBuf.toString(), params);
try
{
return new URL(urlStr);
}
catch (final MalformedURLException e)
{
throw new RuntimeException("Invalid URL " + urlStr, e);
}
}
private <T> T executePost(final String path, final Map<String, String> params, final Object request, final Class<T> responseClass)
{
final URL url = getURL(path, params);
final PostMethod httpPost = new PostMethod(url.toString());
final byte[] data = beanEncoder.encode(request);
final RequestEntity entity = new ByteArrayRequestEntity(data, beanEncoder.getContentType());
httpPost.setRequestEntity(entity);
int result = -1;
InputStream in = null;
try
{
result = executeHttpPost(httpPost);
|
in = httpPost.getResponseBodyAsStream();
if (result != 200)
{
final String errorMsg = in == null ? "code " + result : IOStreamUtils.toString(in);
throw new AdempiereException("Error " + result + " while posting on " + url + ": " + errorMsg);
}
if (responseClass != null)
{
final T response = beanEncoder.decodeStream(in, responseClass);
return response;
}
}
catch (final Exception e)
{
throw new AdempiereException(e);
}
finally
{
IOStreamUtils.close(in);
in = null;
}
return null;
}
private int executeHttpPost(final PostMethod httpPost) throws HttpException, IOException
{
final int result = httpclient.executeMethod(httpPost);
RestHttpArchiveEndpoint.logger.trace("Result code: {}", result);
// final DefaultMethodRetryHandler retryHandler = new DefaultMethodRetryHandler();
// retryHandler.setRetryCount(3);
// httpPost.setMethodRetryHandler(retryHandler);
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\RestHttpArchiveEndpoint.java
| 1
|
请完成以下Java代码
|
public final Timestamp getParameterAsTimestamp(final String parameterName)
{
final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName);
return processInfoParameter != null ? processInfoParameter.getParameterAsTimestamp() : null;
}
@Override
public LocalDate getParameterAsLocalDate(final String parameterName)
{
final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName);
return processInfoParameter != null ? processInfoParameter.getParameterAsLocalDate() : null;
}
@Override
public ZonedDateTime getParameterAsZonedDateTime(final String parameterName)
{
final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName);
return processInfoParameter != null ? processInfoParameter.getParameterAsZonedDateTime() : null;
}
@Override
public Instant getParameterAsInstant(final String parameterName)
{
final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName);
return processInfoParameter != null ? processInfoParameter.getParameterAsInstant() : null;
}
@Override
public Timestamp getParameter_ToAsTimestamp(final String parameterName)
{
final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName);
return processInfoParameter != null ? processInfoParameter.getParameter_ToAsTimestamp() : null;
}
@Override
public LocalDate getParameter_ToAsLocalDate(final String parameterName)
{
|
final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName);
return processInfoParameter != null ? processInfoParameter.getParameter_ToAsLocalDate() : null;
}
@Override
public ZonedDateTime getParameter_ToAsZonedDateTime(final String parameterName)
{
final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName);
return processInfoParameter != null ? processInfoParameter.getParameter_ToAsZonedDateTime() : null;
}
/**
* Returns an immutable collection of the wrapped process parameter names.
*/
@Override
public Collection<String> getParameterNames()
{
return ImmutableSet.copyOf(getParametersMap().keySet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessParams.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void prepareRestAPIContext(@NonNull final Exchange exchange)
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
final ScriptedImportConversionRestAPIContext context = ScriptedImportConversionRestAPIContext.builder()
.request(request)
.build();
exchange.setProperty(PROPERTY_SCRIPTED_SCRIPTED_IMPORTED_CONVERSION_CONTEXT, context);
}
private void prepareExternalStatusCreateRequest(@NonNull final Exchange exchange, @NonNull final JsonExternalStatus externalStatus)
{
final ScriptedImportConversionRestAPIContext context = ProcessorHelper.getPropertyOrThrowError(exchange, PROPERTY_SCRIPTED_SCRIPTED_IMPORTED_CONVERSION_CONTEXT, ScriptedImportConversionRestAPIContext.class);
final JsonExternalSystemRequest request = context.getRequest();
final JsonStatusRequest jsonStatusRequest = JsonStatusRequest.builder()
.status(externalStatus)
.pInstanceId(request.getAdPInstanceId())
.build();
final ExternalStatusCreateCamelRequest camelRequest = ExternalStatusCreateCamelRequest.builder()
.jsonStatusRequest(jsonStatusRequest)
.externalSystemConfigType(getExternalSystemTypeCode())
.externalSystemChildConfigValue(request.getExternalSystemChildConfigValue())
.serviceValue(getServiceValue())
.build();
exchange.getIn().setBody(camelRequest, JsonExternalSystemRequest.class);
|
}
@Override
public String getServiceValue()
{
return "defaultRestAPIScriptedImportConversion";
}
@Override
public String getExternalSystemTypeCode()
{
return SCRIPTED_IMPORT_CONVERSION_SYSTEM_NAME;
}
@Override
public String getEnableCommand()
{
return ENABLE_RESOURCE_ROUTE;
}
@Override
public String getDisableCommand()
{
return DISABLE_RESOURCE_ROUTE;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-scriptedadapter\src\main\java\de\metas\camel\externalsystems\scriptedadapter\convertmsg\to_mf\ScriptedImportConversionRestAPIRouteBuilder.java
| 2
|
请完成以下Java代码
|
protected Long compute() {
if (end - start <= threshold) {
long count = 0;
for (int i = 0; i <= end - start; i++) {
count = count + start + i;
}
System.out.println(Thread.currentThread().getName() + " 小计结果: " + count);
return count;
} else {
// 如果任务大于阈值,就分裂成三个子任务计算
long slip = (end - start) / 3;
ForkJoinCountTask oneTask = new ForkJoinCountTask(start, start + slip);
ForkJoinCountTask twoTask = new ForkJoinCountTask(start + slip + 1, start + slip * 2);
ForkJoinCountTask threeTask = new ForkJoinCountTask(start + slip * 2 + 1, end);
// 提交子任务到框架去执行
invokeAll(oneTask, twoTask, threeTask);
// 等待子任务执行完,得到其结果,并合并子任务
return oneTask.join() + twoTask.join() + threeTask.join();
}
|
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
ForkJoinPool pool = new ForkJoinPool();
// 生成一个计算任务,负责计算1+2+3+n
ForkJoinCountTask countTask = new ForkJoinCountTask(1, 1000000);
// 执行一个任务(同步执行,任务会阻塞在这里直到任务执行完成)
pool.invoke(countTask);
// 异常检查
if (countTask.isCompletedAbnormally()) {
Throwable throwable = countTask.getException();
if (Objects.nonNull(throwable)) {
System.out.println(throwable.getMessage());
}
}
// join方法是一个阻塞方法,会等待任务执行完成
System.out.println("计算为:" + countTask.join() + ", 耗时:" + (System.currentTimeMillis() - start) + "毫秒");
}
}
|
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\ForkJoinCountTask.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object obj) {
return obj == this;
}
@Override
public Object invoke(ELContext context, Object[] params) {
try {
return method.invoke(null, params);
} catch (IllegalAccessException e) {
throw new ELException(LocalMessages.get("error.identifier.method.access", name));
} catch (IllegalArgumentException e) {
throw new ELException(LocalMessages.get("error.identifier.method.invocation", name, e));
} catch (InvocationTargetException e) {
throw new ELException(
LocalMessages.get("error.identifier.method.invocation", name, e.getCause())
);
}
}
@Override
public MethodInfo getMethodInfo(ELContext context) {
return new MethodInfo(method.getName(), method.getReturnType(), method.getParameterTypes());
}
};
} else if (value instanceof MethodExpression) {
return (MethodExpression) value;
}
throw new MethodNotFoundException(
LocalMessages.get("error.identifier.method.notamethod", name, value.getClass())
);
}
public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
return getMethodExpression(bindings, context, returnType, paramTypes).getMethodInfo(context);
}
public Object invoke(
Bindings bindings,
ELContext context,
Class<?> returnType,
Class<?>[] paramTypes,
Object[] params
) {
return getMethodExpression(bindings, context, returnType, paramTypes).invoke(context, params);
}
@Override
|
public String toString() {
return name;
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
b.append(bindings != null && bindings.isVariableBound(index) ? "<var>" : name);
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public int getCardinality() {
return 0;
}
public AstNode getChild(int i) {
return null;
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstIdentifier.java
| 1
|
请完成以下Java代码
|
public class WebsocketFilter implements Filter {
private static final String TOKEN_KEY = "Sec-WebSocket-Protocol";
private static CommonAPI commonApi;
private static RedisUtil redisUtil;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (commonApi == null) {
commonApi = SpringContextUtils.getBean(CommonAPI.class);
}
if (redisUtil == null) {
redisUtil = SpringContextUtils.getBean(RedisUtil.class);
}
HttpServletRequest request = (HttpServletRequest)servletRequest;
String token = request.getHeader(TOKEN_KEY);
|
log.debug("Websocket连接 Token安全校验,Path = {},token:{}", request.getRequestURI(), token);
try {
TokenUtils.verifyToken(token, commonApi, redisUtil);
} catch (Exception exception) {
//log.error("Websocket连接 Token安全校验失败,IP:{}, Token:{}, Path = {},异常:{}", oConvertUtils.getIpAddrByRequest(request), token, request.getRequestURI(), exception.getMessage());
log.debug("Websocket连接 Token安全校验失败,IP:{}, Token:{}, Path = {},异常:{}", oConvertUtils.getIpAddrByRequest(request), token, request.getRequestURI(), exception.getMessage());
return;
}
HttpServletResponse response = (HttpServletResponse)servletResponse;
response.setHeader(TOKEN_KEY, token);
filterChain.doFilter(servletRequest, servletResponse);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\filter\WebsocketFilter.java
| 1
|
请完成以下Java代码
|
public ExternalTaskQueryTopicBuilder processDefinitionId(String processDefinitionId) {
currentInstruction.setProcessDefinitionId(processDefinitionId);
return this;
}
public ExternalTaskQueryTopicBuilder processDefinitionIdIn(String... processDefinitionIds) {
currentInstruction.setProcessDefinitionIds(processDefinitionIds);
return this;
}
public ExternalTaskQueryTopicBuilder processDefinitionKey(String processDefinitionKey) {
currentInstruction.setProcessDefinitionKey(processDefinitionKey);
return this;
}
public ExternalTaskQueryTopicBuilder processDefinitionKeyIn(String... processDefinitionKeys) {
currentInstruction.setProcessDefinitionKeys(processDefinitionKeys);
return this;
}
public ExternalTaskQueryTopicBuilder processDefinitionVersionTag(String processDefinitionVersionTag) {
currentInstruction.setProcessDefinitionVersionTag(processDefinitionVersionTag);
return this;
}
public ExternalTaskQueryTopicBuilder withoutTenantId() {
currentInstruction.setTenantIds(null);
return this;
}
public ExternalTaskQueryTopicBuilder tenantIdIn(String... tenantIds) {
currentInstruction.setTenantIds(tenantIds);
return this;
}
protected void submitCurrentInstruction() {
if (currentInstruction != null) {
this.instructions.put(currentInstruction.getTopicName(), currentInstruction);
|
}
}
public ExternalTaskQueryTopicBuilder enableCustomObjectDeserialization() {
currentInstruction.setDeserializeVariables(true);
return this;
}
public ExternalTaskQueryTopicBuilder localVariables() {
currentInstruction.setLocalVariables(true);
return this;
}
public ExternalTaskQueryTopicBuilder includeExtensionProperties() {
currentInstruction.setIncludeExtensionProperties(true);
return this;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\ExternalTaskQueryTopicBuilderImpl.java
| 1
|
请完成以下Java代码
|
public DmnDecisionResultEntries remove(int index) {
throw new UnsupportedOperationException("decision result is immutable");
}
@Override
public int indexOf(Object o) {
return ruleResults.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return ruleResults.lastIndexOf(o);
}
@Override
public ListIterator<DmnDecisionResultEntries> listIterator() {
return asUnmodifiableList().listIterator();
}
@Override
public ListIterator<DmnDecisionResultEntries> listIterator(int index) {
|
return asUnmodifiableList().listIterator(index);
}
@Override
public List<DmnDecisionResultEntries> subList(int fromIndex, int toIndex) {
return asUnmodifiableList().subList(fromIndex, toIndex);
}
@Override
public String toString() {
return ruleResults.toString();
}
protected List<DmnDecisionResultEntries> asUnmodifiableList() {
return Collections.unmodifiableList(ruleResults);
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultImpl.java
| 1
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final int huId = context.getSingleSelectedRecordId();
final I_M_HU hu = handlingUnitsDAO.getById(HuId.ofRepoId(huId));
final QtyTU qtyTU = handlingUnitsBL.getTUsCount(hu);
if (handlingUnitsBL.isAggregateHU(hu) && qtyTU.toInt() > 1)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("HU is aggregated and Qty is bigger then 1. Cannot assign QR code to it.");
}
|
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final HUQRCode huQRCode = HUQRCode.fromGlobalQRCodeJsonString(p_Barcode);
final HuId selectedHuId = HuId.ofRepoId(getRecord_ID());
final boolean ensureSingleAssignment = !qrCodeConfigurationService.isOneQrCodeForAggregatedHUsEnabledFor(handlingUnitsBL.getById(selectedHuId));
huQRCodesService.assign(huQRCode, selectedHuId, ensureSingleAssignment);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Assign_QRCode.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAdminId() {
return adminId;
}
public void setAdminId(Long adminId) {
this.adminId = adminId;
}
public Long getPermissionId() {
return permissionId;
}
public void setPermissionId(Long permissionId) {
this.permissionId = permissionId;
}
public Integer getType() {
return type;
}
|
public void setType(Integer type) {
this.type = type;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", adminId=").append(adminId);
sb.append(", permissionId=").append(permissionId);
sb.append(", type=").append(type);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdminPermissionRelation.java
| 1
|
请完成以下Java代码
|
public void addPair(IWord first, IWord second)
{
String combine = first.getValue() + "@" + second.getValue();
Integer frequency = trie.get(combine);
if (frequency == null) frequency = 0;
trie.put(combine, frequency + 1);
// 同时还要统计标签的转移情况
tmDictionaryMaker.addPair(first.getLabel(), second.getLabel());
}
/**
* 保存NGram词典和转移矩阵
*
* @param path
* @return
*/
public boolean saveTxtTo(String path)
{
saveNGramToTxt(path + ".ngram.txt");
saveTransformMatrixToTxt(path + ".tr.txt");
return true;
}
/**
* 保存NGram词典
*
* @param path
* @return
*/
public boolean saveNGramToTxt(String path)
|
{
try
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8"));
for (Map.Entry<String, Integer> entry : trie.entrySet())
{
bw.write(entry.getKey() + " " + entry.getValue());
bw.newLine();
}
bw.close();
}
catch (Exception e)
{
Predefine.logger.warning("在保存NGram词典到" + path + "时发生异常" + e);
return false;
}
return true;
}
/**
* 保存转移矩阵
*
* @param path
* @return
*/
public boolean saveTransformMatrixToTxt(String path)
{
return tmDictionaryMaker.saveTxtTo(path);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\NGramDictionaryMaker.java
| 1
|
请完成以下Java代码
|
public class ListenerContainerConsumerFailedEvent extends AmqpEvent {
@Serial
private static final long serialVersionUID = -8122166328567190605L;
private final @Nullable String reason;
private final boolean fatal;
private final @Nullable Throwable throwable;
/**
* Construct an instance with the provided arguments.
* @param source the source container.
* @param reason the reason.
* @param throwable the throwable.
* @param fatal true if the startup failure was fatal (will not be retried).
*/
public ListenerContainerConsumerFailedEvent(Object source, @Nullable String reason,
@Nullable Throwable throwable, boolean fatal) {
super(source);
this.reason = reason;
this.fatal = fatal;
this.throwable = throwable;
}
public @Nullable String getReason() {
|
return this.reason;
}
public boolean isFatal() {
return this.fatal;
}
public @Nullable Throwable getThrowable() {
return this.throwable;
}
@Override
public String toString() {
return "ListenerContainerConsumerFailedEvent [reason=" + this.reason + ", fatal=" + this.fatal + ", throwable="
+ this.throwable + ", container=" + this.source + "]";
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\ListenerContainerConsumerFailedEvent.java
| 1
|
请完成以下Java代码
|
public static byte[] readInputStream(InputStream inputStream, String inputStreamName) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[16 * 1024];
try {
int bytesRead = inputStream.read(buffer);
while (bytesRead != -1) {
outputStream.write(buffer, 0, bytesRead);
bytesRead = inputStream.read(buffer);
}
} catch (Exception e) {
throw new FlowableException("couldn't read input stream " + inputStreamName, e);
}
return outputStream.toByteArray();
}
public static String readFileAsString(String filePath) {
byte[] buffer = new byte[(int) getFile(filePath).length()];
BufferedInputStream inputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(getFile(filePath)));
inputStream.read(buffer);
} catch (Exception e) {
throw new FlowableException("Couldn't read file " + filePath + ": " + e.getMessage());
} finally {
IoUtil.closeSilently(inputStream);
}
return new String(buffer);
}
public static File getFile(String filePath) {
URL url = IoUtil.class.getClassLoader().getResource(filePath);
try {
return new File(url.toURI());
} catch (Exception e) {
throw new FlowableException("Couldn't get file " + filePath + ": " + e.getMessage());
}
}
public static void writeStringToFile(String content, String filePath) {
BufferedOutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath)));
|
outputStream.write(content.getBytes());
outputStream.flush();
} catch (Exception e) {
throw new FlowableException("Couldn't write file " + filePath, e);
} finally {
IoUtil.closeSilently(outputStream);
}
}
/**
* Closes the given stream. The same as calling {@link InputStream#close()}, but errors while closing are silently ignored.
*/
public static void closeSilently(InputStream inputStream) {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ignore) {
// Exception is silently ignored
}
}
/**
* Closes the given stream. The same as calling {@link OutputStream#close()} , but errors while closing are silently ignored.
*/
public static void closeSilently(OutputStream outputStream) {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException ignore) {
// Exception is silently ignored
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\util\IoUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DataController {
@Autowired
PersonRepository personRepository;
@RequestMapping("/save")
public Person save(){
Person p = new Person("wyf",32);
Collection<Location> locations = new LinkedHashSet<Location>();
Location loc1 = new Location("上海","2009");
Location loc2 = new Location("合肥","2010");
Location loc3 = new Location("广州","2011");
Location loc4 = new Location("马鞍山","2012");
locations.add(loc1);
locations.add(loc2);
locations.add(loc3);
locations.add(loc4);
|
p.setLocations(locations);
return personRepository.save(p);
}
@RequestMapping("/q1")
public Person q1(String name){
return personRepository.findByName(name);
}
@RequestMapping("/q2")
public List<Person> q2(Integer age){
return personRepository.withQueryFindByAge(age);
}
}
|
repos\spring-boot-student-master\spring-boot-student-data-mongo\src\main\java\com\xiaolyuh\controller\DataController.java
| 2
|
请完成以下Java代码
|
public class CsvTransfer {
private List<String[]> csvStringList;
private List<CsvBean> csvList;
public CsvTransfer() {}
public List<String[]> getCsvStringList() {
if (csvStringList != null) return csvStringList;
return new ArrayList<String[]>();
}
public void addLine(String[] line) {
if (this.csvList == null) this.csvStringList = new ArrayList<>();
|
this.csvStringList.add(line);
}
public void setCsvStringList(List<String[]> csvStringList) {
this.csvStringList = csvStringList;
}
public void setCsvList(List<CsvBean> csvList) {
this.csvList = csvList;
}
public List<CsvBean> getCsvList() {
if (csvList != null) return csvList;
return new ArrayList<CsvBean>();
}
}
|
repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\libraries\opencsv\pojos\CsvTransfer.java
| 1
|
请完成以下Java代码
|
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set 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 Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementMatcher.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8081
spring:
application:
name: feign-service # 服务名
# Zipkin 配置项,对应 ZipkinProperties 类
zipkin:
base-url: http://127.0.0.1:9411 # Zipkin 服务的地址
# Spring Cloud Sleuth 配置项
sleuth:
# Spring Cloud Sleuth 针对 Web 组件的配置项,例如说 SpringMVC
web:
enabled: true #
|
是否开启,默认为 true
# Spring Cloud Sleuth 针对 Feign 组件的配置项,对应 SleuthFeignProperties 类
feign:
enabled: true # 是否开启,默认为 true
|
repos\SpringBoot-Labs-master\labx-13\labx-13-sc-sleuth-feign\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public static String byPaddingZeros(int value, int paddingLength) {
return String.format("%0" + paddingLength + "d", value);
}
public static double withTwoDecimalPlaces(double value) {
DecimalFormat df = new DecimalFormat("#.00");
return Double.valueOf(df.format(value));
}
public static String withLargeIntegers(double value) {
DecimalFormat df = new DecimalFormat("###,###,###");
return df.format(value);
}
public static String forPercentages(double value, Locale localisation) {
NumberFormat nf = NumberFormat.getPercentInstance(localisation);
return nf.format(value);
}
public static String currencyWithChosenLocalisation(double value, Locale localisation) {
NumberFormat nf = NumberFormat.getCurrencyInstance(localisation);
return nf.format(value);
}
|
public static String currencyWithDefaultLocalisation(double value) {
NumberFormat nf = NumberFormat.getCurrencyInstance();
return nf.format(value);
}
public static String formatScientificNotation(double value, Locale localisation) {
return String.format(localisation, "%.3E", value);
}
public static String formatScientificNotationWithMinChars(double value, Locale localisation) {
return String.format(localisation, "%12.4E", value);
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers\src\main\java\com\baeldung\formatNumber\FormatNumber.java
| 1
|
请完成以下Java代码
|
public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
this.allowUrlEncodedSlash = allowUrlEncodedSlash;
}
private boolean containsInvalidUrlEncodedSlash(String uri) {
if (this.allowUrlEncodedSlash || uri == null) {
return false;
}
return uri.contains("%2f") || uri.contains("%2F");
}
/**
* Checks whether a path is normalized (doesn't contain path traversal sequences like
* "./", "/../" or "/.")
* @param path the path to test
* @return true if the path doesn't contain any path-traversal character sequences.
*/
private boolean isNormalized(String path) {
if (path == null) {
return true;
}
for (int i = path.length(); i > 0;) {
|
int slashIndex = path.lastIndexOf('/', i - 1);
int gap = i - slashIndex;
if (gap == 2 && path.charAt(slashIndex + 1) == '.') {
// ".", "/./" or "/."
return false;
}
if (gap == 3 && path.charAt(slashIndex + 1) == '.' && path.charAt(slashIndex + 2) == '.') {
return false;
}
i = slashIndex;
}
return true;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\DefaultHttpFirewall.java
| 1
|
请完成以下Java代码
|
public void setCode(Integer code) {
this.code = code;
}
public ModelApiResponse type(String type) {
this.type = type;
return this;
}
/**
* Get type
* @return type
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_TYPE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ModelApiResponse message(String message) {
this.message = message;
return this;
}
/**
* Get message
* @return message
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_MESSAGE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
|
ModelApiResponse _apiResponse = (ModelApiResponse) o;
return Objects.equals(this.code, _apiResponse.code) &&
Objects.equals(this.type, _apiResponse.type) &&
Objects.equals(this.message, _apiResponse.message);
}
@Override
public int hashCode() {
return Objects.hash(code, type, message);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ModelApiResponse {\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\ModelApiResponse.java
| 1
|
请完成以下Java代码
|
public int getSupervisor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set UserDiscount.
@param UserDiscount UserDiscount */
@Override
public void setUserDiscount (java.math.BigDecimal UserDiscount)
{
set_Value (COLUMNNAME_UserDiscount, UserDiscount);
}
/** Get UserDiscount.
@return UserDiscount */
@Override
public java.math.BigDecimal getUserDiscount ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_UserDiscount);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/**
* UserLevel AD_Reference_ID=226
* Reference name: AD_Role User Level
*/
public static final int USERLEVEL_AD_Reference_ID=226;
/** System = S__ */
public static final String USERLEVEL_System = "S__";
/** Client = _C_ */
public static final String USERLEVEL_Client = "_C_";
/** Organization = __O */
public static final String USERLEVEL_Organization = "__O";
/** Client+Organization = _CO */
public static final String USERLEVEL_ClientPlusOrganization = "_CO";
/** Set Nutzer-Ebene.
@param UserLevel
System Client Organization
*/
@Override
public void setUserLevel (java.lang.String UserLevel)
{
set_Value (COLUMNNAME_UserLevel, UserLevel);
}
/** Get Nutzer-Ebene.
@return System Client Organization
*/
@Override
|
public java.lang.String getUserLevel ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserLevel);
}
/** Set Is webui role.
@param WEBUI_Role Is webui role */
@Override
public void setWEBUI_Role (boolean WEBUI_Role)
{
set_Value (COLUMNNAME_WEBUI_Role, Boolean.valueOf(WEBUI_Role));
}
/** Get Is webui role.
@return Is webui role */
@Override
public boolean isWEBUI_Role ()
{
Object oo = get_Value(COLUMNNAME_WEBUI_Role);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsAllowPasswordChangeForOthers (final boolean IsAllowPasswordChangeForOthers)
{
set_Value (COLUMNNAME_IsAllowPasswordChangeForOthers, IsAllowPasswordChangeForOthers);
}
@Override
public boolean isAllowPasswordChangeForOthers()
{
return get_ValueAsBoolean(COLUMNNAME_IsAllowPasswordChangeForOthers);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role.java
| 1
|
请完成以下Java代码
|
public int getM_Picking_Job_Line_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Line_ID);
}
@Override
public void setM_Picking_Job_Schedule_ID (final int M_Picking_Job_Schedule_ID)
{
if (M_Picking_Job_Schedule_ID < 1)
set_Value (COLUMNNAME_M_Picking_Job_Schedule_ID, null);
else
set_Value (COLUMNNAME_M_Picking_Job_Schedule_ID, M_Picking_Job_Schedule_ID);
}
@Override
public int getM_Picking_Job_Schedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Schedule_ID);
}
@Override
public void setM_PickingSlot_ID (final int M_PickingSlot_ID)
{
if (M_PickingSlot_ID < 1)
set_Value (COLUMNNAME_M_PickingSlot_ID, null);
else
set_Value (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID);
}
@Override
public int getM_PickingSlot_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID);
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
@Override
public void setPP_Order_ID (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_Value (COLUMNNAME_PP_Order_ID, null);
else
|
set_Value (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyToPick (final BigDecimal QtyToPick)
{
set_Value (COLUMNNAME_QtyToPick, QtyToPick);
}
@Override
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick);
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_Picking_Job_Line.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class S3CrudService {
private final S3Client s3Client;
public S3CrudService(S3Client s3Client) {
this.s3Client = s3Client;
}
public void createBucket(String bucketName) {
CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
.bucket(bucketName)
.build();
s3Client.createBucket(bucketRequest);
}
public void createObject(String bucketName, File inMemoryObject) {
PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucketName)
.key(inMemoryObject.getName())
.build();
s3Client.putObject(request, RequestBody.fromByteBuffer(inMemoryObject.getContent()));
}
public Optional<byte[]> getObject(String bucketName, String objectKey) {
try {
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
ResponseBytes<GetObjectResponse> responseResponseBytes = s3Client.getObjectAsBytes(getObjectRequest);
return Optional.of(responseResponseBytes.asByteArray());
} catch (S3Exception e) {
return Optional.empty();
|
}
}
public boolean deleteObject(String bucketName, String objectKey) {
try {
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
s3Client.deleteObject(deleteObjectRequest);
return true;
} catch (S3Exception e) {
return false;
}
}
}
|
repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\S3CrudService.java
| 2
|
请完成以下Java代码
|
public void setF_COMDEPTID(String f_COMDEPTID) {
F_COMDEPTID = f_COMDEPTID;
}
public String getF_CONTACTMAN() {
return F_CONTACTMAN;
}
public void setF_CONTACTMAN(String f_CONTACTMAN) {
F_CONTACTMAN = f_CONTACTMAN;
}
public String getF_TEL() {
return F_TEL;
}
public void setF_TEL(String f_TEL) {
F_TEL = f_TEL;
}
public String getF_MOBIL() {
return F_MOBIL;
}
public void setF_MOBIL(String f_MOBIL) {
F_MOBIL = f_MOBIL;
}
public String getF_EMAIL() {
return F_EMAIL;
}
public void setF_EMAIL(String f_EMAIL) {
F_EMAIL = f_EMAIL;
}
public String getF_BGOFFICEID() {
return F_BGOFFICEID;
}
public void setF_BGOFFICEID(String f_BGOFFICEID) {
F_BGOFFICEID = f_BGOFFICEID;
}
public String getF_INFOMOBIL() {
return F_INFOMOBIL;
}
public void setF_INFOMOBIL(String f_INFOMOBIL) {
F_INFOMOBIL = f_INFOMOBIL;
}
public String getF_INFOMAN() {
return F_INFOMAN;
}
public void setF_INFOMAN(String f_INFOMAN) {
F_INFOMAN = f_INFOMAN;
}
public String getF_LOGPASS() {
return F_LOGPASS;
}
public void setF_LOGPASS(String f_LOGPASS) {
F_LOGPASS = f_LOGPASS;
}
public String getF_STARTDATE() {
return F_STARTDATE;
}
public void setF_STARTDATE(String f_STARTDATE) {
F_STARTDATE = f_STARTDATE;
}
|
public String getF_STOPDATE() {
return F_STOPDATE;
}
public void setF_STOPDATE(String f_STOPDATE) {
F_STOPDATE = f_STOPDATE;
}
public String getF_STATUS() {
return F_STATUS;
}
public void setF_STATUS(String f_STATUS) {
F_STATUS = f_STATUS;
}
public String getF_MEMO() {
return F_MEMO;
}
public void setF_MEMO(String f_MEMO) {
F_MEMO = f_MEMO;
}
public String getF_AUDITER() {
return F_AUDITER;
}
public void setF_AUDITER(String f_AUDITER) {
F_AUDITER = f_AUDITER;
}
public String getF_AUDITTIME() {
return F_AUDITTIME;
}
public void setF_AUDITTIME(String f_AUDITTIME) {
F_AUDITTIME = f_AUDITTIME;
}
public String getF_ISAUDIT() {
return F_ISAUDIT;
}
public void setF_ISAUDIT(String f_ISAUDIT) {
F_ISAUDIT = f_ISAUDIT;
}
public Timestamp getF_EDITTIME() {
return F_EDITTIME;
}
public void setF_EDITTIME(Timestamp f_EDITTIME) {
F_EDITTIME = f_EDITTIME;
}
public Integer getF_PLATFORM_ID() {
return F_PLATFORM_ID;
}
public void setF_PLATFORM_ID(Integer f_PLATFORM_ID) {
F_PLATFORM_ID = f_PLATFORM_ID;
}
public String getF_ISPRINTBILL() {
return F_ISPRINTBILL;
}
public void setF_ISPRINTBILL(String f_ISPRINTBILL) {
F_ISPRINTBILL = f_ISPRINTBILL;
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscExeOffice.java
| 1
|
请完成以下Java代码
|
public boolean isFailIfNothingLocked()
{
return failIfNothingLocked;
}
@Override
public ILockCommand retryOnFailure(final int retryOnFailure)
{
this.retryOnFailure = Math.max(retryOnFailure, 0);
return this;
}
@Override
public int getRetryOnFailure() {return retryOnFailure;}
@Override
public ILockCommand setRecordByModel(final Object model)
{
_recordsToLock.setRecordByModel(model);
return this;
}
@Override
public ILockCommand setRecordByTableRecordId(final int tableId, final int recordId)
{
_recordsToLock.setRecordByTableRecordId(tableId, recordId);
return this;
}
@Override
public ILockCommand setRecordsBySelection(final Class<?> modelClass, final PInstanceId pinstanceId)
{
_recordsToLock.setRecordsBySelection(modelClass, pinstanceId);
return this;
}
@Override
public <T> ILockCommand setRecordsByFilter(final Class<T> clazz, final IQueryFilter<T> filters)
{
_recordsToLock.setRecordsByFilter(clazz, filters);
return this;
}
@Override
public <T> ILockCommand addRecordsByFilter(final Class<T> clazz, final IQueryFilter<T> filters)
{
_recordsToLock.addRecordsByFilter(clazz, filters);
return this;
}
@Override
public List<LockRecordsByFilter> getSelectionToLock_Filters()
{
return _recordsToLock.getSelection_Filters();
}
|
@Override
public final AdTableId getSelectionToLock_AD_Table_ID()
{
return _recordsToLock.getSelection_AD_Table_ID();
}
@Override
public final PInstanceId getSelectionToLock_AD_PInstance_ID()
{
return _recordsToLock.getSelection_PInstanceId();
}
@Override
public final Iterator<TableRecordReference> getRecordsToLockIterator()
{
return _recordsToLock.getRecordsIterator();
}
@Override
public LockCommand addRecordByModel(final Object model)
{
_recordsToLock.addRecordByModel(model);
return this;
}
@Override
public LockCommand addRecordsByModel(final Collection<?> models)
{
_recordsToLock.addRecordByModels(models);
return this;
}
@Override
public ILockCommand addRecord(@NonNull final TableRecordReference record)
{
_recordsToLock.addRecords(ImmutableSet.of(record));
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockCommand.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Map<String, Link> getAccessibleLinks(@Nullable AccessLevel accessLevel, Map<String, Link> links) {
if (accessLevel == null) {
return new LinkedHashMap<>();
}
return links.entrySet()
.stream()
.filter((entry) -> entry.getKey().equals("self") || accessLevel.isAccessAllowed(entry.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
@Override
public String toString() {
return "Actuator root web endpoint";
}
}
/**
* {@link ReactiveWebOperation} wrapper to add security.
*/
private static class SecureReactiveWebOperation implements ReactiveWebOperation {
private final ReactiveWebOperation delegate;
private final SecurityInterceptor securityInterceptor;
private final EndpointId endpointId;
SecureReactiveWebOperation(ReactiveWebOperation delegate, SecurityInterceptor securityInterceptor,
EndpointId endpointId) {
this.delegate = delegate;
this.securityInterceptor = securityInterceptor;
this.endpointId = endpointId;
}
@Override
public Mono<ResponseEntity<Object>> handle(ServerWebExchange exchange, @Nullable Map<String, String> body) {
return this.securityInterceptor.preHandle(exchange, this.endpointId.toLowerCaseString())
.flatMap((securityResponse) -> flatMapResponse(exchange, body, securityResponse));
}
private Mono<ResponseEntity<Object>> flatMapResponse(ServerWebExchange exchange,
@Nullable Map<String, String> body, SecurityResponse securityResponse) {
if (!securityResponse.getStatus().equals(HttpStatus.OK)) {
return Mono.just(new ResponseEntity<>(securityResponse.getStatus()));
|
}
return this.delegate.handle(exchange, body);
}
}
static class CloudFoundryWebFluxEndpointHandlerMappingRuntimeHints implements RuntimeHintsRegistrar {
private final ReflectiveRuntimeHintsRegistrar reflectiveRegistrar = new ReflectiveRuntimeHintsRegistrar();
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.reflectiveRegistrar.registerRuntimeHints(hints, CloudFoundryLinksHandler.class);
this.bindingRegistrar.registerReflectionHints(hints.reflection(), Link.class);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\reactive\CloudFoundryWebFluxEndpointHandlerMapping.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String fromScratchContractExample() {
String contractAddress = "";
try {
//Create a wallet
WalletUtils.generateNewWalletFile("PASSWORD", new File("/path/to/destination"), true);
//Load the credentials from it
Credentials credentials = WalletUtils.loadCredentials("PASSWORD", "/path/to/walletfile");
//Deploy contract to address specified by wallet
Example contract = Example.deploy(this.web3j,
credentials,
ManagedTransaction.GAS_PRICE,
Contract.GAS_LIMIT).send();
//Het the address
contractAddress = contract.getContractAddress();
} catch (Exception ex) {
System.out.println(PLEASE_SUPPLY_REAL_DATA);
return PLEASE_SUPPLY_REAL_DATA;
}
return contractAddress;
}
@Async
public String sendTx() {
String transactionHash = "";
try {
List inputParams = new ArrayList();
List outputParams = new ArrayList();
Function function = new Function("fuctionName", inputParams, outputParams);
String encodedFunction = FunctionEncoder.encode(function);
|
BigInteger nonce = BigInteger.valueOf(100);
BigInteger gasprice = BigInteger.valueOf(100);
BigInteger gaslimit = BigInteger.valueOf(100);
Transaction transaction = Transaction.createFunctionCallTransaction("FROM_ADDRESS", nonce, gasprice, gaslimit, "TO_ADDRESS", encodedFunction);
org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse = web3j.ethSendTransaction(transaction).sendAsync().get();
transactionHash = transactionResponse.getTransactionHash();
} catch (Exception ex) {
System.out.println(PLEASE_SUPPLY_REAL_DATA);
return PLEASE_SUPPLY_REAL_DATA;
}
return transactionHash;
}
}
|
repos\tutorials-master\ethereum\src\main\java\com\baeldung\web3j\services\Web3Service.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.