instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public static String removeLeadingZeroesWithSubstring(String s) {
int index = 0;
for (; index < s.length() - 1; index++) {
if (s.charAt(index) != '0') {
break;
}
}
return s.substring(index);
}
public static String removeTrailingZeroesWithSubstring(String s) {
int index = s.length() - 1;
for (; index > 0; index--) {
if (s.charAt(index) != '0') {
break;
}
}
return s.substring(0, index + 1);
}
public static String removeLeadingZeroesWithApacheCommonsStripStart(String s) {
String stripped = StringUtils.stripStart(s, "0");
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeTrailingZeroesWithApacheCommonsStripEnd(String s) {
String stripped = StringUtils.stripEnd(s, "0");
if (stripped.isEmpty() && !s.isEmpty()) {
|
return "0";
}
return stripped;
}
public static String removeLeadingZeroesWithGuavaTrimLeadingFrom(String s) {
String stripped = CharMatcher.is('0')
.trimLeadingFrom(s);
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeTrailingZeroesWithGuavaTrimTrailingFrom(String s) {
String stripped = CharMatcher.is('0')
.trimTrailingFrom(s);
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeLeadingZeroesWithRegex(String s) {
return s.replaceAll("^0+(?!$)", "");
}
public static String removeTrailingZeroesWithRegex(String s) {
return s.replaceAll("(?!^)0+$", "");
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-algorithms-2\src\main\java\com\baeldung\removeleadingtrailingchar\RemoveLeadingAndTrailingZeroes.java
| 1
|
请完成以下Java代码
|
public void setRequestUrl (java.lang.String RequestUrl)
{
set_ValueNoCheck (COLUMNNAME_RequestUrl, RequestUrl);
}
/** Get Abfrage.
@return Abfrage */
@Override
public java.lang.String getRequestUrl ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestUrl);
}
/** Set Antwort .
@param ResponseCode Antwort */
@Override
public void setResponseCode (int ResponseCode)
{
set_Value (COLUMNNAME_ResponseCode, Integer.valueOf(ResponseCode));
}
/** Get Antwort .
@return Antwort */
@Override
public int getResponseCode ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ResponseCode);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Antwort-Text.
@param ResponseText
Anfrage-Antworttext
*/
@Override
public void setResponseText (java.lang.String ResponseText)
{
set_Value (COLUMNNAME_ResponseText, ResponseText);
}
/** Get Antwort-Text.
@return Anfrage-Antworttext
*/
@Override
public java.lang.String getResponseText ()
{
return (java.lang.String)get_Value(COLUMNNAME_ResponseText);
}
|
/** Set TransaktionsID Client.
@param TransactionIDClient TransaktionsID Client */
@Override
public void setTransactionIDClient (java.lang.String TransactionIDClient)
{
set_ValueNoCheck (COLUMNNAME_TransactionIDClient, TransactionIDClient);
}
/** Get TransaktionsID Client.
@return TransaktionsID Client */
@Override
public java.lang.String getTransactionIDClient ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionIDClient);
}
/** Set TransaktionsID Server.
@param TransactionIDServer TransaktionsID Server */
@Override
public void setTransactionIDServer (java.lang.String TransactionIDServer)
{
set_ValueNoCheck (COLUMNNAME_TransactionIDServer, TransactionIDServer);
}
/** Get TransaktionsID Server.
@return TransaktionsID Server */
@Override
public java.lang.String getTransactionIDServer ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionIDServer);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Log.java
| 1
|
请完成以下Java代码
|
public int compare(final IProductionMaterial pm1, final IProductionMaterial pm2)
{
if (pm1 == pm2)
{
return 0;
}
if (pm1 == null)
{
return -1;
}
if (pm2 == null)
{
return +1;
}
//
// Compare Types
{
final ProductionMaterialType type1 = pm1.getType();
final ProductionMaterialType type2 = pm2.getType();
final int cmp = type1.compareTo(type2);
if (cmp != 0)
{
return cmp;
}
}
//
// Compare Product
{
final int productId1 = pm1.getM_Product().getM_Product_ID();
final int productId2 = pm2.getM_Product().getM_Product_ID();
if (productId1 != productId2)
{
return productId1 - productId2;
}
}
//
// Compare Qty
{
final BigDecimal qty1 = pm1.getQty();
final BigDecimal qty2 = pm2.getQty();
final int cmp = qty1.compareTo(qty2);
if (cmp != 0)
{
return cmp;
|
}
}
//
// Compare UOM
{
final int uomId1 = pm1.getC_UOM().getC_UOM_ID();
final int uomId2 = pm2.getC_UOM().getC_UOM_ID();
if (uomId1 != uomId2)
{
return uomId1 - uomId2;
}
}
//
// Compare QM_QtyDeliveredPercOfRaw
{
final BigDecimal qty1 = pm1.getQM_QtyDeliveredPercOfRaw();
final BigDecimal qty2 = pm2.getQM_QtyDeliveredPercOfRaw();
final int cmp = qty1.compareTo(qty2);
if (cmp != 0)
{
return cmp;
}
}
//
// Compare QM_QtyDeliveredPercOfRaw
{
final BigDecimal qty1 = pm1.getQM_QtyDeliveredAvg();
final BigDecimal qty2 = pm2.getQM_QtyDeliveredAvg();
final int cmp = qty1.compareTo(qty2);
if (cmp != 0)
{
return cmp;
}
}
//
// If we reach this point, they are equal
return 0;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ProductionMaterialComparator.java
| 1
|
请完成以下Java代码
|
private ITranslatableString getAttributeDisplayValue(@NonNull final Attribute attribute)
{
final AttributeCode attributeCode = attribute.getAttributeCode();
final AttributeValueType attributeValueType = attribute.getValueType();
if (AttributeValueType.STRING.equals(attributeValueType))
{
final String valueStr = attributeSet.getValueAsString(attributeCode);
return ASIDescriptionBuilderCommand.formatStringValue(valueStr);
}
else if (AttributeValueType.NUMBER.equals(attributeValueType))
{
final BigDecimal valueBD = attributeSet.getValueAsBigDecimal(attributeCode);
if (valueBD != null)
{
return ASIDescriptionBuilderCommand.formatNumber(valueBD, attribute.getNumberDisplayType());
}
else
{
return null;
}
}
else if (AttributeValueType.DATE.equals(attributeValueType))
{
final LocalDate valueDate = attributeSet.getValueAsLocalDate(attributeCode);
return valueDate != null
? ASIDescriptionBuilderCommand.formatDateValue(valueDate)
: null;
}
else if (AttributeValueType.LIST.equals(attributeValueType))
{
final AttributeValueId attributeValueId = attributeSet.getAttributeValueIdOrNull(attributeCode);
final AttributeListValue attributeValue = attributeValueId != null
? attributesRepo.retrieveAttributeValueOrNull(attribute, attributeValueId)
: null;
if (attributeValue != null)
{
|
return attributeValue.getNameTrl();
}
else
{
final String valueStr = attributeSet.getValueAsString(attributeCode);
return ASIDescriptionBuilderCommand.formatStringValue(valueStr);
}
}
else
{
// Unknown attributeValueType
final String valueStr = attributeSet.getValueAsString(attributeCode);
return ASIDescriptionBuilderCommand.formatStringValue(valueStr);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeSetDescriptionBuilderCommand.java
| 1
|
请完成以下Java代码
|
public String encodingType() {
return "gzip";
}
@Override
public byte[] decode(byte[] encoded) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
GZIPInputStream gis = new GZIPInputStream(bis);
return FileCopyUtils.copyToByteArray(gis);
}
catch (IOException e) {
throw new IllegalStateException("couldn't decode body from gzip", e);
}
}
|
@Override
public byte[] encode(DataBuffer original) {
try {
ByteArrayOutputStream bis = new ByteArrayOutputStream();
GZIPOutputStream gos = new GZIPOutputStream(bis);
FileCopyUtils.copy(original.asInputStream(), gos);
return bis.toByteArray();
}
catch (IOException e) {
throw new IllegalStateException("couldn't encode body to gzip", e);
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\rewrite\GzipMessageBodyResolver.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Key {
/**
* The password used to access the key in the key store.
*/
private @Nullable String password;
/**
* The alias that identifies the key in the key store.
*/
private @Nullable String alias;
public @Nullable String getPassword() {
return this.password;
}
|
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getAlias() {
return this.alias;
}
public void setAlias(@Nullable String alias) {
this.alias = alias;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\SslBundleProperties.java
| 2
|
请完成以下Java代码
|
public BigDecimal getRate() {
return rate;
}
/**
* Sets the value of the rate property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setRate(BigDecimal value) {
this.rate = value;
}
/**
* Gets the value of the br property.
*
* @return
* possible object is
* {@link ChargeBearerType1Code }
*
*/
public ChargeBearerType1Code getBr() {
return br;
}
/**
* Sets the value of the br property.
*
* @param value
* allowed object is
* {@link ChargeBearerType1Code }
*
*/
public void setBr(ChargeBearerType1Code value) {
this.br = value;
}
/**
* Gets the value of the pty property.
*
* @return
* possible object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public BranchAndFinancialInstitutionIdentification4 getPty() {
return pty;
}
/**
|
* Sets the value of the pty property.
*
* @param value
* allowed object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public void setPty(BranchAndFinancialInstitutionIdentification4 value) {
this.pty = value;
}
/**
* Gets the value of the tax property.
*
* @return
* possible object is
* {@link TaxCharges2 }
*
*/
public TaxCharges2 getTax() {
return tax;
}
/**
* Sets the value of the tax property.
*
* @param value
* allowed object is
* {@link TaxCharges2 }
*
*/
public void setTax(TaxCharges2 value) {
this.tax = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ChargesInformation6.java
| 1
|
请完成以下Java代码
|
public class IgniteStream {
private static final Gson GSON = new Gson();
public static void main(String[] args) throws Exception {
Ignition.setClientMode(true);
Ignite ignite = Ignition.start();
IgniteCache<Integer, Employee> cache = ignite.getOrCreateCache(CacheConfig.employeeCache());
IgniteDataStreamer<Integer, Employee> streamer = ignite.dataStreamer(cache.getName());
streamer.allowOverwrite(true);
streamer.receiver(StreamTransformer.from((e, arg) -> {
Employee employee = e.getValue();
employee.setEmployed(true);
|
e.setValue(employee);
return employee;
}));
Path path = Paths.get(IgniteStream.class.getResource("employees.txt").toURI());
Files.lines(path)
.forEach(line -> {
Employee employee = GSON.fromJson(line, Employee.class);
streamer.addData(employee.getId(), employee);
});
}
}
|
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\ignite\stream\IgniteStream.java
| 1
|
请完成以下Java代码
|
public Stream<E> stream()
{
return IteratorUtils.stream(this);
}
@lombok.Value
public static final class Page<E>
{
public static <E> Page<E> ofRows(final List<E> rows)
{
final Integer lastRow = null;
return new Page<>(rows, lastRow);
}
public static <E> Page<E> ofRowsOrNull(final List<E> rows)
{
return rows != null && !rows.isEmpty()
? ofRows(rows)
: null;
}
public static <E> Page<E> ofRowsAndLastRowIndex(final List<E> rows, final int lastRowZeroBased)
{
return new Page<>(rows, lastRowZeroBased);
}
private final List<E> rows;
private final Integer lastRowZeroBased;
private Page(final List<E> rows, final Integer lastRowZeroBased)
{
Check.assumeNotEmpty(rows, "rows is not empty");
Check.assume(lastRowZeroBased == null || lastRowZeroBased >= 0, "lastRow shall be null, positive or zero");
|
this.rows = rows;
this.lastRowZeroBased = lastRowZeroBased;
}
}
/** Loads and provides the requested page */
@FunctionalInterface
public interface PageFetcher<E>
{
/**
* @param firstRow (first page is ZERO)
* @param pageSize max rows to return
* @return page or null in case there is no page
*/
Page<E> getPage(int firstRow, int pageSize);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\PagedIterator.java
| 1
|
请完成以下Java代码
|
private void scheduleTickMsg(TbContext ctx, EntityId deduplicationId, DeduplicationData data) {
if (!data.isTickScheduled()) {
scheduleTickMsg(ctx, deduplicationId);
data.setTickScheduled(true);
}
}
private Optional<TbPair<Long, Long>> findValidPack(List<TbMsg> msgs, long deduplicationTimeoutMs) {
Optional<TbMsg> min = msgs.stream().min(Comparator.comparing(TbMsg::getMetaDataTs));
return min.map(minTsMsg -> {
long packStartTs = minTsMsg.getMetaDataTs();
long packEndTs = packStartTs + deduplicationInterval;
if (packEndTs <= deduplicationTimeoutMs) {
return new TbPair<>(packStartTs, packEndTs);
}
return null;
});
}
private void enqueueForTellNextWithRetry(TbContext ctx, TbMsg msg, int retryAttempt) {
if (retryAttempt <= config.getMaxRetries()) {
ctx.enqueueForTellNext(msg, TbNodeConnectionType.SUCCESS,
() -> log.trace("[{}][{}][{}] Successfully enqueue deduplication result message!", ctx.getSelfId(), msg.getOriginator(), retryAttempt),
throwable -> {
log.trace("[{}][{}][{}] Failed to enqueue deduplication output message due to: ", ctx.getSelfId(), msg.getOriginator(), retryAttempt, throwable);
if (retryAttempt < config.getMaxRetries()) {
ctx.schedule(() -> enqueueForTellNextWithRetry(ctx, msg, retryAttempt + 1), TB_MSG_DEDUPLICATION_RETRY_DELAY, TimeUnit.SECONDS);
} else {
log.trace("[{}][{}] Max retries [{}] exhausted. Dropping deduplication result message [{}]",
ctx.getSelfId(), msg.getOriginator(), config.getMaxRetries(), msg.getId());
|
}
});
}
}
private void scheduleTickMsg(TbContext ctx, EntityId deduplicationId) {
ctx.tellSelf(ctx.newMsg(null, TbMsgType.DEDUPLICATION_TIMEOUT_SELF_MSG, deduplicationId, TbMsgMetaData.EMPTY, TbMsg.EMPTY_STRING), deduplicationInterval + 1);
}
private String getMergedData(List<TbMsg> msgs) {
ArrayNode mergedData = JacksonUtil.newArrayNode();
msgs.forEach(msg -> {
ObjectNode msgNode = JacksonUtil.newObjectNode();
msgNode.set("msg", JacksonUtil.toJsonNode(msg.getData()));
msgNode.set("metadata", JacksonUtil.valueToTree(msg.getMetaData().getData()));
mergedData.add(msgNode);
});
return JacksonUtil.toString(mergedData);
}
private TbMsgMetaData getMetadata() {
TbMsgMetaData metaData = new TbMsgMetaData();
metaData.putValue("ts", String.valueOf(System.currentTimeMillis()));
return metaData;
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\deduplication\TbMsgDeduplicationNode.java
| 1
|
请完成以下Java代码
|
public OrderLineBuilder externalId(@Nullable final ExternalId externalId)
{
assertNotBuilt();
this.externalId = externalId;
return this;
}
public OrderLineBuilder manualPrice(@Nullable final BigDecimal manualPrice)
{
assertNotBuilt();
this.manualPrice = manualPrice;
return this;
}
public OrderLineBuilder manualPrice(@Nullable final Money manualPrice)
{
return manualPrice(manualPrice != null ? manualPrice.toBigDecimal() : null);
}
public OrderLineBuilder manualDiscount(final BigDecimal manualDiscount)
{
assertNotBuilt();
this.manualDiscount = manualDiscount;
return this;
}
public OrderLineBuilder setDimension(final Dimension dimension)
{
assertNotBuilt();
this.dimension = dimension;
return this;
}
public boolean isProductAndUomMatching(@Nullable final ProductId productId, @Nullable final UomId uomId)
{
return ProductId.equals(getProductId(), productId)
&& UomId.equals(getUomId(), uomId);
}
public OrderLineBuilder description(@Nullable final String description)
{
this.description = description;
|
return this;
}
public OrderLineBuilder hideWhenPrinting(final boolean hideWhenPrinting)
{
this.hideWhenPrinting = hideWhenPrinting;
return this;
}
public OrderLineBuilder details(@NonNull final Collection<OrderLineDetailCreateRequest> details)
{
assertNotBuilt();
detailCreateRequests.addAll(details);
return this;
}
public OrderLineBuilder detail(@NonNull final OrderLineDetailCreateRequest detail)
{
assertNotBuilt();
detailCreateRequests.add(detail);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLineBuilder.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public List<String> getIds() {
return ids;
}
public String getIdIgnoreCase() {
return idIgnoreCase;
}
public String getFirstName() {
return firstName;
}
public String getFirstNameLike() {
return firstNameLike;
}
public String getFirstNameLikeIgnoreCase() {
return firstNameLikeIgnoreCase;
}
public String getLastName() {
return lastName;
}
public String getLastNameLike() {
return lastNameLike;
}
public String getLastNameLikeIgnoreCase() {
return lastNameLikeIgnoreCase;
}
public String getEmail() {
return email;
}
public String getEmailLike() {
return emailLike;
}
public String getGroupId() {
return groupId;
}
|
public List<String> getGroupIds() {
return groupIds;
}
public String getFullNameLike() {
return fullNameLike;
}
public String getFullNameLikeIgnoreCase() {
return fullNameLikeIgnoreCase;
}
public String getDisplayName() {
return displayName;
}
public String getDisplayNameLike() {
return displayNameLike;
}
public String getDisplayNameLikeIgnoreCase() {
return displayNameLikeIgnoreCase;
}
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\UserQueryImpl.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ComplexClass))
return false;
ComplexClass other = (ComplexClass) obj;
if (genericList == null) {
if (other.genericList != null)
return false;
} else if (!genericList.equals(other.genericList))
return false;
if (integerSet == null) {
if (other.integerSet != null)
return false;
} else if (!integerSet.equals(other.integerSet))
return false;
return true;
}
|
protected List<?> getGenericList() {
return genericList;
}
protected void setGenericArrayList(List<?> genericList) {
this.genericList = genericList;
}
protected Set<Integer> getIntegerSet() {
return integerSet;
}
protected void setIntegerSet(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-8\src\main\java\com\baeldung\equalshashcode\entities\ComplexClass.java
| 1
|
请完成以下Java代码
|
private final I_AD_Client retriveAD_Client(final Properties ctx)
{
final List<I_AD_Client> clients = Services.get(IClientDAO.class).retrieveAllClients(ctx);
for (final I_AD_Client client : clients)
{
if (client.getAD_Client_ID() > 0)
{
return client;
}
}
return null;
}
private BufferedImage loadProductLogoImage()
{
final Image logo = Adempiere.getProductLogoLarge();
if (logo == null)
{
return null;
}
return toBufferedImage(logo);
}
/**
* Converts a given Image into a BufferedImage
*
* @param image The Image to be converted
* @return The converted BufferedImage
*/
public static BufferedImage toBufferedImage(final Image image)
{
if (image instanceof BufferedImage)
{
return (BufferedImage)image;
}
// Create a buffered image with transparency
final BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
final Graphics2D bGr = bufferedImage.createGraphics();
bGr.drawImage(image, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bufferedImage;
}
private static byte[] toPngData(final BufferedImage image, final int width)
{
if (image == null)
{
return null;
}
BufferedImage imageScaled;
final int widthOrig = image.getWidth();
final int heightOrig = image.getHeight();
if (width > 0 && widthOrig > 0)
{
|
final double scale = (double)width / (double)widthOrig;
final int height = (int)(heightOrig * scale);
imageScaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
final AffineTransform at = new AffineTransform();
at.scale(scale, scale);
final AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
imageScaled = scaleOp.filter(image, imageScaled);
}
else
{
imageScaled = image;
}
final ByteArrayOutputStream pngBuf = new ByteArrayOutputStream();
try
{
ImageIO.write(imageScaled, "png", pngBuf);
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
return pngBuf.toByteArray();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\servlet\ImagesServlet.java
| 1
|
请完成以下Java代码
|
public String getNameLike() {
return nameLike;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public Integer getVersion() {
return version;
}
public boolean isLatest() {
return latest;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public String getIncidentId() {
return incidentId;
}
public String getIncidentType() {
return incidentType;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getIncidentMessageLike() {
return incidentMessageLike;
}
|
public String getVersionTag() {
return versionTag;
}
public boolean isStartableInTasklist() {
return isStartableInTasklist;
}
public boolean isNotStartableInTasklist() {
return isNotStartableInTasklist;
}
public boolean isStartablePermissionCheck() {
return startablePermissionCheck;
}
public void setProcessDefinitionCreatePermissionChecks(List<PermissionCheck> processDefinitionCreatePermissionChecks) {
this.processDefinitionCreatePermissionChecks = processDefinitionCreatePermissionChecks;
}
public List<PermissionCheck> getProcessDefinitionCreatePermissionChecks() {
return processDefinitionCreatePermissionChecks;
}
public boolean isShouldJoinDeploymentTable() {
return shouldJoinDeploymentTable;
}
public void addProcessDefinitionCreatePermissionCheck(CompositePermissionCheck processDefinitionCreatePermissionCheck) {
processDefinitionCreatePermissionChecks.addAll(processDefinitionCreatePermissionCheck.getAllPermissionChecks());
}
public List<String> getCandidateGroups() {
if (cachedCandidateGroups != null) {
return cachedCandidateGroups;
}
if(authorizationUserId != null) {
List<Group> groups = Context.getCommandContext()
.getReadOnlyIdentityProvider()
.createGroupQuery()
.groupMember(authorizationUserId)
.list();
cachedCandidateGroups = groups.stream().map(Group::getId).collect(Collectors.toList());
}
return cachedCandidateGroups;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessDefinitionQueryImpl.java
| 1
|
请完成以下Java代码
|
public RetryConfig setMethods(HttpMethod... methods) {
this.methods = Arrays.asList(methods);
return this;
}
public List<Class<? extends Throwable>> getExceptions() {
return exceptions;
}
public RetryConfig setExceptions(Class<? extends Throwable>... exceptions) {
this.exceptions = Arrays.asList(exceptions);
return this;
}
}
public static class BackoffConfig {
private Duration firstBackoff = Duration.ofMillis(5);
private @Nullable Duration maxBackoff;
private int factor = 2;
private boolean basedOnPreviousValue = true;
public BackoffConfig() {
}
public BackoffConfig(Duration firstBackoff, Duration maxBackoff, int factor, boolean basedOnPreviousValue) {
this.firstBackoff = firstBackoff;
this.maxBackoff = maxBackoff;
this.factor = factor;
this.basedOnPreviousValue = basedOnPreviousValue;
}
public void validate() {
Objects.requireNonNull(this.firstBackoff, "firstBackoff must be present");
}
public Duration getFirstBackoff() {
return firstBackoff;
}
public void setFirstBackoff(Duration firstBackoff) {
this.firstBackoff = firstBackoff;
}
public @Nullable Duration getMaxBackoff() {
return maxBackoff;
}
public void setMaxBackoff(Duration maxBackoff) {
this.maxBackoff = maxBackoff;
}
public int getFactor() {
return factor;
}
public void setFactor(int factor) {
this.factor = factor;
}
public boolean isBasedOnPreviousValue() {
return basedOnPreviousValue;
|
}
public void setBasedOnPreviousValue(boolean basedOnPreviousValue) {
this.basedOnPreviousValue = basedOnPreviousValue;
}
@Override
public String toString() {
return new ToStringCreator(this).append("firstBackoff", firstBackoff)
.append("maxBackoff", maxBackoff)
.append("factor", factor)
.append("basedOnPreviousValue", basedOnPreviousValue)
.toString();
}
}
public static class JitterConfig {
private double randomFactor = 0.5;
public void validate() {
Assert.isTrue(randomFactor >= 0 && randomFactor <= 1,
"random factor must be between 0 and 1 (default 0.5)");
}
public JitterConfig() {
}
public JitterConfig(double randomFactor) {
this.randomFactor = randomFactor;
}
public double getRandomFactor() {
return randomFactor;
}
public void setRandomFactor(double randomFactor) {
this.randomFactor = randomFactor;
}
@Override
public String toString() {
return new ToStringCreator(this).append("randomFactor", randomFactor).toString();
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RetryGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.delegate.getAuthorities();
}
@Override
public String getUsername() {
return this.delegate.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return this.delegate.isAccountNonExpired();
}
@Override
|
public boolean isAccountNonLocked() {
return this.delegate.isAccountNonLocked();
}
@Override
public boolean isCredentialsNonExpired() {
return this.delegate.isCredentialsNonExpired();
}
@Override
public boolean isEnabled() {
return this.delegate.isEnabled();
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\provisioning\MutableUser.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public CurrencyType getDocumentCurrency() {
return documentCurrency;
}
/**
* Sets the value of the documentCurrency property.
*
* @param value
* allowed object is
* {@link CurrencyType }
*
*/
public void setDocumentCurrency(CurrencyType value) {
this.documentCurrency = value;
}
/**
* If this attribute is set to true, the issuer of the document signalizes the recipient of the document that the document shall be checked manual upon receipt before any automated processing takes place.
* This might for instance occur if previously untested fields are set or tests shall be conducted.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isManualProcessing() {
return manualProcessing;
}
/**
* Sets the value of the manualProcessing property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setManualProcessing(Boolean value) {
this.manualProcessing = value;
}
/**
* The free-text title of the document.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDocumentTitle() {
return documentTitle;
}
/**
* Sets the value of the documentTitle property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDocumentTitle(String value) {
this.documentTitle = value;
}
/**
* The language used throughout the document. Codes according to ISO 639-2 must be used.
*
* @return
* possible object is
* {@link String }
|
*
*/
public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
/**
* @Deprecated. Indicates whether prices in this document are provided in gross or in net.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isIsGrossPrice() {
return isGrossPrice;
}
/**
* Sets the value of the isGrossPrice property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setIsGrossPrice(Boolean value) {
this.isGrossPrice = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DocumentType.java
| 2
|
请完成以下Java代码
|
public Map<String, String> hgetAll(final String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.hgetAll(key);
} catch (Exception ex) {
log.error("Exception caught in hgetAll", ex);
}
return new HashMap<String, String>();
}
public Long sadd(final String key, final String... members) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.sadd(key, members);
} catch (Exception ex) {
log.error("Exception caught in sadd", ex);
}
return null;
}
public Set<String> smembers(final String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.smembers(key);
} catch (Exception ex) {
log.error("Exception caught in smembers", ex);
}
return new HashSet<String>();
}
public Long zadd(final String key, final Map<String, Double> scoreMembers) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.zadd(key, scoreMembers);
} catch (Exception ex) {
log.error("Exception caught in zadd", ex);
}
return 0L;
}
public List<String> zrange(final String key, final long start, final long stop) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.zrange(key, start, stop);
} catch (Exception ex) {
log.error("Exception caught in zrange", ex);
}
return new ArrayList<>();
}
public String mset(final HashMap<String, String> keysValues) {
try (Jedis jedis = jedisPool.getResource()) {
ArrayList<String> keysValuesArrayList = new ArrayList<>();
keysValues.forEach((key, value) -> {
|
keysValuesArrayList.add(key);
keysValuesArrayList.add(value);
});
return jedis.mset((keysValuesArrayList.toArray(new String[keysValues.size()])));
} catch (Exception ex) {
log.error("Exception caught in mset", ex);
}
return null;
}
public Set<String> keys(final String pattern) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.keys(pattern);
} catch (Exception ex) {
log.error("Exception caught in keys", ex);
}
return new HashSet<String>();
}
public RedisIterator iterator(int initialScanCount, String pattern, ScanStrategy strategy) {
return new RedisIterator(jedisPool, initialScanCount, pattern, strategy);
}
public void flushAll() {
try (Jedis jedis = jedisPool.getResource()) {
jedis.flushAll();
} catch (Exception ex) {
log.error("Exception caught in flushAll", ex);
}
}
public void destroyInstance() {
jedisPool = null;
instance = null;
}
}
|
repos\tutorials-master\persistence-modules\redis\src\main\java\com\baeldung\redis_scan\client\RedisClient.java
| 1
|
请完成以下Java代码
|
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public void setExternalSystem_Config_PrintingClient_ID (final int ExternalSystem_Config_PrintingClient_ID)
{
if (ExternalSystem_Config_PrintingClient_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_PrintingClient_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_PrintingClient_ID, ExternalSystem_Config_PrintingClient_ID);
}
@Override
public int getExternalSystem_Config_PrintingClient_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_PrintingClient_ID);
}
@Override
public void setExternalSystemValue (final java.lang.String ExternalSystemValue)
{
set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue);
|
}
@Override
public java.lang.String getExternalSystemValue()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemValue);
}
@Override
public void setTarget_Directory (final java.lang.String Target_Directory)
{
set_Value (COLUMNNAME_Target_Directory, Target_Directory);
}
@Override
public java.lang.String getTarget_Directory()
{
return get_ValueAsString(COLUMNNAME_Target_Directory);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_PrintingClient.java
| 1
|
请完成以下Java代码
|
public static String validateAccountNo (String AccountNo)
{
int length = checkNumeric(AccountNo).length();
if (length > 0)
return "";
return "PaymentBankAccountNotValid";
} // validateBankAccountNo
/**
* Validate Check No
* @param CheckNo CheckNo
* @return "" or Error AD_Message
*/
public static String validateCheckNo (String CheckNo)
{
int length = checkNumeric(CheckNo).length();
if (length > 0)
return "";
return "PaymentBankCheckNotValid";
} // validateBankCheckNo
/**
* Check Numeric
|
* @param data input
* @return the digits of the data - ignore the rest
*/
public static String checkNumeric (String data)
{
if (data == null || data.length() == 0)
return "";
// Remove all non Digits
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length(); i++)
{
if (Character.isDigit(data.charAt(i)))
sb.append(data.charAt(i));
}
return sb.toString();
} // checkNumeric
} // MPaymentValidate
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MPaymentValidate.java
| 1
|
请完成以下Java代码
|
public int getAsyncExecutorDefaultQueueSizeFullWaitTime() {
return asyncExecutorDefaultQueueSizeFullWaitTime;
}
public ProcessEngineConfigurationImpl setAsyncExecutorDefaultQueueSizeFullWaitTime(int asyncExecutorDefaultQueueSizeFullWaitTime) {
this.asyncExecutorDefaultQueueSizeFullWaitTime = asyncExecutorDefaultQueueSizeFullWaitTime;
return this;
}
public String getAsyncExecutorLockOwner() {
return asyncExecutorLockOwner;
}
public ProcessEngineConfigurationImpl setAsyncExecutorLockOwner(String asyncExecutorLockOwner) {
this.asyncExecutorLockOwner = asyncExecutorLockOwner;
return this;
}
public int getAsyncExecutorTimerLockTimeInMillis() {
return asyncExecutorTimerLockTimeInMillis;
}
public ProcessEngineConfigurationImpl setAsyncExecutorTimerLockTimeInMillis(int asyncExecutorTimerLockTimeInMillis) {
this.asyncExecutorTimerLockTimeInMillis = asyncExecutorTimerLockTimeInMillis;
return this;
}
|
public int getAsyncExecutorAsyncJobLockTimeInMillis() {
return asyncExecutorAsyncJobLockTimeInMillis;
}
public ProcessEngineConfigurationImpl setAsyncExecutorAsyncJobLockTimeInMillis(int asyncExecutorAsyncJobLockTimeInMillis) {
this.asyncExecutorAsyncJobLockTimeInMillis = asyncExecutorAsyncJobLockTimeInMillis;
return this;
}
public int getAsyncExecutorLockRetryWaitTimeInMillis() {
return asyncExecutorLockRetryWaitTimeInMillis;
}
public ProcessEngineConfigurationImpl setAsyncExecutorLockRetryWaitTimeInMillis(int asyncExecutorLockRetryWaitTimeInMillis) {
this.asyncExecutorLockRetryWaitTimeInMillis = asyncExecutorLockRetryWaitTimeInMillis;
return this;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cfg\ProcessEngineConfigurationImpl.java
| 1
|
请完成以下Java代码
|
public void compute(List<List<IWord>> sentenceList)
{
roleTag(sentenceList);
addToDictionary(sentenceList);
}
/**
* 同compute
* @param sentenceList
*/
public void learn(List<Sentence> sentenceList)
{
List<List<IWord>> s = new ArrayList<List<IWord>>(sentenceList.size());
for (Sentence sentence : sentenceList)
{
s.add(sentence.wordList);
}
compute(s);
}
/**
* 同compute
* @param sentences
*/
public void learn(Sentence ... sentences)
{
learn(Arrays.asList(sentences));
}
/**
* 训练
* @param corpus 语料库路径
*/
|
public void train(String corpus)
{
CorpusLoader.walk(corpus, new CorpusLoader.Handler()
{
@Override
public void handle(Document document)
{
List<List<Word>> simpleSentenceList = document.getSimpleSentenceList();
List<List<IWord>> compatibleList = new LinkedList<List<IWord>>();
for (List<Word> wordList : simpleSentenceList)
{
compatibleList.add(new LinkedList<IWord>(wordList));
}
CommonDictionaryMaker.this.compute(compatibleList);
}
});
}
/**
* 加入到词典中,允许子类自定义过滤等等,这样比较灵活
* @param sentenceList
*/
abstract protected void addToDictionary(List<List<IWord>> sentenceList);
/**
* 角色标注,如果子类要进行label的调整或增加新的首尾等等,可以在此进行
*/
abstract protected void roleTag(List<List<IWord>> sentenceList);
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\CommonDictionaryMaker.java
| 1
|
请完成以下Java代码
|
public static class Builder {
private final HttpStatusCode statusCode;
private final HttpHeaders headers = new HttpHeaders();
private final List<ByteBuffer> body = new ArrayList<>();
private @Nullable Instant timestamp;
public Builder(HttpStatusCode statusCode) {
this.statusCode = statusCode;
}
public Builder header(String name, String value) {
this.headers.add(name, value);
return this;
}
public Builder headers(HttpHeaders headers) {
this.headers.addAll(headers);
return this;
}
public Builder timestamp(Instant timestamp) {
|
this.timestamp = timestamp;
return this;
}
public Builder timestamp(Date timestamp) {
this.timestamp = timestamp.toInstant();
return this;
}
public Builder body(String data) {
return appendToBody(ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8)));
}
public Builder appendToBody(ByteBuffer byteBuffer) {
this.body.add(byteBuffer);
return this;
}
public CachedResponse build() {
return new CachedResponse(statusCode, headers, body, timestamp == null ? new Date() : Date.from(timestamp));
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\CachedResponse.java
| 1
|
请完成以下Java代码
|
public static InputStream getResponseAsInputStream(WebClient client, String url) throws IOException, InterruptedException {
PipedOutputStream pipedOutputStream = new PipedOutputStream();
PipedInputStream pipedInputStream = new PipedInputStream(1024 * 10);
pipedInputStream.connect(pipedOutputStream);
Flux<DataBuffer> body = client.get()
.uri(url)
.exchangeToFlux(clientResponse -> {
return clientResponse.body(BodyExtractors.toDataBuffers());
})
.doOnError(error -> {
logger.error("error occurred while reading body", error);
})
.doFinally(s -> {
try {
pipedOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.doOnCancel(() -> {
logger.error("Get request is cancelled");
});
DataBufferUtils.write(body, pipedOutputStream)
.log("Writing to output buffer")
.subscribe();
return pipedInputStream;
}
private static String readContentFromPipedInputStream(PipedInputStream stream) throws IOException {
StringBuffer contentStringBuffer = new StringBuffer();
try {
Thread pipeReader = new Thread(() -> {
try {
contentStringBuffer.append(readContent(stream));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
pipeReader.start();
pipeReader.join();
} catch (InterruptedException e) {
|
throw new RuntimeException(e);
} finally {
stream.close();
}
return String.valueOf(contentStringBuffer);
}
private static String readContent(InputStream stream) throws IOException {
StringBuffer contentStringBuffer = new StringBuffer();
byte[] tmp = new byte[stream.available()];
int byteCount = stream.read(tmp, 0, tmp.length);
logger.info(String.format("read %d bytes from the stream\n", byteCount));
contentStringBuffer.append(new String(tmp));
return String.valueOf(contentStringBuffer);
}
public static void main(String[] args) throws IOException, InterruptedException {
WebClient webClient = getWebClient();
InputStream inputStream = getResponseAsInputStream(webClient, REQUEST_ENDPOINT);
Thread.sleep(3000);
String content = readContentFromPipedInputStream((PipedInputStream) inputStream);
logger.info("response content: \n{}", content.replace("}", "}\n"));
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-reactive-3\src\main\java\com\baeldung\databuffer\DataBufferToInputStream.java
| 1
|
请完成以下Java代码
|
public String getLastName() {
return lastName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final User user = (User) o;
if (!Objects.equals(id, user.id)) {
return false;
}
if (!Objects.equals(firstName, user.firstName)) {
return false;
}
return Objects.equals(lastName, user.lastName);
}
|
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-query-4\src\main\java\com\baeldung\spring\data\jpa\querymap\User.java
| 1
|
请完成以下Java代码
|
public int getMaxRetries() {
return this.maxRetries;
}
@Override
public void setInitialInterval(long initialInterval) {
super.setInitialInterval(initialInterval);
calculateMaxElapsed();
}
@Override
public void setMultiplier(double multiplier) {
super.setMultiplier(multiplier);
calculateMaxElapsed();
}
@Override
public void setMaxInterval(long maxInterval) {
super.setMaxInterval(maxInterval);
calculateMaxElapsed();
}
@Override
public void setMaxElapsedTime(long maxElapsedTime) {
throw new IllegalStateException("'maxElapsedTime' is calculated from the 'maxRetries' property");
}
|
@SuppressWarnings("this-escape")
private void calculateMaxElapsed() {
long maxInterval = getMaxInterval();
long maxElapsed = Math.min(getInitialInterval(), maxInterval);
long current = maxElapsed;
for (int i = 1; i < this.maxRetries; i++) {
long next = Math.min((long) (current * getMultiplier()), maxInterval);
current = next;
maxElapsed += current;
}
super.setMaxElapsedTime(maxElapsed);
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\ExponentialBackOffWithMaxRetries.java
| 1
|
请完成以下Java代码
|
static final class DelayedInitializationHttpHandler implements HttpHandler {
private final Supplier<HttpHandler> handlerSupplier;
private final boolean lazyInit;
private volatile HttpHandler delegate = this::handleUninitialized;
private DelayedInitializationHttpHandler(Supplier<HttpHandler> handlerSupplier, boolean lazyInit) {
this.handlerSupplier = handlerSupplier;
this.lazyInit = lazyInit;
}
private Mono<Void> handleUninitialized(ServerHttpRequest request, ServerHttpResponse response) {
throw new IllegalStateException("The HttpHandler has not yet been initialized");
}
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
return this.delegate.handle(request, response);
}
void initializeHandler() {
this.delegate = this.lazyInit ? new LazyHttpHandler(this.handlerSupplier) : this.handlerSupplier.get();
}
HttpHandler getHandler() {
return this.delegate;
}
|
}
/**
* {@link HttpHandler} that initializes its delegate on first request.
*/
private static final class LazyHttpHandler implements HttpHandler {
private final Mono<HttpHandler> delegate;
private LazyHttpHandler(Supplier<HttpHandler> handlerSupplier) {
this.delegate = Mono.fromSupplier(handlerSupplier);
}
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
return this.delegate.flatMap((handler) -> handler.handle(request, response));
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\WebServerManager.java
| 1
|
请完成以下Java代码
|
public List<ImpDataCell> parseDataCells(final String line)
{
final int columnsCount = columns.size();
final List<ImpDataCell> cells = new ArrayList<>(columnsCount);
for (final ImpFormatColumn impFormatColumn : columns)
{
final ImpDataCell cell = parseDataCell(line, impFormatColumn);
cells.add(cell);
} // for all columns
return ImmutableList.copyOf(cells);
} // parseLine
private ImpDataCell parseDataCell(final String line, final ImpFormatColumn column)
{
try
{
final String rawValue = extractCellRawValue(line, column);
final Object value = column.parseCellValue(rawValue);
return ImpDataCell.value(value);
}
catch (final Exception ex)
{
|
return ImpDataCell.error(ErrorMessage.of(ex));
}
}
private static String extractCellRawValue(final String line, final ImpFormatColumn impFormatColumn)
{
if (impFormatColumn.isConstant())
{
return impFormatColumn.getConstantValue();
}
else
{
// check length
if (impFormatColumn.getStartNo() > 0 && impFormatColumn.getEndNo() <= line.length())
{
return line.substring(impFormatColumn.getStartNo() - 1, impFormatColumn.getEndNo());
}
else
{
return null;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\FixedPositionImpDataLineParser.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private BeanMetadataElement authorizationManager(Map<Pointcut, BeanMetadataElement> managers) {
return BeanDefinitionBuilder.rootBeanDefinition(PointcutDelegatingAuthorizationManager.class)
.addConstructorArgValue(managers)
.getBeanDefinition();
}
}
/**
* This is the real class which does the work. We need access to the ParserContext in
* order to do bean registration.
*
* @deprecated Use
* {@link InternalAuthorizationManagerInterceptMethodsBeanDefinitionDecorator}
*/
@Deprecated
static class InternalInterceptMethodsBeanDefinitionDecorator
extends AbstractInterceptorDrivenBeanDefinitionDecorator {
static final String ATT_METHOD = "method";
static final String ATT_ACCESS = "access";
private static final String ATT_ACCESS_MGR = "access-decision-manager-ref";
@Override
protected BeanDefinition createInterceptorDefinition(Node node) {
Element interceptMethodsElt = (Element) node;
BeanDefinitionBuilder interceptor = BeanDefinitionBuilder
.rootBeanDefinition(MethodSecurityInterceptor.class);
// Default to autowiring to pick up after invocation mgr
interceptor.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
String accessManagerId = interceptMethodsElt.getAttribute(ATT_ACCESS_MGR);
if (!StringUtils.hasText(accessManagerId)) {
|
accessManagerId = BeanIds.METHOD_ACCESS_MANAGER;
}
interceptor.addPropertyValue("accessDecisionManager", new RuntimeBeanReference(accessManagerId));
interceptor.addPropertyValue("authenticationManager",
new RuntimeBeanReference(BeanIds.AUTHENTICATION_MANAGER));
// Lookup parent bean information
String parentBeanClass = ((Element) interceptMethodsElt.getParentNode()).getAttribute("class");
// Parse the included methods
List<Element> methods = DomUtils.getChildElementsByTagName(interceptMethodsElt, Elements.PROTECT);
Map<String, BeanDefinition> mappings = new ManagedMap<>();
for (Element protectmethodElt : methods) {
BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder.rootBeanDefinition(SecurityConfig.class);
attributeBuilder.setFactoryMethod("createListFromCommaDelimitedString");
attributeBuilder.addConstructorArgValue(protectmethodElt.getAttribute(ATT_ACCESS));
// Support inference of class names
String methodName = protectmethodElt.getAttribute(ATT_METHOD);
if (methodName.lastIndexOf(".") == -1) {
if (parentBeanClass != null && !"".equals(parentBeanClass)) {
methodName = parentBeanClass + "." + methodName;
}
}
mappings.put(methodName, attributeBuilder.getBeanDefinition());
}
BeanDefinition metadataSource = new RootBeanDefinition(MapBasedMethodSecurityMetadataSource.class);
metadataSource.getConstructorArgumentValues().addGenericArgumentValue(mappings);
interceptor.addPropertyValue("securityMetadataSource", metadataSource);
return interceptor.getBeanDefinition();
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\InterceptMethodsBeanDefinitionDecorator.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PrometheusScrapeEndpoint {
private static final int METRICS_SCRAPE_CHARS_EXTRA = 1024;
private final PrometheusRegistry prometheusRegistry;
private final ExpositionFormats expositionFormats;
private volatile int nextMetricsScrapeSize = 16;
/**
* Creates a new {@link PrometheusScrapeEndpoint}.
* @param prometheusRegistry the Prometheus registry to use
* @param exporterProperties the properties used to configure Prometheus'
* {@link ExpositionFormats}
* @since 3.3.1
*/
public PrometheusScrapeEndpoint(PrometheusRegistry prometheusRegistry, @Nullable Properties exporterProperties) {
this.prometheusRegistry = prometheusRegistry;
PrometheusProperties prometheusProperties = (exporterProperties != null)
? PrometheusPropertiesLoader.load(exporterProperties) : PrometheusPropertiesLoader.load();
this.expositionFormats = ExpositionFormats.init(prometheusProperties.getExporterProperties());
}
@ReadOperation(producesFrom = PrometheusOutputFormat.class)
public WebEndpointResponse<byte[]> scrape(PrometheusOutputFormat format, @Nullable Set<String> includedNames) {
|
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(this.nextMetricsScrapeSize);
MetricSnapshots metricSnapshots = (includedNames != null)
? this.prometheusRegistry.scrape(includedNames::contains) : this.prometheusRegistry.scrape();
format.write(this.expositionFormats, outputStream, metricSnapshots);
byte[] content = outputStream.toByteArray();
this.nextMetricsScrapeSize = content.length + METRICS_SCRAPE_CHARS_EXTRA;
return new WebEndpointResponse<>(content, format);
}
catch (IOException ex) {
throw new IllegalStateException("Writing metrics failed", ex);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\prometheus\PrometheusScrapeEndpoint.java
| 2
|
请完成以下Java代码
|
public class PriceRateOrAmountChoice {
@XmlElement(name = "Rate")
protected BigDecimal rate;
@XmlElement(name = "Amt")
protected ActiveOrHistoricCurrencyAnd13DecimalAmount amt;
/**
* Gets the value of the rate property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getRate() {
return rate;
}
/**
* Sets the value of the rate property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setRate(BigDecimal value) {
this.rate = value;
}
/**
* Gets the value of the amt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAnd13DecimalAmount }
*
|
*/
public ActiveOrHistoricCurrencyAnd13DecimalAmount getAmt() {
return amt;
}
/**
* Sets the value of the amt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAnd13DecimalAmount }
*
*/
public void setAmt(ActiveOrHistoricCurrencyAnd13DecimalAmount value) {
this.amt = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PriceRateOrAmountChoice.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JsonResponseManufacturingOrder getManufacturingOrderNonNull()
{
if (this.jsonResponseManufacturingOrder == null)
{
throw new RuntimeCamelException("JsonResponseManufacturingOrder cannot be null!");
}
return this.jsonResponseManufacturingOrder;
}
@NonNull
public JsonProduct getProductInfoNonNull()
{
if (this.jsonProduct == null)
{
throw new RuntimeCamelException("JsonProduct cannot be null!");
}
return this.jsonProduct;
}
@NonNull
public JsonPluFileAudit getJsonPluFileAuditNonNull()
{
if (this.jsonPluFileAudit == null)
{
throw new RuntimeCamelException("JsonPluFileAudit cannot be null!");
}
return this.jsonPluFileAudit;
}
@NonNull
public String getUpdatedPLUFileContent()
{
if (this.pluFileXmlContent == null)
{
throw new RuntimeCamelException("pluFileXmlContent cannot be null!");
}
return this.pluFileXmlContent;
}
@NonNull
public String getPLUTemplateFilename()
{
if (this.pluTemplateFilename == null)
|
{
throw new RuntimeCamelException("filename cannot be null!");
}
return this.pluTemplateFilename;
}
@NonNull
public List<String> getPluFileConfigKeys()
{
return this.pluFileConfigs.getPluFileConfigs()
.stream()
.map(JsonExternalSystemLeichMehlPluFileConfig::getTargetFieldName)
.collect(ImmutableList.toImmutableList());
}
@Nullable
public Integer getAdPInstance()
{
return JsonMetasfreshId.toValue(this.jsonExternalSystemRequest.getAdPInstanceId());
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\pporder\ExportPPOrderRouteContext.java
| 2
|
请完成以下Java代码
|
public int getGL_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Category_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
|
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Reval_Entry.java
| 1
|
请完成以下Java代码
|
public Synonym randomSynonym()
{
return randomSynonym(null, null);
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append(entry);
sb.append(' ');
sb.append(type);
sb.append(' ');
sb.append(synonymList);
return sb.toString();
}
/**
* 语义距离
*
* @param other
* @return
*/
public long distance(SynonymItem other)
{
return entry.distance(other.entry);
|
}
/**
* 创建一个@类型的词典之外的条目
*
* @param word
* @return
*/
public static SynonymItem createUndefined(String word)
{
SynonymItem item = new SynonymItem(new Synonym(word, word.hashCode() * 1000000 + Long.MAX_VALUE / 3), null, Type.UNDEFINED);
return item;
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\common\CommonSynonymDictionary.java
| 1
|
请完成以下Java代码
|
public Integer getId() {
return id;
}
public UserDetailVO setId(Integer id) {
this.id = id;
return this;
}
public String getUsername() {
return username;
}
public UserDetailVO setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
return password;
}
public UserDetailVO setPassword(String password) {
this.password = password;
return this;
}
public Integer getGender() {
return gender;
}
public UserDetailVO setGender(Integer gender) {
this.gender = gender;
return this;
}
public Date getCreateTime() {
return createTime;
}
public UserDetailVO setCreateTime(Date createTime) {
this.createTime = createTime;
return this;
}
public Integer getDeleted() {
return deleted;
}
|
public UserDetailVO setDeleted(Integer deleted) {
this.deleted = deleted;
return this;
}
public Integer getTenantId() {
return tenantId;
}
public UserDetailVO setTenantId(Integer tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public String toString() {
return "UserDetailVO{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender=" + gender +
", createTime=" + createTime +
", deleted=" + deleted +
", tenantId=" + tenantId +
'}';
}
}
|
repos\SpringBoot-Labs-master\lab-12-mybatis\lab-12-mybatis-plus-tenant\src\main\java\cn\iocoder\springboot\lab12\mybatis\vo\UserDetailVO.java
| 1
|
请完成以下Java代码
|
public void setPriceLimit(final BigDecimal priceLimit)
{
this.priceLimit = priceLimit;
this.priceLimitSet = true;
}
public void setPriceList(final BigDecimal priceList)
{
this.priceList = priceList;
this.priceListSet = true;
}
public void setPriceStd(final BigDecimal priceStd)
{
this.priceStd = priceStd;
}
public void setSeqNo(final Integer seqNo)
{
this.seqNo = seqNo;
this.seqNoSet = true;
}
public void setTaxCategory(final TaxCategory taxCategory)
{
this.taxCategory = taxCategory;
}
public void setActive(final Boolean active)
{
this.active = active;
this.activeSet = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
this.syncAdviseSet = true;
}
public void setUomCode(final String uomCode)
{
this.uomCode = uomCode;
this.uomCodeSet = true;
}
|
@NonNull
public String getOrgCode()
{
return orgCode;
}
@NonNull
public String getProductIdentifier()
{
return productIdentifier;
}
@NonNull
public TaxCategory getTaxCategory()
{
return taxCategory;
}
@NonNull
public BigDecimal getPriceStd()
{
return priceStd;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-pricing\src\main\java\de\metas\common\pricing\v2\productprice\JsonRequestProductPrice.java
| 1
|
请完成以下Java代码
|
protected PermissionType noPermission()
{
return null;
}
@Override
public final Optional<PermissionType> getPermissionIfExists(final Resource resource)
{
return Optional.fromNullable(permissions.get(resource));
}
@Override
public final PermissionType getPermissionOrDefault(final Resource resource)
{
//
// Get the permission for given resource
final Optional<PermissionType> permission = getPermissionIfExists(resource);
if (permission.isPresent())
{
return permission.get();
}
//
// Fallback: get the permission defined for the resource of "no permission", if any
|
final PermissionType nonePermission = noPermission();
if (nonePermission == null)
{
return null;
}
final Resource defaultResource = nonePermission.getResource();
return getPermissionIfExists(defaultResource)
// Fallback: return the "no permission"
.or(nonePermission);
}
@Override
public final boolean hasPermission(final Permission permission)
{
return permissions.values().contains(permission);
}
@Override
public final boolean hasAccess(final Resource resource, final Access access)
{
return getPermissionOrDefault(resource).hasAccess(access);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\AbstractPermissions.java
| 1
|
请完成以下Java代码
|
public void changeOwner(Task task, String owner) {
TaskHelper.changeTaskOwner((TaskEntity) task, owner);
}
@Override
public void addCandidateUser(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink);
}
@Override
public void addCandidateUsers(Task task, List<IdentityLink> candidateUsers) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
for (IdentityLink identityLink : candidateUsers) {
identityLinks.add((IdentityLinkEntity) identityLink);
}
IdentityLinkUtil.handleTaskIdentityLinkAdditions((TaskEntity) task, identityLinks);
}
@Override
public void addCandidateGroup(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink);
}
@Override
public void addCandidateGroups(Task task, List<IdentityLink> candidateGroups) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
for (IdentityLink identityLink : candidateGroups) {
identityLinks.add((IdentityLinkEntity) identityLink);
}
IdentityLinkUtil.handleTaskIdentityLinkAdditions((TaskEntity) task, identityLinks);
}
@Override
public void addUserIdentityLink(Task task, IdentityLink identityLink) {
|
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink);
}
@Override
public void addGroupIdentityLink(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink);
}
@Override
public void deleteUserIdentityLink(Task task, IdentityLink identityLink) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
identityLinks.add((IdentityLinkEntity) identityLink);
IdentityLinkUtil.handleTaskIdentityLinkDeletions((TaskEntity) task, identityLinks, true, true);
}
@Override
public void deleteGroupIdentityLink(Task task, IdentityLink identityLink) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
identityLinks.add((IdentityLinkEntity) identityLink);
IdentityLinkUtil.handleTaskIdentityLinkDeletions((TaskEntity) task, identityLinks, true, true);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\DefaultTaskAssignmentManager.java
| 1
|
请完成以下Java代码
|
public static String generateName(int i) {
return GENERATED_NAME_PREFIX + i;
}
public static String normalizeRoutePredicateName(Class<? extends RoutePredicateFactory> clazz) {
return removeGarbage(clazz.getSimpleName().replace(RoutePredicateFactory.class.getSimpleName(), ""));
}
public static String normalizeRoutePredicateNameAsProperty(Class<? extends RoutePredicateFactory> clazz) {
return normalizeToCanonicalPropertyFormat(normalizeRoutePredicateName(clazz));
}
public static String normalizeFilterFactoryName(Class<? extends GatewayFilterFactory> clazz) {
return removeGarbage(clazz.getSimpleName().replace(GatewayFilterFactory.class.getSimpleName(), ""));
}
public static String normalizeGlobalFilterName(Class<? extends GlobalFilter> clazz) {
return removeGarbage(clazz.getSimpleName().replace(GlobalFilter.class.getSimpleName(), "")).replace("Filter",
"");
}
public static String normalizeFilterFactoryNameAsProperty(Class<? extends GatewayFilterFactory> clazz) {
return normalizeToCanonicalPropertyFormat(normalizeFilterFactoryName(clazz));
}
public static String normalizeGlobalFilterNameAsProperty(Class<? extends GlobalFilter> filterClass) {
return normalizeToCanonicalPropertyFormat(normalizeGlobalFilterName(filterClass));
}
public static String normalizeToCanonicalPropertyFormat(String name) {
|
Matcher matcher = NAME_PATTERN.matcher(name);
StringBuffer stringBuffer = new StringBuffer();
while (matcher.find()) {
if (stringBuffer.length() != 0) {
matcher.appendReplacement(stringBuffer, "-" + matcher.group(1));
}
else {
matcher.appendReplacement(stringBuffer, matcher.group(1));
}
}
return stringBuffer.toString().toLowerCase(Locale.ROOT);
}
private static String removeGarbage(String s) {
int garbageIdx = s.indexOf("$Mockito");
if (garbageIdx > 0) {
return s.substring(0, garbageIdx);
}
return s;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\NameUtils.java
| 1
|
请完成以下Java代码
|
public static AsyncBatchId ofRepoIdOr(final int repoId, @NonNull final Supplier<AsyncBatchId> supplier)
{
return repoId > 0 ? new AsyncBatchId(repoId) : supplier.get();
}
public static int toRepoId(@Nullable final AsyncBatchId asyncBatchId)
{
return asyncBatchId != null ? asyncBatchId.getRepoId() : -1;
}
@Nullable
public static AsyncBatchId toAsyncBatchIdOrNull(@Nullable final AsyncBatchId asyncBatchId)
{
return asyncBatchId != null && !asyncBatchId.equals(NONE_ASYNC_BATCH_ID)
? asyncBatchId
|
: null;
}
private AsyncBatchId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "asyncBatchId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\AsyncBatchId.java
| 1
|
请完成以下Java代码
|
public static ProductsProposalViewFilter extractPackageableViewFilterVO(@NonNull final JSONFilterViewRequest filterViewRequest)
{
final DocumentFilterList filters = filterViewRequest.getFiltersUnwrapped(getDescriptors());
return extractPackageableViewFilterVO(filters);
}
private static ProductsProposalViewFilter extractPackageableViewFilterVO(final DocumentFilterList filters)
{
return filters.getFilterById(ProductsProposalViewFilter.FILTER_ID)
.map(filter -> toProductsProposalViewFilterValue(filter))
.orElse(ProductsProposalViewFilter.ANY);
}
private static ProductsProposalViewFilter toProductsProposalViewFilterValue(final DocumentFilter filter)
{
return ProductsProposalViewFilter.builder()
.productName(filter.getParameterValueAsString(ProductsProposalViewFilter.PARAM_ProductName, null))
.build();
}
public static DocumentFilterList toDocumentFilters(final ProductsProposalViewFilter filter)
|
{
final DocumentFilter.DocumentFilterBuilder builder = DocumentFilter.builder()
.setFilterId(ProductsProposalViewFilter.FILTER_ID)
.setCaption(getDefaultFilterCaption());
if (!Check.isEmpty(filter.getProductName()))
{
builder.addParameter(DocumentFilterParam.ofNameEqualsValue(ProductsProposalViewFilter.PARAM_ProductName, filter.getProductName()));
}
if (!builder.hasParameters())
{
return DocumentFilterList.EMPTY;
}
return DocumentFilterList.of(builder.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\filters\ProductsProposalViewFilters.java
| 1
|
请完成以下Java代码
|
public static String TO_CHAR(
final String columnName,
final int displayType,
final String formatPattern)
{
if (Check.isEmpty(formatPattern, false))
{
return TO_CHAR(columnName);
}
else if (DisplayType.isNumeric(displayType))
{
final String pgFormatPattern = convertDecimalPatternToPG(formatPattern);
if (pgFormatPattern == null)
{
return TO_CHAR(columnName);
}
return TO_CHAR("to_char(" + columnName + ", '" + pgFormatPattern + "')");
}
else
{
return TO_CHAR(columnName);
}
}
/**
* Convert {@link DecimalFormat} pattern to PostgreSQL's number formatting pattern
* <p>
* See <a href="http://www.postgresql.org/docs/9.1/static/functions-formatting.html#FUNCTIONS-FORMATTING-NUMERIC-TABLE">http://www.postgresql.org/docs/9.1/static/functions-formatting.html#FUNCTIONS-FORMATTING-NUMERIC-TABLE</a>.
*
* @return PostgreSQL's number formatting pattern or <code>null</code> if it could not be converted
* @see DecimalFormat
*/
@VisibleForTesting
@Nullable
/* package */ static String convertDecimalPatternToPG(final String formatPattern)
{
if (formatPattern == null || formatPattern.isEmpty())
{
return null;
}
final StringBuilder pgFormatPattern = new StringBuilder(formatPattern.length() + 2);
pgFormatPattern.append("FM"); // fill mode (suppress padding blanks and trailing zeroes)
for (int i = 0; i < formatPattern.length(); i++)
{
final char ch = formatPattern.charAt(i);
// Case: chars that don't need to be translated because have the same meaning
if (ch == '0' || ch == '.' || ch == ',')
{
pgFormatPattern.append(ch);
}
// Case: # - Digit, zero shows as absent
// Convert to: 9 - value with the specified number of digits
else if (ch == '#')
{
pgFormatPattern.append('9');
}
// Case: invalid char / char that we cannot convert (atm)
else
{
return null;
|
}
}
return pgFormatPattern.toString();
}
/**
* Return number as string for INSERT statements with correct precision
*
* @param number number
* @param displayType display Type
* @return number as string
*/
public static String TO_NUMBER(final BigDecimal number, final int displayType)
{
if (number == null)
{
return "NULL";
}
BigDecimal result = number;
final int scale = DisplayType.getDefaultPrecision(displayType);
if (scale > number.scale())
{
result = number.setScale(scale, RoundingMode.HALF_UP);
}
return result.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\Database.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessBusinessKey() {
return processBusinessKey;
}
public void setProcessBusinessKey(String processBusinessKey) {
this.processBusinessKey = processBusinessKey;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public String getSignalEventSubscriptionName() {
return signalEventSubscriptionName;
}
public void setSignalEventSubscriptionName(String signalEventSubscriptionName) {
this.signalEventSubscriptionName = signalEventSubscriptionName;
}
public String getMessageEventSubscriptionName() {
return messageEventSubscriptionName;
}
public void setMessageEventSubscriptionName(String messageEventSubscriptionName) {
this.messageEventSubscriptionName = messageEventSubscriptionName;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getParentId() {
return parentId;
}
|
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(Set<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionQueryRequest.java
| 2
|
请完成以下Java代码
|
public int getMarginRight ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MarginRight);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Top Margin.
@param MarginTop
Top Space in 1/72 inch
*/
public void setMarginTop (int MarginTop)
{
set_Value (COLUMNNAME_MarginTop, Integer.valueOf(MarginTop));
}
/** Get Top Margin.
@return Top Space in 1/72 inch
*/
public int getMarginTop ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MarginTop);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Size X.
@param SizeX
X (horizontal) dimension size
*/
public void setSizeX (BigDecimal SizeX)
|
{
set_Value (COLUMNNAME_SizeX, SizeX);
}
/** Get Size X.
@return X (horizontal) dimension size
*/
public BigDecimal getSizeX ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SizeX);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Size Y.
@param SizeY
Y (vertical) dimension size
*/
public void setSizeY (BigDecimal SizeY)
{
set_Value (COLUMNNAME_SizeY, SizeY);
}
/** Get Size Y.
@return Y (vertical) dimension size
*/
public BigDecimal getSizeY ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SizeY);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintPaper.java
| 1
|
请完成以下Java代码
|
public ValueMapperException valueMapperExceptionDueToSerializerNotFoundForTypedValue(TypedValue typedValue) {
return new ValueMapperException(exceptionMessage(
"023", "Cannot find serializer for value '{}'", typedValue));
}
public ValueMapperException valueMapperExceptionDueToSerializerNotFoundForTypedValueField(Object value) {
return new ValueMapperException(exceptionMessage(
"024", "Cannot find serializer for value '{}'", value));
}
public ValueMapperException cannotSerializeVariable(String variableName, Throwable e) {
return new ValueMapperException(exceptionMessage("025", "Cannot serialize variable '{}'", variableName), e);
}
public void logDataFormats(Collection<DataFormat> formats) {
if (isInfoEnabled()) {
for (DataFormat format : formats) {
logDataFormat(format);
}
}
}
protected void logDataFormat(DataFormat dataFormat) {
logInfo("025", "Discovered data format: {}[name = {}]", dataFormat.getClass().getName(), dataFormat.getName());
}
public void logDataFormatProvider(DataFormatProvider provider) {
if (isInfoEnabled()) {
logInfo("026", "Discovered data format provider: {}[name = {}]",
provider.getClass().getName(), provider.getDataFormatName());
}
}
@SuppressWarnings("rawtypes")
public void logDataFormatConfigurator(DataFormatConfigurator configurator) {
|
if (isInfoEnabled()) {
logInfo("027", "Discovered data format configurator: {}[dataformat = {}]",
configurator.getClass(), configurator.getDataFormatClass().getName());
}
}
public ExternalTaskClientException multipleProvidersForDataformat(String dataFormatName) {
return new ExternalTaskClientException(exceptionMessage("028", "Multiple providers found for dataformat '{}'", dataFormatName));
}
public ExternalTaskClientException passNullValueParameter(String parameterName) {
return new ExternalTaskClientException(exceptionMessage(
"030", "Null value is not allowed as '{}'", parameterName));
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientLogger.java
| 1
|
请完成以下Java代码
|
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
|
public Date getSubmissionDate() {
return submissionDate;
}
public void setSubmissionDate(Date submissionDate) {
this.submissionDate = submissionDate;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\model\Post.java
| 1
|
请完成以下Java代码
|
public class CustomKeyStoreParam extends AbstractKeyStoreParam {
/**
* 公钥/私钥在磁盘上的存储路径
*/
private final String storePath;
private final String alias;
private final String storePwd;
private final String keyPwd;
public CustomKeyStoreParam(Class clazz, String resource, String alias, String storePwd, String keyPwd) {
super(clazz, resource);
this.storePath = resource;
this.alias = alias;
this.storePwd = storePwd;
this.keyPwd = keyPwd;
}
@Override
public String getAlias() {
return alias;
}
@Override
public String getStorePwd() {
return storePwd;
|
}
@Override
public String getKeyPwd() {
return keyPwd;
}
/**
* <p>项目名称: true-license-demo </p>
* <p>文件名称: CustomKeyStoreParam.java </p>
* <p>方法描述: 用于将公私钥存储文件存放到其他磁盘位置而不是项目中,AbstractKeyStoreParam 里面的 getStream() 方法默认文件是存储的项目中 </p>
* <p>创建时间: 2020/10/10 13:31 </p>
*
* @param
* @return java.io.InputStream
* @author 方瑞冬
* @version 1.0
*/
@Override
public InputStream getStream() throws IOException {
return new FileInputStream(new File(storePath));
}
}
|
repos\springboot-demo-master\SoftwareLicense\src\main\java\com\et\license\license\CustomKeyStoreParam.java
| 1
|
请完成以下Java代码
|
public static XMLGregorianCalendar toXMLGregorianCalendar(final LocalDateTime date)
{
if (date == null)
{
return null;
}
final GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(date.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
return datatypeFactoryHolder.get().newXMLGregorianCalendar(c);
}
public static XMLGregorianCalendar toXMLGregorianCalendar(final ZonedDateTime date)
{
if (date == null)
{
return null;
}
final GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(date.toInstant().toEpochMilli());
return datatypeFactoryHolder.get().newXMLGregorianCalendar(c);
}
public static LocalDateTime toLocalDateTime(final XMLGregorianCalendar xml)
{
if (xml == null)
{
return null;
}
return xml.toGregorianCalendar().toZonedDateTime().toLocalDateTime();
}
public static ZonedDateTime toZonedDateTime(final XMLGregorianCalendar xml)
{
|
if (xml == null)
{
return null;
}
return xml.toGregorianCalendar().toZonedDateTime();
}
public static java.util.Date toDate(final XMLGregorianCalendar xml)
{
return xml == null ? null : xml.toGregorianCalendar().getTime();
}
public static Timestamp toTimestamp(final XMLGregorianCalendar xmlGregorianCalendar)
{
final Date date = toDate(xmlGregorianCalendar);
if (date == null)
{
return null;
}
return new Timestamp(date.getTime());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\util\JAXBDateUtils.java
| 1
|
请完成以下Spring Boot application配置
|
sharding:
jdbc:
dataSource:
names: db-test0,db-test1,db-test2
#
db-test0: #org.apache.tomcat.jdbc.pool.DataSource
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://{master-host}:3306/cool?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
username: root
password:
#
maxPoolSize: 20
db-test1: # õһӿ
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://{slave1-host}:3306/cool?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT
username: root
password:
maxPoolSize: 20
db-test2: # õڶӿ
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://{slave2-host}:3306/cool?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezon
|
e=GMT
username: root
password:
maxPoolSize: 20
config:
masterslave: # öд
load-balance-algorithm-type: round_robin # ôӿѡԣṩѯѡѯ//random //round_robin ѯ
name: db1s2
master-data-source-name: db-test0
slave-data-source-names: db-test1,db-test2
props:
sql: # SQLʾĬֵ: falseע⣺öдʱӡ־
show: true
server.port: 8085
mybatis.config-location: classpath:META-INF/mybatis-config.xml
|
repos\SpringBootLearning-master\sharding-jdbc-example\sharding-jdbc-master-slave\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public class TaskAssignedListenerDelegate implements ActivitiEventListener {
private final List<TaskRuntimeEventListener<TaskAssignedEvent>> listeners;
private final ToAPITaskAssignedEventConverter taskAssignedEventConverter;
public TaskAssignedListenerDelegate(
List<TaskRuntimeEventListener<TaskAssignedEvent>> listeners,
ToAPITaskAssignedEventConverter taskAssignedEventConverter
) {
this.listeners = listeners;
this.taskAssignedEventConverter = taskAssignedEventConverter;
}
@Override
public void onEvent(ActivitiEvent event) {
|
if (event instanceof ActivitiEntityEvent) {
taskAssignedEventConverter
.from((ActivitiEntityEvent) event)
.ifPresent(convertedEvent -> {
for (TaskRuntimeEventListener<TaskAssignedEvent> listener : listeners) {
listener.onEvent(convertedEvent);
}
});
}
}
@Override
public boolean isFailOnException() {
return false;
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TaskAssignedListenerDelegate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private ProductUpsertCamelRequest getProductUpsertCamelRequest(@NonNull final JsonBOM jsonBOM){
final TokenCredentials credentials = (TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials();
final JsonRequestProduct requestProduct = new JsonRequestProduct();
requestProduct.setCode(jsonBOM.getProductValue());
requestProduct.setActive(jsonBOM.isActive());
requestProduct.setType(JsonRequestProduct.Type.ITEM);
requestProduct.setName(JsonBOMUtil.getName(jsonBOM));
requestProduct.setUomCode(GRSSignumConstants.DEFAULT_UOM_CODE);
requestProduct.setGtin(jsonBOM.getGtin());
requestProduct.setBpartnerProductItems(ImmutableList.of(getBPartnerProductUpsertRequest(jsonBOM)));
final JsonRequestProductUpsertItem productUpsertItem = JsonRequestProductUpsertItem.builder()
.productIdentifier(ExternalIdentifierFormat.asExternalIdentifier(jsonBOM.getProductId()))
.requestProduct(requestProduct)
.build();
final JsonRequestProductUpsert productUpsert = JsonRequestProductUpsert.builder()
.requestItem(productUpsertItem)
.syncAdvise(SyncAdvise.CREATE_OR_MERGE)
.build();
return ProductUpsertCamelRequest.builder()
.orgCode(credentials.getOrgCode())
.jsonRequestProductUpsert(productUpsert)
.build();
}
@NonNull
|
private JsonRequestBPartnerProductUpsert getBPartnerProductUpsertRequest(@NonNull final JsonBOM jsonBOM)
{
if(Check.isBlank(jsonBOM.getBPartnerMetasfreshId()))
{
throw new RuntimeException("Missing mandatory METASFRESHID! JsonBOM.ARTNRID=" + jsonBOM.getProductId());
}
final JsonRequestBPartnerProductUpsert requestBPartnerProductUpsert = new JsonRequestBPartnerProductUpsert();
requestBPartnerProductUpsert.setBpartnerIdentifier(jsonBOM.getBPartnerMetasfreshId());
requestBPartnerProductUpsert.setActive(true);
return requestBPartnerProductUpsert;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\bom\processor\PushProductProcessor.java
| 2
|
请完成以下Java代码
|
public class Player {
private int ranking;
private String name;
private int age;
public Player(int ranking, String name, int age) {
this.ranking = ranking;
this.name = name;
this.age = age;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.name;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang\src\main\java\com\baeldung\comparator\Player.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class InvokeHandlerAndLogRequest
{
@NonNull
Class<?> handlerClass;
@NonNull
Runnable invokaction;
@Default
boolean onlyIfNotAlreadyProcessed = true;
}
/**
* Invokes the given {@code request}'s runnable and sets up a threadlocal {@link ILoggable}.
*/
public void invokeHandlerAndLog(@NonNull final InvokeHandlerAndLogRequest request)
{
if (request.isOnlyIfNotAlreadyProcessed()
&& wasEventProcessedByHandler(request.getHandlerClass()))
{
return;
}
try (final IAutoCloseable loggable = EventLogLoggable.createAndRegisterThreadLocal(request.getHandlerClass()))
{
request.getInvokaction().run();
newLogEntry(request.getHandlerClass())
.formattedMessage("this handler is done")
.processed(true)
.createAndStore();
}
|
catch (final RuntimeException e)
{
// e.printStackTrace();
newErrorLogEntry(
request.getHandlerClass(), e)
.createAndStore();
}
}
private boolean wasEventProcessedByHandler(@NonNull final Class<?> handlerClass)
{
final EventLogEntryCollector eventLogCollector = EventLogEntryCollector.getThreadLocal();
final Collection<String> processedByHandlerClassNames = eventLogCollector.getEvent()
.getProperty(PROPERTY_PROCESSED_BY_HANDLER_CLASS_NAMES);
return processedByHandlerClassNames != null
&& processedByHandlerClassNames.contains(handlerClass.getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogUserService.java
| 2
|
请完成以下Java代码
|
public class ClassLoaderUtil {
public static ClassLoader getContextClassloader() {
if(System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
} else {
return Thread.currentThread().getContextClassLoader();
}
}
public static ClassLoader getClassloader(final Class<?> clazz) {
if(System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return clazz.getClassLoader();
}
});
} else {
return clazz.getClassLoader();
}
}
public static void setContextClassloader(final ClassLoader classLoader) {
if(System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
Thread.currentThread().setContextClassLoader(classLoader);
return null;
}
});
} else {
Thread.currentThread().setContextClassLoader(classLoader);
}
}
|
public static ClassLoader getServletContextClassloader(final ServletContextEvent sce) {
if(System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return sce.getServletContext().getClassLoader();
}
});
} else {
return sce.getServletContext().getClassLoader();
}
}
/**
* Switch the current Thread ClassLoader to the ProcessEngine's
* to assure the loading of the engine classes during job execution.
*
* @return the current Thread ClassLoader
*/
public static ClassLoader switchToProcessEngineClassloader() {
ClassLoader currentClassloader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(ProcessEngine.class.getClassLoader());
return currentClassloader;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ClassLoaderUtil.java
| 1
|
请完成以下Java代码
|
public void setEMail (final @Nullable java.lang.String EMail)
{
set_Value (COLUMNNAME_EMail, EMail);
}
@Override
public java.lang.String getEMail()
{
return get_ValueAsString(COLUMNNAME_EMail);
}
@Override
public void setFirstname (final @Nullable java.lang.String Firstname)
{
set_Value (COLUMNNAME_Firstname, Firstname);
}
@Override
public java.lang.String getFirstname()
{
return get_ValueAsString(COLUMNNAME_Firstname);
}
@Override
public void setIsDefaultContact (final boolean IsDefaultContact)
{
set_Value (COLUMNNAME_IsDefaultContact, IsDefaultContact);
}
@Override
public boolean isDefaultContact()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefaultContact);
}
/**
* IsInvoiceEmailEnabled AD_Reference_ID=319
* Reference name: _YesNo
*/
public static final int ISINVOICEEMAILENABLED_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISINVOICEEMAILENABLED_Yes = "Y";
/** No = N */
public static final String ISINVOICEEMAILENABLED_No = "N";
@Override
public void setIsInvoiceEmailEnabled (final @Nullable java.lang.String IsInvoiceEmailEnabled)
{
set_Value (COLUMNNAME_IsInvoiceEmailEnabled, IsInvoiceEmailEnabled);
}
@Override
public java.lang.String getIsInvoiceEmailEnabled()
{
return get_ValueAsString(COLUMNNAME_IsInvoiceEmailEnabled);
}
@Override
public void setIsMembershipContact (final boolean IsMembershipContact)
{
set_Value (COLUMNNAME_IsMembershipContact, IsMembershipContact);
}
@Override
public boolean isMembershipContact()
{
return get_ValueAsBoolean(COLUMNNAME_IsMembershipContact);
}
@Override
public void setIsNewsletter (final boolean IsNewsletter)
{
set_Value (COLUMNNAME_IsNewsletter, IsNewsletter);
}
@Override
public boolean isNewsletter()
{
return get_ValueAsBoolean(COLUMNNAME_IsNewsletter);
}
@Override
|
public void setLastname (final @Nullable java.lang.String Lastname)
{
set_Value (COLUMNNAME_Lastname, Lastname);
}
@Override
public java.lang.String getLastname()
{
return get_ValueAsString(COLUMNNAME_Lastname);
}
@Override
public void setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPhone2 (final @Nullable java.lang.String Phone2)
{
set_Value (COLUMNNAME_Phone2, Phone2);
}
@Override
public java.lang.String getPhone2()
{
return get_ValueAsString(COLUMNNAME_Phone2);
}
@Override
public void setTitle (final @Nullable java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class HistoricDecisionDefinitionRestServiceImpl implements HistoricDecisionDefinitionRestService {
protected ObjectMapper objectMapper;
protected ProcessEngine processEngine;
public HistoricDecisionDefinitionRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) {
this.objectMapper = objectMapper;
this.processEngine = processEngine;
}
@Override
public List<CleanableHistoricDecisionInstanceReportResultDto> getCleanableHistoricDecisionInstanceReport(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
CleanableHistoricDecisionInstanceReportDto queryDto = new CleanableHistoricDecisionInstanceReportDto(objectMapper, uriInfo.getQueryParameters());
CleanableHistoricDecisionInstanceReport query = queryDto.toQuery(processEngine);
List<CleanableHistoricDecisionInstanceReportResult> reportResult = QueryUtil.list(query, firstResult, maxResults);
return CleanableHistoricDecisionInstanceReportResultDto.convert(reportResult);
|
}
@Override
public CountResultDto getCleanableHistoricDecisionInstanceReportCount(UriInfo uriInfo) {
CleanableHistoricDecisionInstanceReportDto queryDto = new CleanableHistoricDecisionInstanceReportDto(objectMapper, uriInfo.getQueryParameters());
queryDto.setObjectMapper(objectMapper);
CleanableHistoricDecisionInstanceReport query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricDecisionDefinitionRestServiceImpl.java
| 2
|
请完成以下Java代码
|
private void invalidateFreightCostCandidateIfNeeded(final I_M_InOut inout)
{
final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class);
final OrderId orderId = OrderId.ofRepoIdOrNull(inout.getC_Order_ID());
if (orderId == null)
{
// nothing to do
return;
}
invoiceCandDAO.invalidateUninvoicedFreightCostCandidate(orderId);
}
private void invalidateCandidatesForInOut(final I_M_InOut inout)
{
//
// Retrieve inout line handlers
final Properties ctx = InterfaceWrapperHelper.getCtx(inout);
final List<IInvoiceCandidateHandler> inoutLineHandlers = Services.get(IInvoiceCandidateHandlerBL.class).retrieveImplementationsForTable(ctx, org.compiere.model.I_M_InOutLine.Table_Name);
for (final IInvoiceCandidateHandler handler : inoutLineHandlers)
{
for (final org.compiere.model.I_M_InOutLine line : inOutDAO.retrieveLines(inout))
{
handler.invalidateCandidatesFor(line);
}
}
}
@Override
public String getSourceTable()
{
return org.compiere.model.I_M_InOut.Table_Name;
}
|
@Override
public boolean isUserInChargeUserEditable()
{
return false;
}
@Override
public void setOrderedData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic)
{
throw new UnsupportedOperationException();
}
@Override
public void setBPartnerData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\invoicecandidate\M_InOut_Handler.java
| 1
|
请完成以下Java代码
|
public String getLabel() {
return label;
}
/**
* @param label the label to set
*/
public void setLabel(String label) {
this.label = label;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
|
public String getSlotTitle() {
return slotTitle;
}
public void setSlotTitle(String slotTitle) {
this.slotTitle = slotTitle;
}
public Integer getRuleFlag() {
return ruleFlag;
}
public void setRuleFlag(Integer ruleFlag) {
this.ruleFlag = ruleFlag;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\TreeModel.java
| 1
|
请完成以下Java代码
|
public static final class Builder
{
private Map<String, TableCalloutsMap> registeredCalloutsByTableId = null;
private Builder()
{
super();
}
public ICalloutProvider build()
{
if (registeredCalloutsByTableId == null || registeredCalloutsByTableId.isEmpty())
{
return ICalloutProvider.NULL;
}
return new ImmutablePlainCalloutProvider(this);
}
|
public Builder addCallout(final String tableName, final String columnName, final ICalloutInstance callout)
{
Check.assumeNotNull(tableName, "TableName not null");
Check.assumeNotNull(columnName, "ColumnName not null");
Check.assumeNotNull(callout, "callout not null");
//
// Add the new callout to our internal map
if (registeredCalloutsByTableId == null)
{
registeredCalloutsByTableId = new HashMap<>();
}
registeredCalloutsByTableId.compute(tableName, (tableNameKey, currentTabCalloutsMap) -> TableCalloutsMap.compose(currentTabCalloutsMap, columnName, callout));
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\spi\ImmutablePlainCalloutProvider.java
| 1
|
请完成以下Java代码
|
public class UsageBasedBilling {
static final String SUBMIT_CMD = "submit";
static final String FETCH_CMD = "fetch";
private JCommander jCommander;
private SubmitUsageCommand submitUsageCmd;
private FetchCurrentChargesCommand fetchChargesCmd;
public UsageBasedBilling() {
this.submitUsageCmd = new SubmitUsageCommand();
this.fetchChargesCmd = new FetchCurrentChargesCommand();
jCommander = JCommander.newBuilder()
.addObject(this)
.addCommand(submitUsageCmd)
.addCommand(fetchChargesCmd)
.build();
setUsageFormatter(SUBMIT_CMD);
setUsageFormatter(FETCH_CMD);
}
public void run(String[] args) {
String parsedCmdStr;
try {
jCommander.parse(args);
parsedCmdStr = jCommander.getParsedCommand();
switch (parsedCmdStr) {
case SUBMIT_CMD:
if (submitUsageCmd.isHelp()) {
getSubCommandHandle(SUBMIT_CMD).usage();
}
System.out.println("Parsing usage request...");
submitUsageCmd.submit();
break;
case FETCH_CMD:
if (fetchChargesCmd.isHelp()) {
getSubCommandHandle(SUBMIT_CMD).usage();
}
System.out.println("Preparing fetch query...");
fetchChargesCmd.fetch();
break;
|
default:
System.err.println("Invalid command: " + parsedCmdStr);
}
} catch (ParameterException e) {
System.err.println(e.getLocalizedMessage());
parsedCmdStr = jCommander.getParsedCommand();
if (parsedCmdStr != null) {
getSubCommandHandle(parsedCmdStr).usage();
} else {
jCommander.usage();
}
}
}
private JCommander getSubCommandHandle(String command) {
JCommander cmd = jCommander.getCommands().get(command);
if (cmd == null) {
System.err.println("Invalid command: " + command);
}
return cmd;
}
private void setUsageFormatter(String subCommand) {
JCommander cmd = getSubCommandHandle(subCommand);
cmd.setUsageFormatter(new UnixStyleUsageFormatter(cmd));
}
}
|
repos\tutorials-master\libraries-cli\src\main\java\com\baeldung\jcommander\usagebilling\cli\UsageBasedBilling.java
| 1
|
请完成以下Java代码
|
public void onAttributeValueChanged(
@NonNull final IAttributeValueContext attributeValueContext,
@NonNull final IAttributeStorage storage,
final IAttributeValue attributeValue,
final Object valueOld)
{
// checks and so on
final AbstractHUAttributeStorage huAttributeStorage = AbstractHUAttributeStorage.castOrNull(storage);
final boolean storageIsAboutHUs = huAttributeStorage != null;
if (!storageIsAboutHUs)
{
return;
}
final boolean relevantAttributesArePresent = storage.hasAttribute(HUAttributeConstants.ATTR_Age)
&& storage.hasAttribute(HUAttributeConstants.ATTR_ProductionDate);
if (!relevantAttributesArePresent)
{
return;
}
final AttributeCode attributeCode = attributeValue.getAttributeCode();
final boolean relevantAttributeHasChanged = HUAttributeConstants.ATTR_ProductionDate.equals(attributeCode);
if (!relevantAttributeHasChanged)
|
{
return;
}
// actual logic starts here
final LocalDateTime productionDate = storage.getValueAsLocalDateTime(HUAttributeConstants.ATTR_ProductionDate);
if (productionDate != null)
{
final Age age = ageAttributesService.getAgeValues().computeAgeInMonths(productionDate);
storage.setValue(HUAttributeConstants.ATTR_Age, age.toStringValue());
}
else
{
storage.setValue(HUAttributeConstants.ATTR_Age, null);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\age\AgeAttributeStorageListener.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public abstract class AbstractSecurityBuilder<O> implements SecurityBuilder<O> {
private AtomicBoolean building = new AtomicBoolean();
private O object;
@Override
public final O build() {
if (this.building.compareAndSet(false, true)) {
this.object = doBuild();
return this.object;
}
throw new AlreadyBuiltException("This object has already been built");
}
/**
* Gets the object that was built. If it has not been built yet an Exception is
* thrown.
|
* @return the Object that was built
*/
public final O getObject() {
if (!this.building.get()) {
throw new IllegalStateException("This object has not been built");
}
return this.object;
}
/**
* Subclasses should implement this to perform the build.
* @return the object that should be returned by {@link SecurityBuilder#build()}.
* @throws Exception if an error occurs
*/
protected abstract O doBuild();
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\AbstractSecurityBuilder.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String generateFileName(Message<?> message) {
return (String) message.getHeaders().get("filename");
}
});
return handler;
}
/**
* <ul>
* <li>ls (list files)
* <li> nlst (list file names)
* <li> get (retrieve a file)
* <li> mget (retrieve multiple files)
* <li> rm (remove file(s))
* <li> mv (move and rename file)
* <li> put (send a file)
* <li> mput (send multiple files)
* </ul>
*
* @author :qiushicai
* @date :Created in 2020/11/20
* @description: outbound gateway API
* @version:
*/
@MessagingGateway
public interface SftpGateway {
//ls (list files)
@Gateway(requestChannel = "lsChannel")
List<FileInfo> listFile(String dir);
@Gateway(requestChannel = "nlstChannel")
String nlstFile(String dir);
@Gateway(requestChannel = "getChannel")
|
File getFile(String dir);
@Gateway(requestChannel = "mgetChannel")
List<File> mgetFile(String dir);
@Gateway(replyChannel = "rmChannel")
boolean rmFile(String file);
@Gateway(replyChannel = "mvChannel")
boolean mv(String sourceFile, String targetFile);
@Gateway(requestChannel = "putChannel")
File putFile(String dir);
@Gateway(requestChannel = "mputChannel")
List<File> mputFile(String dir);
@Gateway(requestChannel = "uploadChannel")
void upload(File file);
@Gateway(requestChannel = "uploadByteChannel")
void upload(byte[] inputStream, String name);
@Gateway(requestChannel = "toPathChannel")
void upload(@Payload byte[] file, @Header("filename") String filename, @Header("path") String path);
@Gateway(requestChannel = "downloadChannel")
List<File> downloadFiles(String dir);
}
}
|
repos\springboot-demo-master\sftp\src\main\java\com\et\sftp\config\SftpConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private List<I_C_Project_Repair_CostCollector> retrieveRecordsByQuotationLineId(final OrderAndLineId quotationLineId)
{
return queryBL.createQueryBuilder(I_C_Project_Repair_CostCollector.class)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_Quotation_Order_ID, quotationLineId.getOrderId())
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_Quotation_OrderLine_ID, quotationLineId.getOrderLineId())
.create()
.list();
}
public List<ServiceRepairProjectCostCollector> getByQuotationLineIds(final Set<OrderAndLineId> quotationLineIds)
{
if (quotationLineIds.isEmpty())
{
return ImmutableList.of();
}
return queryBL.createQueryBuilder(I_C_Project_Repair_CostCollector.class)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_Quotation_OrderLine_ID, OrderAndLineId.getOrderLineIds(quotationLineIds))
.create()
.stream()
.map(ServiceRepairProjectCostCollectorRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
}
public Set<PPOrderAndCostCollectorId> retainExistingPPCostCollectorIds(
@NonNull final ProjectId projectId,
@NonNull final Set<PPOrderAndCostCollectorId> orderAndCostCollectorIds)
{
if (orderAndCostCollectorIds.isEmpty())
{
return ImmutableSet.of();
}
final Set<PPCostCollectorId> costCollectorIds = orderAndCostCollectorIds.stream().map(PPOrderAndCostCollectorId::getCostCollectorId).collect(Collectors.toSet());
return queryBL.createQueryBuilder(I_C_Project_Repair_CostCollector.class)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_C_Project_ID, projectId)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_From_Repair_Cost_Collector_ID, costCollectorIds)
.create()
.stream()
.map(record -> PPOrderAndCostCollectorId.ofRepoId(record.getFrom_Rapair_Order_ID(), record.getFrom_Repair_Cost_Collector_ID()))
|
.collect(ImmutableSet.toImmutableSet());
}
public boolean matchesByTaskAndProduct(
@NonNull final ServiceRepairProjectTaskId taskId,
@NonNull final ProductId productId)
{
return queryBL.createQueryBuilder(I_C_Project_Repair_CostCollector.class)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_C_Project_ID, taskId.getProjectId())
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_C_Project_Repair_Task_ID, taskId)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_M_Product_ID, productId)
.create()
.anyMatch();
}
public void deleteByIds(@NonNull final Collection<ServiceRepairProjectCostCollectorId> ids)
{
if (ids.isEmpty())
{
return;
}
queryBL.createQueryBuilder(I_C_Project_Repair_CostCollector.class)
.addInArrayFilter(I_C_Project_Repair_CostCollector.COLUMNNAME_C_Project_Repair_CostCollector_ID, ids)
.create()
.delete();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\repository\ServiceRepairProjectCostCollectorRepository.java
| 2
|
请完成以下Java代码
|
public void setExchangeRejectedHandler(ServerExchangeRejectedHandler exchangeRejectedHandler) {
this.exchangeRejectedHandler = exchangeRejectedHandler;
}
/**
* Used to decorate the original {@link WebFilterChain} for each request
*
* <p>
* By default, this decorates the filter chain with a {@link DefaultWebFilterChain}
* that iterates through security filters and then delegates to the original chain
* @param filterChainDecorator the strategy for constructing the filter chain
* @since 6.0
*/
public void setFilterChainDecorator(WebFilterChainDecorator filterChainDecorator) {
Assert.notNull(filterChainDecorator, "filterChainDecorator cannot be null");
this.filterChainDecorator = filterChainDecorator;
}
/**
* A strategy for decorating the provided filter chain with one that accounts for the
* {@link SecurityFilterChain} for a given request.
*
* @author Josh Cummings
* @since 6.0
*/
public interface WebFilterChainDecorator {
/**
* Provide a new {@link WebFilterChain} that accounts for needed security
* considerations when there are no security filters.
* @param original the original {@link WebFilterChain}
* @return a security-enabled {@link WebFilterChain}
*/
default WebFilterChain decorate(WebFilterChain original) {
return decorate(original, Collections.emptyList());
}
/**
* Provide a new {@link WebFilterChain} that accounts for the provided filters as
* well as the original filter chain.
* @param original the original {@link WebFilterChain}
* @param filters the security filters
* @return a security-enabled {@link WebFilterChain} that includes the provided
* filters
*/
|
WebFilterChain decorate(WebFilterChain original, List<WebFilter> filters);
}
/**
* A {@link WebFilterChainDecorator} that uses the {@link DefaultWebFilterChain}
*
* @author Josh Cummings
* @since 6.0
*/
public static class DefaultWebFilterChainDecorator implements WebFilterChainDecorator {
/**
* {@inheritDoc}
*/
@Override
public WebFilterChain decorate(WebFilterChain original) {
return original;
}
/**
* {@inheritDoc}
*/
@Override
public WebFilterChain decorate(WebFilterChain original, List<WebFilter> filters) {
return new DefaultWebFilterChain(original::filter, filters);
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\WebFilterChainProxy.java
| 1
|
请完成以下Java代码
|
public class TaskCompletedEventHandler extends AbstractTaskEventHandler {
@Override
public EventLogEntryEntity generateEventLogEntry(CommandContext commandContext) {
ActivitiEntityEvent activitiEntityEvent = (ActivitiEntityEvent) event;
TaskEntity task = (TaskEntity) activitiEntityEvent.getEntity();
Map<String, Object> data = handleCommonTaskFields(task);
long duration = timeStamp.getTime() - task.getCreateTime().getTime();
putInMapIfNotNull(data, Fields.DURATION, duration);
if (event instanceof ActivitiEntityWithVariablesEvent) {
ActivitiEntityWithVariablesEvent activitiEntityWithVariablesEvent =
(ActivitiEntityWithVariablesEvent) event;
if (
activitiEntityWithVariablesEvent.getVariables() != null &&
!activitiEntityWithVariablesEvent.getVariables().isEmpty()
) {
Map<String, Object> variableMap = new HashMap<String, Object>();
for (Object variableName : activitiEntityWithVariablesEvent.getVariables().keySet()) {
putInMapIfNotNull(
|
variableMap,
(String) variableName,
activitiEntityWithVariablesEvent.getVariables().get(variableName)
);
}
if (activitiEntityWithVariablesEvent.isLocalScope()) {
putInMapIfNotNull(data, Fields.LOCAL_VARIABLES, variableMap);
} else {
putInMapIfNotNull(data, Fields.VARIABLES, variableMap);
}
}
}
return createEventLogEntry(
task.getProcessDefinitionId(),
task.getProcessInstanceId(),
task.getExecutionId(),
task.getId(),
data
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\event\logger\handler\TaskCompletedEventHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringBootMvcFnApplication {
private static final Logger LOG = LoggerFactory.getLogger(SpringBootMvcFnApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringBootMvcFnApplication.class, args);
}
@Bean
RouterFunction<ServerResponse> productListing(ProductController pc, ProductService ps) {
return pc.productListing(ps);
}
@Bean
RouterFunction<ServerResponse> allApplicationRoutes(ProductController pc, ProductService ps) {
return route().add(pc.remainingProductRoutes(ps))
.before(req -> {
LOG.info("Found a route which matches " + req.uri()
.getPath());
return req;
})
.after((req, res) -> {
if (res.statusCode() == HttpStatus.OK) {
LOG.info("Finished processing request " + req.uri()
.getPath());
} else {
LOG.info("There was an error while processing request" + req.uri());
}
return res;
})
.onError(Throwable.class, (e, res) -> {
LOG.error("Fatal exception has occurred", e);
|
return status(HttpStatus.INTERNAL_SERVER_ERROR).build();
})
.build()
.and(route(RequestPredicates.all(), req -> notFound().build()));
}
public static class Error {
private String errorMessage;
public Error(String message) {
this.errorMessage = message;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\springbootmvc\SpringBootMvcFnApplication.java
| 2
|
请完成以下Java代码
|
public int getResourceType() {
return resourceType;
}
public void setResourceType(int type) {
this.resourceType = type;
}
public Integer getResource() {
return resourceType;
}
public void setResource(Resource resource) {
this.resourceType = resource.resourceType();
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public void setPermissions(int permissions) {
this.permissions = permissions;
}
public int getPermissions() {
return permissions;
}
public Set<Permission> getCachedPermissions() {
return cachedPermissions;
}
public int getRevisionNext() {
return revision + 1;
}
public Object getPersistentState() {
HashMap<String, Object> state = new HashMap<String, Object>();
state.put("userId", userId);
state.put("groupId", groupId);
state.put("resourceType", resourceType);
state.put("resourceId", resourceId);
state.put("permissions", permissions);
state.put("removalTime", removalTime);
state.put("rootProcessInstanceId", rootProcessInstanceId);
return state;
}
|
@Override
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
@Override
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
return referenceIdAndClass;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", authorizationType=" + authorizationType
+ ", permissions=" + permissions
+ ", userId=" + userId
+ ", groupId=" + groupId
+ ", resourceType=" + resourceType
+ ", resourceId=" + resourceId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AuthorizationEntity.java
| 1
|
请完成以下Java代码
|
public Optional<Customer> findCustomerByTenantIdAndTitle(UUID tenantId, String title) {
return Optional.ofNullable(DaoUtil.getData(customerRepository.findByTenantIdAndTitle(tenantId, title)));
}
@Override
public Optional<Customer> findPublicCustomerByTenantId(UUID tenantId) {
return Optional.ofNullable(DaoUtil.getData(customerRepository.findPublicCustomerByTenantId(tenantId)));
}
@Override
public Long countByTenantId(TenantId tenantId) {
return customerRepository.countByTenantId(tenantId.getId());
}
@Override
public Customer findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(customerRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public Customer findByTenantIdAndName(UUID tenantId, String name) {
return findCustomerByTenantIdAndTitle(tenantId, name).orElse(null);
}
@Override
public PageData<Customer> findByTenantId(UUID tenantId, PageLink pageLink) {
return findCustomersByTenantId(tenantId, pageLink);
}
@Override
public CustomerId getExternalIdByInternal(CustomerId internalId) {
return Optional.ofNullable(customerRepository.getExternalIdById(internalId.getId()))
.map(CustomerId::new).orElse(null);
}
@Override
public PageData<Customer> findCustomersWithTheSameTitle(PageLink pageLink) {
return DaoUtil.toPageData(
customerRepository.findCustomersWithTheSameTitle(DaoUtil.toPageable(pageLink))
);
}
@Override
public List<Customer> findCustomersByTenantIdAndIds(UUID tenantId, List<UUID> customerIds) {
|
return DaoUtil.convertDataList(customerRepository.findCustomersByTenantIdAndIdIn(tenantId, customerIds));
}
@Override
public PageData<Customer> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<CustomerFields> findNextBatch(UUID id, int batchSize) {
return customerRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) {
return customerRepository.findEntityInfosByNamePrefix(tenantId.getId(), name);
}
@Override
public EntityType getEntityType() {
return EntityType.CUSTOMER;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\customer\JpaCustomerDao.java
| 1
|
请完成以下Java代码
|
public class DisableSchedulerForExternalSystem extends JavaProcess implements IProcessPrecondition
{
private final ExternalSystemConfigRepo externalSystemConfigRepo = SpringContextHolder.instance.getBean(ExternalSystemConfigRepo.class);
private final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
else if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
else
{
final String externalSystemType = externalSystemConfigRepo.getParentTypeById(ExternalSystemParentConfigId.ofRepoId(context.getSingleSelectedRecordId()));
final ExternalSystemType type = ExternalSystemType.ofValue(externalSystemType);
final ExternalSystemConfigQuery query = ExternalSystemConfigQuery.builder()
.parentConfigId(ExternalSystemParentConfigId.ofRepoId(context.getSingleSelectedRecordId()))
.build();
final Optional<ExternalSystemParentConfig> config = externalSystemConfigRepo.getByQuery(type, query);
if (!config.isPresent())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_ERR_NO_EXTERNAL_SELECTION, type.getValue()));
|
}
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final SchedulerEventBusService schedulerEventBusService = SpringContextHolder.instance.getBean(SchedulerEventBusService.class);
final String externalSystemType = externalSystemConfigRepo.getParentTypeById(ExternalSystemParentConfigId.ofRepoId(getRecord_ID()));
final ExternalSystemType type = ExternalSystemType.ofValue(externalSystemType);
final AdProcessId targetProcessId = adProcessDAO.retrieveProcessIdByClassIfUnique(ExternalSystemProcesses.getExternalSystemProcessClassName(type));
Check.assumeNotNull(targetProcessId, "There should always be an AD_Process record for classname:" + ExternalSystemProcesses.getExternalSystemProcessClassName(type));
schedulerEventBusService.postRequest(ManageSchedulerRequest.builder()
.schedulerSearchKey(SchedulerSearchKey.of(targetProcessId))
.clientId(Env.getClientId())
.schedulerAction(SchedulerAction.DISABLE)
.supervisorAction(ManageSchedulerRequest.SupervisorAction.DISABLE)
.build());
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\DisableSchedulerForExternalSystem.java
| 1
|
请完成以下Java代码
|
public class FormPropertyAdapter implements FormField {
protected FormProperty formProperty;
protected List<FormFieldValidationConstraint> validationConstraints;
public FormPropertyAdapter(FormProperty formProperty) {
super();
this.formProperty = formProperty;
validationConstraints = new ArrayList<FormFieldValidationConstraint>();
if(formProperty.isRequired()) {
validationConstraints.add(new FormFieldValidationConstraintImpl(HtmlFormEngine.CONSTRAINT_REQUIRED, null));
}
if(!formProperty.isWritable()) {
validationConstraints.add(new FormFieldValidationConstraintImpl(HtmlFormEngine.CONSTRAINT_READONLY, null));
}
}
public String getId() {
return formProperty.getId();
}
public String getLabel() {
return formProperty.getName();
}
public FormType getType() {
return formProperty.getType();
}
|
public String getTypeName() {
return formProperty.getType().getName();
}
public Object getDefaultValue() {
return formProperty.getValue();
}
public List<FormFieldValidationConstraint> getValidationConstraints() {
return validationConstraints;
}
public Map<String, String> getProperties() {
return Collections.emptyMap();
}
@Override
public boolean isBusinessKey() {
return false;
}
public TypedValue getDefaultValueTyped() {
return getValue();
}
public TypedValue getValue() {
return Variables.stringValue(formProperty.getValue());
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\FormPropertyAdapter.java
| 1
|
请完成以下Java代码
|
public class CamundaFormDefinitionDeployer extends AbstractDefinitionDeployer<CamundaFormDefinitionEntity> {
protected static final EngineUtilLogger LOG = ProcessEngineLogger.UTIL_LOGGER;
public static final String[] FORM_RESOURCE_SUFFIXES = new String[] { "form" };
@Override
protected String[] getResourcesSuffixes() {
return FORM_RESOURCE_SUFFIXES;
}
@Override
protected List<CamundaFormDefinitionEntity> transformDefinitions(DeploymentEntity deployment, ResourceEntity resource,
Properties properties) {
String formContent = new String(resource.getBytes(), StandardCharsets.UTF_8);
try {
JsonObject formJsonObject = new Gson().fromJson(formContent, JsonObject.class);
String camundaFormDefinitionKey = JsonUtil.getString(formJsonObject, "id");
CamundaFormDefinitionEntity definition = new CamundaFormDefinitionEntity(camundaFormDefinitionKey, deployment.getId(), resource.getName(), deployment.getTenantId());
return Collections.singletonList(definition);
} catch (Exception e) {
// form could not be parsed, throw exception if strict parsing is not disabled
if (!getCommandContext().getProcessEngineConfiguration().isDisableStrictCamundaFormParsing()) {
throw LOG.exceptionDuringFormParsing(e.getMessage(), resource.getName());
}
return Collections.emptyList();
}
}
@Override
protected CamundaFormDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) {
return getCommandContext().getCamundaFormDefinitionManager().findDefinitionByDeploymentAndKey(deploymentId,
definitionKey);
}
|
@Override
protected CamundaFormDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) {
return getCommandContext().getCamundaFormDefinitionManager().findLatestDefinitionByKeyAndTenantId(definitionKey,
tenantId);
}
@Override
protected void persistDefinition(CamundaFormDefinitionEntity definition) {
getCommandContext().getCamundaFormDefinitionManager().insert(definition);
}
@Override
protected void addDefinitionToDeploymentCache(DeploymentCache deploymentCache,
CamundaFormDefinitionEntity definition) {
deploymentCache.addCamundaFormDefinition(definition);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\deployer\CamundaFormDefinitionDeployer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SettTask {
private static final Log LOG = LogFactory.getLog(SettTask.class);
private static final long MILLIS = 1000L;
@Autowired
private SettScheduled settScheduled;
@PostConstruct
public void runTask() {
try {
LOG.debug("执行(每日待结算数据汇总)任务开始");
settScheduled.launchDailySettCollect();
LOG.debug("执行(每日待结算数据汇总)任务结束");
Thread.sleep(MILLIS);
|
LOG.debug("执行(定期自动结算)任务开始");
settScheduled.launchAutoSett();
LOG.debug("执行(定期自动结算)任务结束");
} catch (Exception e) {
LOG.error("SettTask execute error:", e);
} finally {
try {
AppSettlementApplication.context.close();
} catch (Exception e) {
LOG.error(e);
}
// System.exit(0);
LOG.debug("SettTask Complete");
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-app-settlement\src\main\java\com\roncoo\pay\app\settlement\SettTask.java
| 2
|
请完成以下Java代码
|
private void removeAll(String name) {
for (SourceDirectory sourceDirectory : this.sourceDirectories.values()) {
sourceDirectory.remove(name);
}
this.filesByName.remove(name);
}
/**
* Get or create a {@link SourceDirectory} with the given name.
* @param name the name of the directory
* @return an existing or newly added {@link SourceDirectory}
*/
protected final SourceDirectory getOrCreateSourceDirectory(String name) {
return this.sourceDirectories.computeIfAbsent(name, (key) -> new SourceDirectory(name));
}
/**
* Return all {@link SourceDirectory SourceDirectories} that have been added to the
* collection.
* @return a collection of {@link SourceDirectory} items
*/
public Collection<SourceDirectory> getSourceDirectories() {
return Collections.unmodifiableCollection(this.sourceDirectories.values());
}
/**
* Return the size of the collection.
* @return the size of the collection
*/
public int size() {
return this.filesByName.size();
}
@Override
public @Nullable ClassLoaderFile getFile(@Nullable String name) {
return this.filesByName.get(name);
}
/**
* Returns a set of all file entries across all source directories for efficient
* iteration.
* @return a set of all file entries
* @since 4.0.0
*/
public Set<Entry<String, ClassLoaderFile>> getFileEntries() {
return Collections.unmodifiableSet(this.filesByName.entrySet());
}
/**
* An individual source directory that is being managed by the collection.
*/
public static class SourceDirectory implements Serializable {
@Serial
private static final long serialVersionUID = 1;
private final String name;
private final Map<String, ClassLoaderFile> files = new LinkedHashMap<>();
SourceDirectory(String name) {
this.name = name;
}
public Set<Entry<String, ClassLoaderFile>> getFilesEntrySet() {
return this.files.entrySet();
|
}
protected final void add(String name, ClassLoaderFile file) {
this.files.put(name, file);
}
protected final void remove(String name) {
this.files.remove(name);
}
protected final @Nullable ClassLoaderFile get(String name) {
return this.files.get(name);
}
/**
* Return the name of the source directory.
* @return the name of the source directory
*/
public String getName() {
return this.name;
}
/**
* Return all {@link ClassLoaderFile ClassLoaderFiles} in the collection that are
* contained in this source directory.
* @return the files contained in the source directory
*/
public Collection<ClassLoaderFile> getFiles() {
return Collections.unmodifiableCollection(this.files.values());
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\classloader\ClassLoaderFiles.java
| 1
|
请完成以下Java代码
|
public void setUserInfo(String userId, String key, String value) {
commandExecutor.execute(new SetUserInfoCmd(userId, key, value));
}
public void deleteUserInfo(String userId, String key) {
commandExecutor.execute(new DeleteUserInfoCmd(userId, key));
}
public void deleteUserAccount(String userId, String accountName) {
commandExecutor.execute(new DeleteUserInfoCmd(userId, accountName));
}
public Account getUserAccount(String userId, String userPassword, String accountName) {
return commandExecutor.execute(new GetUserAccountCmd(userId, userPassword, accountName));
}
public void setUserAccount(String userId, String userPassword, String accountName, String accountUsername, String accountPassword, Map<String, String> accountDetails) {
commandExecutor.execute(new SetUserInfoCmd(userId, userPassword, accountName, accountUsername, accountPassword, accountDetails));
}
|
public void createTenantUserMembership(String tenantId, String userId) {
commandExecutor.execute(new CreateTenantUserMembershipCmd(tenantId, userId));
}
public void createTenantGroupMembership(String tenantId, String groupId) {
commandExecutor.execute(new CreateTenantGroupMembershipCmd(tenantId, groupId));
}
public void deleteTenantUserMembership(String tenantId, String userId) {
commandExecutor.execute(new DeleteTenantUserMembershipCmd(tenantId, userId));
}
public void deleteTenantGroupMembership(String tenantId, String groupId) {
commandExecutor.execute(new DeleteTenantGroupMembershipCmd(tenantId, groupId));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\IdentityServiceImpl.java
| 1
|
请完成以下Java代码
|
public void setDateInvoiced(final LocalDate dateInvoiced)
{
this.dateInvoiced = dateInvoiced;
dateInvoicedSet = true;
}
@Nullable
@Override
public LocalDate getDateAcct()
{
if (dateAcctSet)
{
return dateAcct;
}
else if (defaults != null)
{
return defaults.getDateAcct();
}
else
{
return null;
}
}
public void setDateAcct(final LocalDate dateAcct)
{
this.dateAcct = dateAcct;
dateAcctSet = true;
}
@Nullable
@Override
public String getPOReference()
{
if (poReferenceSet)
{
return poReference;
}
else if (defaults != null)
{
return defaults.getPOReference();
}
else
{
return null;
}
}
public void setPOReference(@Nullable final String poReference)
{
this.poReference = poReference;
poReferenceSet = true;
}
@Nullable
@Override
public BigDecimal getCheck_NetAmtToInvoice()
{
if (check_NetAmtToInvoice != null)
{
return check_NetAmtToInvoice;
}
else if (defaults != null)
{
return defaults.getCheck_NetAmtToInvoice();
}
return null;
}
@Override
public boolean isStoreInvoicesInResult()
{
if (storeInvoicesInResult != null)
{
|
return storeInvoicesInResult;
}
else if (defaults != null)
{
return defaults.isStoreInvoicesInResult();
}
else
{
return false;
}
}
public PlainInvoicingParams setStoreInvoicesInResult(final boolean storeInvoicesInResult)
{
this.storeInvoicesInResult = storeInvoicesInResult;
return this;
}
@Override
public boolean isAssumeOneInvoice()
{
if (assumeOneInvoice != null)
{
return assumeOneInvoice;
}
else if (defaults != null)
{
return defaults.isAssumeOneInvoice();
}
else
{
return false;
}
}
public PlainInvoicingParams setAssumeOneInvoice(final boolean assumeOneInvoice)
{
this.assumeOneInvoice = assumeOneInvoice;
return this;
}
public boolean isUpdateLocationAndContactForInvoice()
{
return updateLocationAndContactForInvoice;
}
public void setUpdateLocationAndContactForInvoice(boolean updateLocationAndContactForInvoice)
{
this.updateLocationAndContactForInvoice = updateLocationAndContactForInvoice;
}
public PlainInvoicingParams setCompleteInvoices(final boolean completeInvoices)
{
this.completeInvoices = completeInvoices;
return this;
}
@Override
public boolean isCompleteInvoices()
{
return completeInvoices;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\PlainInvoicingParams.java
| 1
|
请完成以下Java代码
|
private void produce() {
while (true) {
double value = generateValue();
try {
blockingQueue.put(value);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
log.info(String.format("[%s] Value produced: %f%n", Thread.currentThread().getName(), value));
}
}
private void consume() {
while (true) {
Double value;
try {
value = blockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
// Consume value
log.info(String.format("[%s] Value consumed: %f%n", Thread.currentThread().getName(), value));
}
}
|
private double generateValue() {
return Math.random();
}
private void runProducerConsumer() {
for (int i = 0; i < 2; i++) {
Thread producerThread = new Thread(this::produce);
producerThread.start();
}
for (int i = 0; i < 3; i++) {
Thread consumerThread = new Thread(this::consume);
consumerThread.start();
}
}
public static void main(String[] args) {
SimpleProducerConsumerDemonstrator simpleProducerConsumerDemonstrator = new SimpleProducerConsumerDemonstrator();
simpleProducerConsumerDemonstrator.runProducerConsumer();
sleep(2000);
System.exit(0);
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\producerconsumer\SimpleProducerConsumerDemonstrator.java
| 1
|
请完成以下Java代码
|
public class Mem {
/**
* 内存总量
*/
private double total;
/**
* 已用内存
*/
private double used;
/**
* 剩余内存
*/
private double free;
public double getTotal() {
return NumberUtil.div(total, (1024 * 1024 * 1024), 2);
}
public void setTotal(long total) {
this.total = total;
}
public double getUsed() {
return NumberUtil.div(used, (1024 * 1024 * 1024), 2);
}
|
public void setUsed(long used) {
this.used = used;
}
public double getFree() {
return NumberUtil.div(free, (1024 * 1024 * 1024), 2);
}
public void setFree(long free) {
this.free = free;
}
public double getUsage() {
return NumberUtil.mul(NumberUtil.div(used, total, 4), 100);
}
}
|
repos\spring-boot-demo-master\demo-websocket\src\main\java\com\xkcoding\websocket\model\server\Mem.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected AttachmentResponse createSimpleAttachment(AttachmentRequest attachmentRequest, Task task) {
if (attachmentRequest.getName() == null) {
throw new FlowableIllegalArgumentException("Attachment name is required.");
}
Attachment createdAttachment = taskService.createAttachment(attachmentRequest.getType(), task.getId(), task.getProcessInstanceId(), attachmentRequest.getName(),
attachmentRequest.getDescription(), attachmentRequest.getExternalUrl());
return restResponseFactory.createAttachmentResponse(createdAttachment);
}
protected AttachmentResponse createBinaryAttachment(MultipartHttpServletRequest request, Task task) {
String name = null;
String description = null;
String type = null;
Map<String, String[]> paramMap = request.getParameterMap();
for (String parameterName : paramMap.keySet()) {
if (paramMap.get(parameterName).length > 0) {
if ("name".equalsIgnoreCase(parameterName)) {
name = paramMap.get(parameterName)[0];
} else if ("description".equalsIgnoreCase(parameterName)) {
description = paramMap.get(parameterName)[0];
} else if ("type".equalsIgnoreCase(parameterName)) {
type = paramMap.get(parameterName)[0];
}
}
}
if (name == null) {
throw new FlowableIllegalArgumentException("Attachment name is required.");
}
|
if (request.getFileMap().size() == 0) {
throw new FlowableIllegalArgumentException("Attachment content is required.");
}
MultipartFile file = request.getFileMap().values().iterator().next();
if (file == null) {
throw new FlowableIllegalArgumentException("Attachment content is required.");
}
try {
Attachment createdAttachment = taskService.createAttachment(type, task.getId(), task.getProcessInstanceId(), name, description, file.getInputStream());
return restResponseFactory.createAttachmentResponse(createdAttachment);
} catch (Exception e) {
throw new FlowableException("Error creating attachment response", e);
}
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskAttachmentCollectionResource.java
| 2
|
请完成以下Java代码
|
private static void validateCreateSyncAdvise(
@NonNull final Object parentResource,
@NonNull final ExternalIdentifier externalIdentifier,
@NonNull final SyncAdvise effectiveSyncAdvise)
{
if (effectiveSyncAdvise.isFailIfNotExists())
{
throw MissingResourceException.builder()
.resourceName("Warehouse")
.resourceIdentifier(externalIdentifier.getRawValue())
.parentResource(parentResource)
.build()
.setParameter("effectiveSyncAdvise", effectiveSyncAdvise);
}
else if (ExternalIdentifier.Type.METASFRESH_ID.equals(externalIdentifier.getType()))
{
throw MissingResourceException.builder()
.resourceName("Warehouse")
.resourceIdentifier(externalIdentifier.getRawValue())
.parentResource(parentResource)
.detail(TranslatableStrings.constant("With this type, only updates are allowed."))
.build()
.setParameter("effectiveSyncAdvise", effectiveSyncAdvise);
}
}
@NonNull
|
public JsonLocator resolveLocatorScannedCode(@NonNull final ScannedCode scannedCode)
{
final LocatorScannedCodeResolverResult result = locatorScannedCodeResolver.resolve(scannedCode);
return toJsonLocator(result.getLocatorQRCode());
}
private static JsonLocator toJsonLocator(final LocatorQRCode locatorQRCode)
{
return JsonLocator.builder()
.caption(locatorQRCode.getCaption())
.qrCode(locatorQRCode.toGlobalQRCodeJsonString())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\warehouse\WarehouseRestService.java
| 1
|
请完成以下Java代码
|
public Clock getClock() {
return clock;
}
public ProcessEngineConfiguration setClock(Clock clock) {
this.clock = clock;
return this;
}
public AsyncExecutor getAsyncExecutor() {
return asyncExecutor;
}
public ProcessEngineConfiguration setAsyncExecutor(AsyncExecutor asyncExecutor) {
this.asyncExecutor = asyncExecutor;
return this;
}
public int getLockTimeAsyncJobWaitTime() {
return lockTimeAsyncJobWaitTime;
}
public ProcessEngineConfiguration setLockTimeAsyncJobWaitTime(int lockTimeAsyncJobWaitTime) {
this.lockTimeAsyncJobWaitTime = lockTimeAsyncJobWaitTime;
return this;
}
public int getDefaultFailedJobWaitTime() {
return defaultFailedJobWaitTime;
}
public ProcessEngineConfiguration setDefaultFailedJobWaitTime(int defaultFailedJobWaitTime) {
this.defaultFailedJobWaitTime = defaultFailedJobWaitTime;
return this;
}
public int getAsyncFailedJobWaitTime() {
return asyncFailedJobWaitTime;
}
public ProcessEngineConfiguration setAsyncFailedJobWaitTime(int asyncFailedJobWaitTime) {
this.asyncFailedJobWaitTime = asyncFailedJobWaitTime;
|
return this;
}
public boolean isEnableProcessDefinitionInfoCache() {
return enableProcessDefinitionInfoCache;
}
public ProcessEngineConfiguration setEnableProcessDefinitionInfoCache(boolean enableProcessDefinitionInfoCache) {
this.enableProcessDefinitionInfoCache = enableProcessDefinitionInfoCache;
return this;
}
public ProcessEngineConfiguration setCopyVariablesToLocalForTasks(boolean copyVariablesToLocalForTasks) {
this.copyVariablesToLocalForTasks = copyVariablesToLocalForTasks;
return this;
}
public boolean isCopyVariablesToLocalForTasks() {
return copyVariablesToLocalForTasks;
}
public void setEngineAgendaFactory(ActivitiEngineAgendaFactory engineAgendaFactory) {
this.engineAgendaFactory = engineAgendaFactory;
}
public ActivitiEngineAgendaFactory getEngineAgendaFactory() {
return engineAgendaFactory;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ProcessEngineConfiguration.java
| 1
|
请完成以下Java代码
|
protected boolean doProcessCfMsg(ToCalculatedFieldSystemMsg msg) throws CalculatedFieldException {
switch (msg.getMsgType()) {
case CF_PARTITIONS_CHANGE_MSG:
processor.onPartitionChange((CalculatedFieldPartitionChangeMsg) msg);
break;
case CF_CACHE_INIT_MSG:
processor.onCacheInitMsg((CalculatedFieldCacheInitMsg) msg);
break;
case CF_STATE_RESTORE_MSG:
processor.onStateRestoreMsg((CalculatedFieldStateRestoreMsg) msg);
break;
case CF_STATE_PARTITION_RESTORE_MSG:
processor.onStatePartitionRestoreMsg((CalculatedFieldStatePartitionRestoreMsg) msg);
break;
case CF_ENTITY_LIFECYCLE_MSG:
processor.onEntityLifecycleMsg((CalculatedFieldEntityLifecycleMsg) msg);
break;
case CF_ENTITY_ACTION_EVENT_MSG:
processor.onEntityActionEventMsg((CalculatedFieldEntityActionEventMsg) msg);
break;
case CF_TELEMETRY_MSG:
processor.onTelemetryMsg((CalculatedFieldTelemetryMsg) msg);
|
break;
case CF_LINKED_TELEMETRY_MSG:
processor.onLinkedTelemetryMsg((CalculatedFieldLinkedTelemetryMsg) msg);
break;
default:
return false;
}
return true;
}
@Override
void logProcessingException(Exception e) {
log.warn("[{}] Processing failure", tenantId, e);
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\calculatedField\CalculatedFieldManagerActor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/getUsers")
public List<UserEntity> getUsers() {
List<UserEntity> users=userMapper.getAll();
return users;
}
@RequestMapping("/getList")
public Page<UserEntity> getList(UserParam userParam) {
List<UserEntity> users=userMapper.getList(userParam);
long count=userMapper.getCount(userParam);
Page page = new Page(userParam,count,users);
return page;
}
@RequestMapping("/getUser")
public UserEntity getUser(Long id) {
UserEntity user=userMapper.getOne(id);
return user;
}
|
@RequestMapping("/add")
public void save(UserEntity user) {
userMapper.insert(user);
}
@RequestMapping(value="update")
public void update(UserEntity user) {
userMapper.update(user);
}
@RequestMapping(value="/delete/{id}")
public void delete(@PathVariable("id") Long id) {
userMapper.delete(id);
}
}
|
repos\spring-boot-leaning-master\1.x\第07课:Spring Boot 集成 MyBatis\spring-boot-mybatis-annotation\src\main\java\com\neo\web\UserController.java
| 2
|
请完成以下Java代码
|
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaVariableOnPart.class, CAMUNDA_ELEMENT_VARIABLE_ON_PART)
.namespaceUri(CAMUNDA_NS)
.instanceProvider(new ModelTypeInstanceProvider<CamundaVariableOnPart>() {
public CamundaVariableOnPart newInstance(ModelTypeInstanceContext instanceContext) {
return new CamundaVariableOnPartImpl(instanceContext);
}
});
camundaVariableNameAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_VARIABLE_NAME)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
camundaVariableEventChild = sequenceBuilder.element(CamundaVariableTransitionEvent.class)
.build();
typeBuilder.build();
}
public String getVariableName() {
|
return camundaVariableNameAttribute.getValue(this);
}
public void setVariableName(String name) {
camundaVariableNameAttribute.setValue(this, name);
}
public VariableTransition getVariableEvent() {
CamundaVariableTransitionEvent child = camundaVariableEventChild.getChild(this);
return child.getValue();
}
public void setVariableEvent(VariableTransition variableTransition) {
CamundaVariableTransitionEvent child = camundaVariableEventChild.getChild(this);
child.setValue(variableTransition);
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\camunda\CamundaVariableOnPartImpl.java
| 1
|
请完成以下Java代码
|
protected Expression getActiveValue(Expression originalValue, String propertyName, ObjectNode taskElementProperties) {
Expression activeValue = originalValue;
if (taskElementProperties != null) {
JsonNode overrideValueNode = taskElementProperties.get(propertyName);
if (overrideValueNode != null) {
if (overrideValueNode.isNull()) {
activeValue = null;
} else {
activeValue = Context.getProcessEngineConfiguration().getExpressionManager().createExpression(overrideValueNode.asString());
}
}
}
return activeValue;
}
protected Set<Expression> getActiveValueSet(Set<Expression> originalValues, String propertyName, ObjectNode taskElementProperties) {
Set<Expression> activeValues = originalValues;
if (taskElementProperties != null) {
JsonNode overrideValuesNode = taskElementProperties.get(propertyName);
if (overrideValuesNode != null) {
if (overrideValuesNode.isNull() || !overrideValuesNode.isArray() || overrideValuesNode.isEmpty()) {
activeValues = null;
} else {
ExpressionManager expressionManager = Context.getProcessEngineConfiguration().getExpressionManager();
activeValues = new HashSet<>();
for (JsonNode valueNode : overrideValuesNode) {
|
activeValues.add(expressionManager.createExpression(valueNode.asString()));
}
}
}
}
return activeValues;
}
// getters and setters //////////////////////////////////////////////////////
public TaskDefinition getTaskDefinition() {
return taskDefinition;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\UserTaskActivityBehavior.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ArticleNumberType {
@XmlValue
protected String content;
@XmlAttribute(name = "ArticleNumberType", namespace = "http://erpel.at/schemas/1p0/documents")
protected ArticleNumberTypeType articleNumberType;
/**
* Gets the value of the content property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContent() {
return content;
}
/**
* Sets the value of the content property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContent(String value) {
this.content = value;
}
/**
|
* Attribute defining the type of article number.
*
* @return
* possible object is
* {@link ArticleNumberTypeType }
*
*/
public ArticleNumberTypeType getArticleNumberType() {
return articleNumberType;
}
/**
* Sets the value of the articleNumberType property.
*
* @param value
* allowed object is
* {@link ArticleNumberTypeType }
*
*/
public void setArticleNumberType(ArticleNumberTypeType value) {
this.articleNumberType = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ArticleNumberType.java
| 2
|
请完成以下Java代码
|
public class JwtResponse {
private String message;
private Status status;
private String exceptionType;
private String jwt;
private Jws<Claims> jws;
public enum Status {
SUCCESS, ERROR
}
public JwtResponse() {
}
public JwtResponse(String jwt) {
this.jwt = jwt;
this.status = Status.SUCCESS;
}
public JwtResponse(Jws<Claims> jws) {
this.jws = jws;
this.status = Status.SUCCESS;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
|
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getExceptionType() {
return exceptionType;
}
public void setExceptionType(String exceptionType) {
this.exceptionType = exceptionType;
}
public String getJwt() {
return jwt;
}
public void setJwt(String jwt) {
this.jwt = jwt;
}
public Jws<Claims> getJws() {
return jws;
}
public void setJws(Jws<Claims> jws) {
this.jws = jws;
}
}
|
repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\model\JwtResponse.java
| 1
|
请完成以下Java代码
|
private I_M_HU getMaturingHU(@NonNull final I_PP_Order ppOrder)
{
final I_PP_Order_Candidate maturingCandidate = getSingleMaturingCandidate(PPOrderId.ofRepoId(ppOrder.getPP_Order_ID()));
final HuId maturingHUId = HuId.ofRepoId(maturingCandidate.getIssue_HU_ID());
final I_M_HU maturingHU = handlingUnitsBL.getById(maturingHUId);
final ProductId maturedProductId = ProductId.ofRepoId(ppOrder.getM_Product_ID());
if (isHUEligibleForMaturing(maturingHU, maturedProductId))
{
throw new AdempiereException("Issue HU is not eligible for maturing !");
}
return maturingHU;
}
private void receiveMaturedHU(
|
@NonNull final I_PP_Order ppOrder,
@NonNull final I_M_HU huToBeIssued)
{
final LocatorId locatorId = LocatorId.ofRepoId(ppOrder.getM_Warehouse_ID(), ppOrder.getM_Locator_ID());
final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
final I_M_HU receivedHu = receivingMainProduct(ppOrderId)
.locatorId(locatorId)
.receiveVHU(Quantitys.of(ppOrder.getQtyOrdered(), UomId.ofRepoId(ppOrder.getC_UOM_ID())));
attributesBL.transferAttributesForSingleProductHUs(huToBeIssued, receivedHu);
attributesBL.updateHUAttribute(HuId.ofRepoId(receivedHu.getM_HU_ID()), AttributeConstants.ProductionDate, SystemTime.asTimestamp());
final HUQRCode huqrCode = huqrCodesService.get().getQRCodeByHuId(HuId.ofRepoId(huToBeIssued.getM_HU_ID()));
huqrCodesService.get().assign(huqrCode, ImmutableSet.of(HuId.ofRepoId(receivedHu.getM_HU_ID())));
processPlanning(PPOrderPlanningStatus.COMPLETE, ppOrderId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\HUPPOrderBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PatientPrimaryDoctorInstitution type(BigDecimal type) {
this.type = type;
return this;
}
/**
* Art der Institution (2 = Pflegeheim/nursingHome, 4 = Klinik/hospital, 7 = Gemeinschaftspraxis)
* @return type
**/
@Schema(example = "4", description = "Art der Institution (2 = Pflegeheim/nursingHome, 4 = Klinik/hospital, 7 = Gemeinschaftspraxis)")
public BigDecimal getType() {
return type;
}
public void setType(BigDecimal type) {
this.type = type;
}
public PatientPrimaryDoctorInstitution description(String description) {
this.description = description;
return this;
}
/**
* Name und Ort der Institution
* @return description
**/
@Schema(example = "Krankenhaus Martha-Maria, 90491 Nürnberg", description = "Name und Ort der Institution")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public PatientPrimaryDoctorInstitution institutionId(String institutionId) {
this.institutionId = institutionId;
return this;
}
/**
* Alberta-Id des Institution (nur bei Pfelgeheim und Klinik)
* @return institutionId
**/
@Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", description = "Alberta-Id des Institution (nur bei Pfelgeheim und Klinik)")
public String getInstitutionId() {
return institutionId;
}
public void setInstitutionId(String institutionId) {
this.institutionId = institutionId;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatientPrimaryDoctorInstitution patientPrimaryDoctorInstitution = (PatientPrimaryDoctorInstitution) o;
return Objects.equals(this.type, patientPrimaryDoctorInstitution.type) &&
|
Objects.equals(this.description, patientPrimaryDoctorInstitution.description) &&
Objects.equals(this.institutionId, patientPrimaryDoctorInstitution.institutionId);
}
@Override
public int hashCode() {
return Objects.hash(type, description, institutionId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PatientPrimaryDoctorInstitution {\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" institutionId: ").append(toIndentedString(institutionId)).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\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientPrimaryDoctorInstitution.java
| 2
|
请完成以下Java代码
|
public static void requiresNew() {
ProcessEngineContextImpl.set(true);
}
/**
* Declares to the Process Engine that the new Context created
* by the {@link #requiresNew()} method can be closed. Please
* see the {@link ProcessEngineContext} class documentation for
* a more detailed description on the purpose of this method.
*/
public static void clear() {
ProcessEngineContextImpl.clear();
}
/**
* <p>Takes a callable and executes all engine API invocations
* within that callable in a new Process Engine Context. Please
* see the {@link ProcessEngineContext} class documentation for
* a more detailed description on the purpose of this method.</p>
*
* An alternative to calling:
*
|
* <code>
* try {
* requiresNew();
* callable.call();
* } finally {
* clear();
* }
* </code>
*
* @param callable the callable to execute
* @return what is defined by the callable passed to the method
* @throws Exception
*/
public static <T> T withNewProcessEngineContext(Callable<T> callable) throws Exception {
try {
requiresNew();
return callable.call();
} finally {
clear();
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\context\ProcessEngineContext.java
| 1
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.getSelectionSize().isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final IQueryFilter<I_EDI_Desadv_Pack> selectedRecordsFilter = getProcessInfo()
.getQueryFilterOrElse(ConstantQueryFilter.of(false));
|
final Set<EDIDesadvPackId> list = queryBL
.createQueryBuilder(I_EDI_Desadv_Pack.class)
.filter(selectedRecordsFilter)
.create()
.stream()
.map(I_EDI_Desadv_Pack::getEDI_Desadv_Pack_ID)
.map(EDIDesadvPackId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
final ReportResultData reportResult = desadvBL.printSSCC18_Labels(getCtx(), list);
getProcessInfo().getResult().setReportData(reportResult);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_Pack_PrintSSCCLabels.java
| 1
|
请完成以下Java代码
|
static PemSslStore of(@Nullable String type, @Nullable String alias, @Nullable String password,
List<X509Certificate> certificates, @Nullable PrivateKey privateKey) {
Assert.notEmpty(certificates, "'certificates' must not be empty");
return new PemSslStore() {
@Override
public @Nullable String type() {
return type;
}
@Override
public @Nullable String alias() {
return alias;
}
@Override
public @Nullable String password() {
return password;
|
}
@Override
public List<X509Certificate> certificates() {
return certificates;
}
@Override
public @Nullable PrivateKey privateKey() {
return privateKey;
}
};
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemSslStore.java
| 1
|
请完成以下Java代码
|
public void setDecimalPoint (java.lang.String DecimalPoint)
{
set_Value (COLUMNNAME_DecimalPoint, DecimalPoint);
}
/** Get Dezimal-Punkt.
@return Decimal Point in the data file - if any
*/
@Override
public java.lang.String getDecimalPoint ()
{
return (java.lang.String)get_Value(COLUMNNAME_DecimalPoint);
}
/** Set Durch 100 teilen.
@param DivideBy100
Divide number by 100 to get correct amount
*/
@Override
public void setDivideBy100 (boolean DivideBy100)
{
set_Value (COLUMNNAME_DivideBy100, Boolean.valueOf(DivideBy100));
}
/** Get Durch 100 teilen.
@return Divide number by 100 to get correct amount
*/
@Override
public boolean isDivideBy100 ()
{
Object oo = get_Value(COLUMNNAME_DivideBy100);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set End-Nr..
@param EndNo End-Nr. */
@Override
public void setEndNo (int EndNo)
{
set_Value (COLUMNNAME_EndNo, Integer.valueOf(EndNo));
}
/** Get End-Nr..
@return End-Nr. */
@Override
public int getEndNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EndNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Skript.
@param Script
Dynamic Java Language Script to calculate result
*/
@Override
public void setScript (java.lang.String Script)
{
set_Value (COLUMNNAME_Script, Script);
}
|
/** Get Skript.
@return Dynamic Java Language Script to calculate result
*/
@Override
public java.lang.String getScript ()
{
return (java.lang.String)get_Value(COLUMNNAME_Script);
}
/** Set Reihenfolge.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start No.
@param StartNo
Starting number/position
*/
@Override
public void setStartNo (int StartNo)
{
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo));
}
/** Get Start No.
@return Starting number/position
*/
@Override
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ImpFormat_Row.java
| 1
|
请完成以下Java代码
|
private static JsonOpts newJsonOpts() {return JsonOpts.ofAdLanguage(Env.getADLanguageOrBaseLanguage());}
@PostMapping("/resolveLocator")
public JsonResolveLocatorResponse resolveLocator(@RequestBody @NonNull final JsonResolveLocatorRequest request)
{
assertApplicationAccess();
final LocatorScannedCodeResolverResult result = jobService.resolveLocator(
request.getScannedCode(),
request.getWfProcessId(),
request.getLineId(),
Env.getLoggedUserId()
);
return JsonResolveLocatorResponse.of(result);
}
@PostMapping("/resolveHU")
public JsonResolveHUResponse resolveHU(@RequestBody @NonNull final JsonResolveHURequest request)
{
assertApplicationAccess();
final ResolveHUResponse response = jobService.resolveHU(
ResolveHURequest.builder()
.scannedCode(request.getScannedCode())
.callerId(Env.getLoggedUserId())
.wfProcessId(request.getWfProcessId())
.lineId(request.getLineId())
.locatorId(request.getLocatorQRCode().getLocatorId())
.build()
);
return mappers.newJsonResolveHUResponse(newJsonOpts()).toJson(response);
}
@PostMapping("/count")
public JsonWFProcess reportCounting(@RequestBody @NonNull final JsonCountRequest request)
{
assertApplicationAccess();
final Inventory inventory = jobService.reportCounting(request, Env.getLoggedUserId());
return toJsonWFProcess(inventory);
}
|
private JsonWFProcess toJsonWFProcess(final Inventory inventory)
{
return workflowRestController.toJson(WFProcessMapper.toWFProcess(inventory));
}
@GetMapping("/lineHU")
public JsonInventoryLineHU getLineHU(
@RequestParam("wfProcessId") @NonNull String wfProcessIdStr,
@RequestParam("lineId") @NonNull String lineIdStr,
@RequestParam("lineHUId") @NonNull String lineHUIdStr)
{
assertApplicationAccess();
final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr);
final InventoryLineId lineId = InventoryLineId.ofObject(lineIdStr);
final InventoryLineHUId lineHUId = InventoryLineHUId.ofObject(lineHUIdStr);
final InventoryLine line = jobService.getById(wfProcessId, Env.getLoggedUserId()).getLineById(lineId);
return mappers.newJsonInventoryJobMapper(newJsonOpts())
.loadAllDetails(true)
.toJson(line, lineHUId);
}
@GetMapping("/lineHUs")
public JsonGetLineHUsResponse getLineHUs(
@RequestParam("wfProcessId") @NonNull String wfProcessIdStr,
@RequestParam("lineId") @NonNull String lineIdStr)
{
assertApplicationAccess();
final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr);
final InventoryLineId lineId = InventoryLineId.ofObject(lineIdStr);
final InventoryLine line = jobService.getById(wfProcessId, Env.getLoggedUserId()).getLineById(lineId);
return JsonGetLineHUsResponse.builder()
.wfProcessId(wfProcessId)
.lineId(lineId)
.lineHUs(mappers.newJsonInventoryJobMapper(newJsonOpts()).toJsonInventoryLineHUs(line))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\InventoryRestController.java
| 1
|
请完成以下Java代码
|
public void delete(JobEntity jobEntity) {
super.delete(jobEntity);
deleteExceptionByteArrayRef(jobEntity);
removeExecutionLink(jobEntity);
// Send event
if (getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, this)
);
}
}
@Override
public void delete(JobEntity entity, boolean fireDeleteEvent) {
if (entity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) {
CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById(
entity.getExecutionId()
);
if (isExecutionRelatedEntityCountEnabled(executionEntity)) {
executionEntity.setJobCount(executionEntity.getJobCount() - 1);
}
}
super.delete(entity, fireDeleteEvent);
}
/**
* Removes the job's execution's reference to this job, if the job has an associated execution.
* Subclasses may override to provide custom implementations.
*/
protected void removeExecutionLink(JobEntity jobEntity) {
|
if (jobEntity.getExecutionId() != null) {
ExecutionEntity execution = getExecutionEntityManager().findById(jobEntity.getExecutionId());
if (execution != null) {
execution.getJobs().remove(jobEntity);
}
}
}
/**
* Deletes a the byte array used to store the exception information. Subclasses may override
* to provide custom implementations.
*/
protected void deleteExceptionByteArrayRef(JobEntity jobEntity) {
ByteArrayRef exceptionByteArrayRef = jobEntity.getExceptionByteArrayRef();
if (exceptionByteArrayRef != null) {
exceptionByteArrayRef.delete();
}
}
public JobDataManager getJobDataManager() {
return jobDataManager;
}
public void setJobDataManager(JobDataManager jobDataManager) {
this.jobDataManager = jobDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\JobEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public static boolean isToday(final Timestamp timestamp)
{
if (timestamp == null)
{
throw new IllegalArgumentException("Param 'timestamp' may not be null");
}
final Calendar calNow = SystemTime.asGregorianCalendar();
final Calendar calTs = new GregorianCalendar();
calTs.setTime(timestamp);
return calNow.get(Calendar.DAY_OF_MONTH) == calTs
.get(Calendar.DAY_OF_MONTH)
&& calNow.get(Calendar.MONTH) == calTs.get(Calendar.MONTH)
&& calNow.get(Calendar.YEAR) == calTs.get(Calendar.YEAR);
}
public static Timestamp toTimeStamp(final String string)
{
try
{
return new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(string).getTime());
}
catch (ParseException e)
{
throwIllegalArgumentEx(string, "string");
return null;
}
}
public static int getCalloutId(final GridTab mTab, final String colName)
{
final Integer id = (Integer)mTab.getValue(colName);
if (id == null || id <= 0)
{
return 0;
}
return id;
}
/**
* For a {@link Timestamp} representing e.g. "17.12.2009 15:14:34" this method returns a timestamp representing
* "17.12.2009 00:00:00".
*
* @param ctx
* @param ts
* @return
*/
public static Timestamp removeTime(final Timestamp ts)
{
final DateFormat fmt = DateFormat.getDateInstance(DateFormat.LONG);
final String strDate = fmt.format(ts);
java.util.Date date;
try
{
date = fmt.parse(strDate);
}
catch (ParseException e)
|
{
throw new AdempiereException(e);
}
final Timestamp currentDate = new Timestamp(date.getTime());
return currentDate;
}
public static GridTab getGridTabForTableAndWindow(final Properties ctx, final int windowNo, final int AD_Window_ID, final int AD_Table_ID, final boolean startWithEmptyQuery)
{
final GridWindowVO wVO = GridWindowVO.create(ctx, windowNo, AdWindowId.ofRepoId(AD_Window_ID));
if (wVO == null)
{
MWindow w = new MWindow(Env.getCtx(), AD_Window_ID, null);
throw new AdempiereException("No access to window - " + w.getName() + " (AD_Window_ID=" + AD_Window_ID + ")");
}
final GridWindow gridWindow = new GridWindow(wVO);
//
GridTab tab = null;
int tabIndex = -1;
for (int i = 0; i < gridWindow.getTabCount(); i++)
{
GridTab t = gridWindow.getTab(i);
if (t.getAD_Table_ID() == AD_Table_ID)
{
tab = t;
tabIndex = i;
break;
}
}
if (tab == null)
{
throw new AdempiereException("No Tab found for AD_Table_ID=" + AD_Table_ID + ", Window:" + gridWindow.getName());
}
gridWindow.initTab(tabIndex);
//
if (startWithEmptyQuery)
{
tab.setQuery(MQuery.getEqualQuery("1", "2"));
tab.query(false);
}
return tab;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\MiscUtils.java
| 1
|
请完成以下Java代码
|
public static String detectDocTypeUsingFacade(InputStream stream) throws IOException {
Tika tika = new Tika();
String mediaType = tika.detect(stream);
return mediaType;
}
public static String extractContentUsingParser(InputStream stream) throws IOException, TikaException, SAXException {
Parser parser = new AutoDetectParser();
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
ParseContext context = new ParseContext();
parser.parse(stream, handler, metadata, context);
return handler.toString();
}
public static String extractContentUsingFacade(InputStream stream) throws IOException, TikaException {
Tika tika = new Tika();
String content = tika.parseToString(stream);
return content;
}
|
public static Metadata extractMetadatatUsingParser(InputStream stream) throws IOException, SAXException, TikaException {
Parser parser = new AutoDetectParser();
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
ParseContext context = new ParseContext();
parser.parse(stream, handler, metadata, context);
return metadata;
}
public static Metadata extractMetadatatUsingFacade(InputStream stream) throws IOException, TikaException {
Tika tika = new Tika();
Metadata metadata = new Metadata();
tika.parse(stream, metadata);
return metadata;
}
}
|
repos\springboot-demo-master\tika\src\main\java\com\et\tika\convertor\TikaAnalysis.java
| 1
|
请完成以下Java代码
|
public class FlowableJackson2ObjectNode extends FlowableJackson2JsonNode<ObjectNode> implements FlowableObjectNode {
public FlowableJackson2ObjectNode(ObjectNode jsonNode) {
super(jsonNode);
}
@Override
public void put(String propertyName, String value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, Boolean value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, Short value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, Integer value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, Long value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, Double value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, Float value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, BigDecimal value) {
jsonNode.put(propertyName, value);
}
@Override
public void put(String propertyName, BigInteger value) {
jsonNode.put(propertyName, value);
}
@Override
|
public void put(String propertyName, byte[] value) {
jsonNode.put(propertyName, value);
}
@Override
public void putNull(String propertyName) {
jsonNode.putNull(propertyName);
}
@Override
public FlowableArrayNode putArray(String propertyName) {
return new FlowableJackson2ArrayNode(jsonNode.putArray(propertyName));
}
@Override
public void set(String propertyName, FlowableJsonNode value) {
jsonNode.set(propertyName, asJsonNode(value));
}
@Override
public FlowableObjectNode putObject(String propertyName) {
return new FlowableJackson2ObjectNode(jsonNode.putObject(propertyName));
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\json\jackson2\FlowableJackson2ObjectNode.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CityRestController {
@Autowired
private CityService cityService;
/**
* 插入 ES 新城市
*
* @param city
* @return
*/
@RequestMapping(value = "/api/city", method = RequestMethod.POST)
public Long createCity(@RequestBody City city) {
return cityService.saveCity(city);
}
/**
* AND 语句查询
*
* @param description
* @param score
* @return
*/
@RequestMapping(value = "/api/city/and/find", method = RequestMethod.GET)
public List<City> findByDescriptionAndScore(@RequestParam(value = "description") String description,
@RequestParam(value = "score") Integer score) {
return cityService.findByDescriptionAndScore(description, score);
}
/**
* OR 语句查询
*
* @param description
* @param score
* @return
*/
@RequestMapping(value = "/api/city/or/find", method = RequestMethod.GET)
public List<City> findByDescriptionOrScore(@RequestParam(value = "description") String description,
@RequestParam(value = "score") Integer score) {
return cityService.findByDescriptionOrScore(description, score);
}
/**
* 查询城市描述
|
*
* @param description
* @return
*/
@RequestMapping(value = "/api/city/description/find", method = RequestMethod.GET)
public List<City> findByDescription(@RequestParam(value = "description") String description) {
return cityService.findByDescription(description);
}
/**
* NOT 语句查询
*
* @param description
* @return
*/
@RequestMapping(value = "/api/city/description/not/find", method = RequestMethod.GET)
public List<City> findByDescriptionNot(@RequestParam(value = "description") String description) {
return cityService.findByDescriptionNot(description);
}
/**
* LIKE 语句查询
*
* @param description
* @return
*/
@RequestMapping(value = "/api/city/like/find", method = RequestMethod.GET)
public List<City> findByDescriptionLike(@RequestParam(value = "description") String description) {
return cityService.findByDescriptionLike(description);
}
}
|
repos\springboot-learning-example-master\spring-data-elasticsearch-crud\src\main\java\org\spring\springboot\controller\CityRestController.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.