instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | boolean matches(String content) {
return content.contains("\"spdxVersion\"");
}
},
SYFT(MimeType.valueOf("application/vnd.syft+json")) {
@Override
boolean matches(String content) {
return content.contains("\"FoundBy\"") || content.contains("\"foundBy\"");
}
},
UNKNOWN(null) {
@Override
boolean matches(String content) {
return false;
}
}; | private final @Nullable MimeType mediaType;
SbomType(@Nullable MimeType mediaType) {
this.mediaType = mediaType;
}
@Nullable MimeType getMediaType() {
return this.mediaType;
}
abstract boolean matches(String content);
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\sbom\SbomEndpointWebExtension.java | 1 |
请完成以下Java代码 | private void mutate(Individual indiv) {
for (int i = 0; i < indiv.getDefaultGeneLength(); i++) {
if (Math.random() <= mutationRate) {
byte gene = (byte) Math.round(Math.random());
indiv.setSingleGene(i, gene);
}
}
}
private Individual tournamentSelection(Population pop) {
Population tournament = new Population(tournamentSize, false);
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.getIndividuals().size());
tournament.getIndividuals().add(i, pop.getIndividual(randomId));
}
Individual fittest = tournament.getFittest();
return fittest;
}
protected static int getFitness(Individual individual) {
int fitness = 0;
for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) {
if (individual.getSingleGene(i) == solution[i]) {
fitness++; | }
}
return fitness;
}
protected int getMaxFitness() {
int maxFitness = solution.length;
return maxFitness;
}
protected void setSolution(String newSolution) {
solution = new byte[newSolution.length()];
for (int i = 0; i < newSolution.length(); i++) {
String character = newSolution.substring(i, i + 1);
if (character.contains("0") || character.contains("1")) {
solution[i] = Byte.parseByte(character);
} else {
solution[i] = 0;
}
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\binary\SimpleGeneticAlgorithm.java | 1 |
请完成以下Java代码 | public class RemoveEntryApplication {
public static void main(String[] args) {
HashMap<String, String> foodItemTypeMap = new HashMap<>();
foodItemTypeMap.put("Apple", "Fruit");
foodItemTypeMap.put("Grape", "Fruit");
foodItemTypeMap.put("Mango", "Fruit");
foodItemTypeMap.put("Carrot", "Vegetable");
foodItemTypeMap.put("Potato", "Vegetable");
foodItemTypeMap.put("Spinach", "Vegetable");
// Current Map Status: {Potato=Vegetable, Apple=Fruit, Carrot=Vegetable, Grape=Fruit, Mango=Fruit, Spinach=Vegetable}
foodItemTypeMap.remove("Apple");
// Current Map Status: {Potato=Vegetable, Carrot=Vegetable, Grape=Fruit, Mango=Fruit, Spinach=Vegetable}
foodItemTypeMap.remove("Grape", "Vegetable");
// Current Map Status: {Potato=Vegetable, Carrot=Vegetable, Grape=Fruit, Mango=Fruit, Spinach=Vegetable}
try {
for (Entry<String, String> item : foodItemTypeMap.entrySet()) {
if (item.getKey()
.equals("Potato")) {
foodItemTypeMap.remove(item.getKey());
}
}
} catch (ConcurrentModificationException e) {
System.out.println("Exception occured while updating map: " + e.toString());
}
foodItemTypeMap.entrySet()
.removeIf(entry -> entry.getKey()
.equals("Grape"));
// Current Map Status: {Carrot=Vegetable, Mango=Fruit, Spinach=Vegetable}
Iterator<Entry<String, String>> iterator = foodItemTypeMap.entrySet()
.iterator();
while (iterator.hasNext()) {
if (iterator.next()
.getKey()
.equals("Carrot"))
iterator.remove();
}
// Current Map Status: {Mango=Fruit, Spinach=Vegetable} | // Use ConcurrentHashMap
ConcurrentHashMap<String, String> foodItemTypeConcMap = new ConcurrentHashMap<>();
foodItemTypeConcMap.put("Apple", "Fruit");
foodItemTypeConcMap.put("Grape", "Fruit");
foodItemTypeConcMap.put("Mango", "Fruit");
foodItemTypeConcMap.put("Carrot", "Vegetable");
foodItemTypeConcMap.put("Potato", "Vegetable");
foodItemTypeConcMap.put("Spinach", "Vegetable");
for (Entry<String, String> item : foodItemTypeConcMap.entrySet()) {
if (item.getKey() != null && item.getKey()
.equals("Potato")) {
foodItemTypeConcMap.remove(item.getKey());
}
}
// foodItemTypeConcMap : {Apple=Fruit, Carrot=Vegetable, Grape=Fruit, Mango=Fruit, Spinach=Vegetable}
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-3\src\main\java\com\baeldung\map\hashmap\entryremoval\RemoveEntryApplication.java | 1 |
请完成以下Java代码 | public class IrisClassifier {
private static final int CLASSES_COUNT = 3;
private static final int FEATURES_COUNT = 4;
public static void main(String[] args) throws IOException, InterruptedException {
DataSet allData;
try (RecordReader recordReader = new CSVRecordReader(0, ',')) {
recordReader.initialize(new FileSplit(new ClassPathResource("iris.txt").getFile()));
DataSetIterator iterator = new RecordReaderDataSetIterator(recordReader, 150, FEATURES_COUNT, CLASSES_COUNT);
allData = iterator.next();
}
allData.shuffle(42);
DataNormalization normalizer = new NormalizerStandardize();
normalizer.fit(allData);
normalizer.transform(allData);
SplitTestAndTrain testAndTrain = allData.splitTestAndTrain(0.65);
DataSet trainingData = testAndTrain.getTrain();
DataSet testData = testAndTrain.getTest();
MultiLayerConfiguration configuration = new NeuralNetConfiguration.Builder()
.iterations(1000)
.activation(Activation.TANH)
.weightInit(WeightInit.XAVIER)
.regularization(true)
.learningRate(0.1).l2(0.0001)
.list()
.layer(0, new DenseLayer.Builder().nIn(FEATURES_COUNT).nOut(3) | .build())
.layer(1, new DenseLayer.Builder().nIn(3).nOut(3)
.build())
.layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.activation(Activation.SOFTMAX)
.nIn(3).nOut(CLASSES_COUNT).build())
.backpropType(BackpropType.Standard).pretrain(false)
.build();
MultiLayerNetwork model = new MultiLayerNetwork(configuration);
model.init();
model.fit(trainingData);
INDArray output = model.output(testData.getFeatures());
Evaluation eval = new Evaluation(CLASSES_COUNT);
eval.eval(testData.getLabels(), output);
System.out.println(eval.stats());
}
} | repos\tutorials-master\deeplearning4j\src\main\java\com\baeldung\deeplearning4j\IrisClassifier.java | 1 |
请完成以下Java代码 | public void setSourceExecution(DelegateCaseExecution sourceExecution) {
this.sourceExecution = sourceExecution;
}
/**
* Currently not part of public interface.
*/
public DelegateCaseExecution getScopeExecution() {
return scopeExecution;
}
public void setScopeExecution(DelegateCaseExecution scopeExecution) {
this.scopeExecution = scopeExecution;
}
//// methods delegated to wrapped variable ////
public String getId() {
return variableId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getTaskId() {
return taskId;
}
@Override
public String getBatchId() {
return null;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getErrorMessage() {
return errorMessage;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTypeName() {
if(value != null) {
return value.getType().getName();
}
else {
return null;
}
}
public String getName() { | return name;
}
public Object getValue() {
if(value != null) {
return value.getValue();
}
else {
return null;
}
}
public TypedValue getTypedValue() {
return value;
}
public ProcessEngineServices getProcessEngineServices() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public ProcessEngine getProcessEngine() {
return Context.getProcessEngineConfiguration().getProcessEngine();
}
public static DelegateCaseVariableInstanceImpl fromVariableInstance(VariableInstance variableInstance) {
DelegateCaseVariableInstanceImpl delegateInstance = new DelegateCaseVariableInstanceImpl();
delegateInstance.variableId = variableInstance.getId();
delegateInstance.processDefinitionId = variableInstance.getProcessDefinitionId();
delegateInstance.processInstanceId = variableInstance.getProcessInstanceId();
delegateInstance.executionId = variableInstance.getExecutionId();
delegateInstance.caseExecutionId = variableInstance.getCaseExecutionId();
delegateInstance.caseInstanceId = variableInstance.getCaseInstanceId();
delegateInstance.taskId = variableInstance.getTaskId();
delegateInstance.activityInstanceId = variableInstance.getActivityInstanceId();
delegateInstance.tenantId = variableInstance.getTenantId();
delegateInstance.errorMessage = variableInstance.getErrorMessage();
delegateInstance.name = variableInstance.getName();
delegateInstance.value = variableInstance.getTypedValue();
return delegateInstance;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\listener\DelegateCaseVariableInstanceImpl.java | 1 |
请完成以下Java代码 | public void add(T object) {
CountDownLatch lock = new CountDownLatch(1);
this.locks.putIfAbsent(object, lock);
}
public void release(T object) {
CountDownLatch remove = this.locks.remove(object);
if (remove != null) {
remove.countDown();
}
}
public boolean await(long timeout, TimeUnit timeUnit) throws InterruptedException {
long t0 = System.currentTimeMillis();
long t1 = t0 + TimeUnit.MILLISECONDS.convert(timeout, timeUnit);
while (System.currentTimeMillis() <= t1) {
if (this.locks.isEmpty()) {
return true;
}
Collection<T> objects = new HashSet<>(this.locks.keySet());
for (T object : objects) {
CountDownLatch lock = this.locks.get(object);
if (lock == null) {
continue;
}
t0 = System.currentTimeMillis();
if (lock.await(t1 - t0, TimeUnit.MILLISECONDS)) { | this.locks.remove(object);
}
}
}
return false;
}
public int getCount() {
return this.locks.size();
}
public void reset() {
this.locks.clear();
this.active = true;
}
public void deactivate() {
this.active = false;
}
public boolean isActive() {
return this.active;
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\ActiveObjectCounter.java | 1 |
请完成以下Java代码 | private void loadIfNeeded()
{
if (loaded)
{
return;
}
load();
loaded = true;
}
private void load()
{
//
// Load the HU
// NOTE: instead of getting the HU by using huStorage.getM_HU() we are loading it directly because the huStorage's transaction is already closed,
// and our ModelCacheService will log a WARNING about this.
// see ModelCacheService (line ~194): "No transaction was found for " + trxName + ". Skip cache."
if (huId <= 0)
{
loaded = true;
return;
}
final I_M_HU hu = InterfaceWrapperHelper.load(huId, I_M_HU.class);
if (hu == null)
{
return;
}
// Fire only VHUs because those attributes counts for us
if (Services.get(IHandlingUnitsBL.class).isVirtual(hu))
{
return;
}
final ShipmentScheduleSegmentFromHU huSegment = new ShipmentScheduleSegmentFromHU(hu);
// If this HU does not contain QtyOnHand storages, there is no point to go forward
// because actually nothing changed from QOH perspective
if (!huSegment.hasQtyOnHandChanges())
{
return;
}
productIds = huSegment.getProductIds();
bpartnerIds = huSegment.getBpartnerIds();
locatorIds = huSegment.getLocatorIds();
} | @Override
public Set<Integer> getProductIds()
{
loadIfNeeded();
return productIds;
}
@Override
public Set<Integer> getBpartnerIds()
{
loadIfNeeded();
return bpartnerIds;
}
@Override
public Set<Integer> getLocatorIds()
{
loadIfNeeded();
return locatorIds;
}
@Override
public Set<ShipmentScheduleAttributeSegment> getAttributes()
{
loadIfNeeded();
return attributeSegments;
}
@Override
public Set<Integer> getBillBPartnerIds()
{
return ImmutableSet.of();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\segments\ShipmentScheduleSegmentFromHUAttribute.java | 1 |
请完成以下Java代码 | public class MyDtoIgnoreFieldByName {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoIgnoreFieldByName() {
super();
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue; | }
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
} | repos\tutorials-master\jackson-simple\src\main\java\com\baeldung\jackson\ignore\MyDtoIgnoreFieldByName.java | 1 |
请完成以下Java代码 | public static long filesCompareByByte(Path path1, Path path2) throws IOException {
if (path1.getFileSystem()
.provider()
.isSameFile(path1, path2)) {
return -1;
}
try (BufferedInputStream fis1 = new BufferedInputStream(new FileInputStream(path1.toFile()));
BufferedInputStream fis2 = new BufferedInputStream(new FileInputStream(path2.toFile()))) {
int ch = 0;
long pos = 1;
while ((ch = fis1.read()) != -1) {
if (ch != fis2.read()) {
return pos;
}
pos++;
}
if (fis2.read() == -1) {
return -1;
} else {
return pos;
}
}
}
public static long filesCompareByLine(Path path1, Path path2) throws IOException {
if (path1.getFileSystem()
.provider()
.isSameFile(path1, path2)) {
return -1;
}
try (BufferedReader bf1 = Files.newBufferedReader(path1);
BufferedReader bf2 = Files.newBufferedReader(path2)) {
long lineNumber = 1;
String line1 = "", line2 = "";
while ((line1 = bf1.readLine()) != null) {
line2 = bf2.readLine();
if (line2 == null || !line1.equals(line2)) { | return lineNumber;
}
lineNumber++;
}
if (bf2.readLine() == null) {
return -1;
} else {
return lineNumber;
}
}
}
public static boolean compareByMemoryMappedFiles(Path path1, Path path2) throws IOException {
try (RandomAccessFile randomAccessFile1 = new RandomAccessFile(path1.toFile(), "r");
RandomAccessFile randomAccessFile2 = new RandomAccessFile(path2.toFile(), "r")) {
FileChannel ch1 = randomAccessFile1.getChannel();
FileChannel ch2 = randomAccessFile2.getChannel();
if (ch1.size() != ch2.size()) {
return false;
}
long size = ch1.size();
MappedByteBuffer m1 = ch1.map(FileChannel.MapMode.READ_ONLY, 0L, size);
MappedByteBuffer m2 = ch2.map(FileChannel.MapMode.READ_ONLY, 0L, size);
return m1.equals(m2);
}
}
} | repos\tutorials-master\core-java-modules\core-java-12\src\main\java\com\baeldung\file\content\comparison\CompareFileContents.java | 1 |
请完成以下Java代码 | public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the filename property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFilename() {
return filename;
}
/**
* Sets the value of the filename property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFilename(String value) {
this.filename = value;
}
/**
* Gets the value of the mimeType property.
* | * @return
* possible object is
* {@link String }
*
*/
public String getMimeType() {
return mimeType;
}
/**
* Sets the value of the mimeType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMimeType(String value) {
this.mimeType = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\DocumentType.java | 1 |
请完成以下Java代码 | public boolean hasAttachment() {
return attachmentExists;
}
@Override
public boolean hasComment() {
return commentExists;
}
public void escalation(String escalationCode, Map<String, Object> variables) {
ensureTaskActive();
ActivityExecution activityExecution = getExecution();
if (variables != null && !variables.isEmpty()) {
activityExecution.setVariables(variables);
}
EscalationHandler.propagateEscalation(activityExecution, escalationCode);
}
public static enum TaskState { | STATE_INIT ("Init"),
STATE_CREATED ("Created"),
STATE_COMPLETED ("Completed"),
STATE_DELETED ("Deleted"),
STATE_UPDATED ("Updated");
private String taskState;
private TaskState(String taskState) {
this.taskState = taskState;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskEntity.java | 1 |
请完成以下Java代码 | public static int unlabeledContinue() {
String searchName = "Wilson";
int counter = 0;
Map<String, List<String>> nameMap = new HashMap<>();
nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson"));
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold"));
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan"));
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
.iterator();
Entry<String, List<String>> entry = null;
List<String> names = null;
while (iterator.hasNext()) {
entry = iterator.next();
names = entry.getValue();
for (String name : names) {
if (!name.equalsIgnoreCase(searchName)) {
continue;
}
counter++;
}
}
return counter;
}
public static int labeledContinue() {
String searchName = "Wilson";
int counter = 0;
Map<String, List<String>> nameMap = new HashMap<>();
nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson"));
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold")); | nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan"));
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
.iterator();
Entry<String, List<String>> entry = null;
List<String> names = null;
compare:
while (iterator.hasNext()) {
entry = iterator.next();
names = entry.getValue();
for (String name : names) {
if (name.equalsIgnoreCase(searchName)) {
counter++;
continue compare;
}
}
}
return counter;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-syntax\src\main\java\com\baeldung\breakcontinue\BreakContinue.java | 1 |
请完成以下Java代码 | public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo); | }
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxDefinition.java | 1 |
请完成以下Java代码 | protected OrderId getSalesOrderId()
{
final Optional<OrderId> optionalSalesOrderId = CollectionUtils.extractSingleElementOrDefault(
getDocLines(),
docLine -> Optional.ofNullable(docLine.getSalesOrderId()),
Optional.empty());
//noinspection DataFlowIssue
return optionalSalesOrderId.orElse(null);
}
//
//
//
//
//
@Value | static class InOutDocBaseType
{
@NonNull DocBaseType docBaseType;
boolean isSOTrx;
public boolean isCustomerShipment() {return isSOTrx && docBaseType.isShipment();}
public boolean isCustomerReturn() {return isSOTrx && docBaseType.isReceipt();}
public boolean isVendorReceipt() {return !isSOTrx && docBaseType.isReceipt();}
public boolean isVendorReturn() {return !isSOTrx && docBaseType.isShipment();}
public boolean isReturn() {return isCustomerReturn() || isVendorReturn();}
}
} // Doc_InOut | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_InOut.java | 1 |
请完成以下Java代码 | private void indent() {
this.level++;
refreshIndent();
}
/**
* Decrease the indentation level.
*/
private void outdent() {
this.level--;
refreshIndent();
}
private void refreshIndent() {
this.indent = this.indentStrategy.apply(this.level);
}
@Override
public void write(char[] chars, int offset, int length) {
try {
if (this.prependIndent) {
this.out.write(this.indent.toCharArray(), 0, this.indent.length());
this.prependIndent = false;
}
this.out.write(chars, offset, length); | }
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public void flush() throws IOException {
this.out.flush();
}
@Override
public void close() throws IOException {
this.out.close();
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\io\IndentingWriter.java | 1 |
请完成以下Java代码 | public void pushRfQs(@Nullable final List<SyncRfQ> syncRfqs)
{
if (disabled.get())
{
logger.info("Disabled is set to true in this thread; -> doing nothing");
return;
}
if (syncRfqs == null || syncRfqs.isEmpty())
{
return;
}
final IAgentSync agent = getAgentSync();
agent.syncRfQs(syncRfqs);
}
@Override
public void pushRfQCloseEvents(
@Nullable final List<SyncRfQCloseEvent> syncRfQCloseEvents) | {
if (disabled.get())
{
logger.info("Disabled is set to true in this thread; -> doing nothing");
return;
}
if (syncRfQCloseEvents == null || syncRfQCloseEvents.isEmpty())
{
return;
}
final IAgentSync agent = getAgentSync();
agent.closeRfQs(syncRfQCloseEvents);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\WebuiPush.java | 1 |
请完成以下Java代码 | public int hashCode()
{
return new HashcodeBuilder()
.append(ctx)
.append(trxName)
.toHashcode();
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
final PlainContextAware other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.appendByRef(ctx, other.ctx)
.append(trxName, other.trxName) | .isEqual();
}
@Override
public Properties getCtx()
{
return ctx;
}
@Override
public String getTrxName()
{
return trxName;
}
@Override
public boolean isAllowThreadInherited()
{
return allowThreadInherited;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\PlainContextAware.java | 1 |
请完成以下Java代码 | public class OLCandDeleteSelectedRecords extends ViewBasedProcessTemplate implements IProcessPrecondition
{
private static final AdMessageKey PROCESSED_RECORDS_CANNOT_BE_DELETED = AdMessageKey.of("de.metas.ui.web.ordercandidate.process.PROCESSED_RECORDS_CANNOT_BE_DELETED");
private final IOLCandDAO candDAO = Services.get(IOLCandDAO.class);
private final IMsgBL msgBL = Services.get(IMsgBL.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (getSelectedRowIds().isEmpty())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (getSelectedRowIds().isAll())
{
return ProcessPreconditionsResolution.accept();
}
final boolean isProcessedRecordSelected = candDAO.isAnyRecordProcessed(getSelectedRowIds().toIds(OLCandId::ofRepoId));
if (isProcessedRecordSelected)
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(PROCESSED_RECORDS_CANNOT_BE_DELETED));
}
return ProcessPreconditionsResolution.accept(); | }
@Override
protected String doIt() throws Exception
{
final int count = getSelectedRowIds().isAll()
? candDAO.deleteUnprocessedRecords(getProcessInfo().getQueryFilterOrElseFalse())
: candDAO.deleteRecords(getSelectedRowIds().toIds(OLCandId::ofRepoId));
return "@Deleted@ #" + count;
}
@Override
protected void postProcess(final boolean success)
{
invalidateView();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\ordercandidate\process\OLCandDeleteSelectedRecords.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Area getArea()
{
Check.assumeNotNull(_area, "area not null");
return _area;
}
@Override
public Size applyAt(final CellRef cellRef, final Context context)
{
//
// Process area
final Area area = getArea();
final Size size = area.applyAt(cellRef, context);
//
// If given condition is evaluated as true, hide given columns
if (isConditionTrue(context))
{
logger.debug("Hiding column of {} because condition '{}' was evaluated as true", cellRef, condition);
hideColumn(cellRef);
}
else
{
logger.debug("Skip hiding column of {} because condition '{}' was evaluated as false", cellRef, condition);
}
//
return size;
}
private void hideColumn(final CellRef cellRef)
{
final Transformer transformer = getTransformer();
if (transformer instanceof PoiTransformer)
{
final PoiTransformer poiTransformer = (PoiTransformer)transformer;
final Workbook poiWorkbook = poiTransformer.getWorkbook();
if (poiWorkbook == null)
{
logger.warn("Cannot hide column of {} because there is no workbook found", cellRef);
return;
}
final String sheetName = cellRef.getSheetName();
final Sheet poiSheet = poiWorkbook.getSheet(sheetName);
if (poiSheet == null)
{
logger.warn("Cannot hide column of {} because there is no sheet found", cellRef); | return;
}
final AreaRef areaRef = getArea().getAreaRef();
final CellRef areaFirstCell = areaRef.getFirstCellRef();
final CellRef areaLastCell = areaRef.getLastCellRef();
final int firstColumn = Math.min(areaFirstCell.getCol(), areaLastCell.getCol());
final int lastColumn = Math.max(areaFirstCell.getCol(), areaLastCell.getCol());
for (int col = firstColumn; col <= lastColumn; col++)
{
poiSheet.setColumnHidden(col, true);
// poiSheet.setColumnWidth(cellRef.getCol(), 0);
logger.debug("Column of {} was hidden", cellRef);
}
}
else
{
logger.warn("Cannot hide column of {} because transformer {} is not supported", transformer);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\HideColumnIfCommand.java | 2 |
请完成以下Java代码 | public ResponseEntity<HttpStatus> saveColumn(@RequestBody List<ColumnInfo> columnInfos){
generatorService.save(columnInfos);
return new ResponseEntity<>(HttpStatus.OK);
}
@ApiOperation("同步字段数据")
@PostMapping(value = "sync")
public ResponseEntity<HttpStatus> syncColumn(@RequestBody List<String> tables){
for (String table : tables) {
generatorService.sync(generatorService.getColumns(table), generatorService.query(table));
}
return new ResponseEntity<>(HttpStatus.OK);
}
@ApiOperation("生成代码")
@PostMapping(value = "/{tableName}/{type}")
public ResponseEntity<Object> generatorCode(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response){
if(!generatorEnabled && type == 0){ | throw new BadRequestException("此环境不允许生成代码,请选择预览或者下载查看!");
}
switch (type){
// 生成代码
case 0: generatorService.generator(genConfigService.find(tableName), generatorService.getColumns(tableName));
break;
// 预览
case 1: return generatorService.preview(genConfigService.find(tableName), generatorService.getColumns(tableName));
// 打包
case 2: generatorService.download(genConfigService.find(tableName), generatorService.getColumns(tableName), request, response);
break;
default: throw new BadRequestException("没有这个选项");
}
return new ResponseEntity<>(HttpStatus.OK);
}
} | repos\eladmin-master\eladmin-generator\src\main\java\me\zhengjie\rest\GeneratorController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String propertyName = getConfiguredProperty(environment);
DatabaseInitializationMode mode = getDatabaseInitializationMode(environment, propertyName);
boolean match = match(mode);
String messagePrefix = (propertyName != null) ? propertyName : "default value";
return new ConditionOutcome(match, ConditionMessage.forCondition(this.name + "Database Initialization")
.because(messagePrefix + " is " + mode));
}
private boolean match(DatabaseInitializationMode mode) {
return !mode.equals(DatabaseInitializationMode.NEVER);
}
private DatabaseInitializationMode getDatabaseInitializationMode(Environment environment,
@Nullable String propertyName) {
if (StringUtils.hasText(propertyName)) {
String candidate = environment.getProperty(propertyName, "embedded").toUpperCase(Locale.ENGLISH);
if (StringUtils.hasText(candidate)) {
return DatabaseInitializationMode.valueOf(candidate); | }
}
return DatabaseInitializationMode.EMBEDDED;
}
private @Nullable String getConfiguredProperty(Environment environment) {
for (String propertyName : this.propertyNames) {
if (environment.containsProperty(propertyName)) {
return propertyName;
}
}
return null;
}
} | repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\autoconfigure\init\OnDatabaseInitializationCondition.java | 2 |
请完成以下Java代码 | private static BPartnerId extractSingleCustomerIdOrNull(final Collection<HUReservationEntry> entries)
{
final ImmutableSet<BPartnerId> customerIds = entries
.stream()
.map(HUReservationEntry::getCustomerId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
return customerIds.size() == 1 ? customerIds.iterator().next() : null;
}
private static Quantity computeReservedQtySum(final Collection<HUReservationEntry> entries)
{
//noinspection OptionalGetWithoutIsPresent
return entries
.stream()
.map(HUReservationEntry::getQtyReserved)
.reduce(Quantity::add)
.get();
} | public ImmutableSet<HuId> getVhuIds()
{
return entriesByVHUId.keySet();
}
public Quantity getReservedQtyByVhuId(@NonNull final HuId vhuId)
{
final HUReservationEntry entry = entriesByVHUId.get(vhuId);
if (entry == null)
{
throw new AdempiereException("@NotFound@ @VHU_ID@");
}
return entry.getQtyReserved();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservation.java | 1 |
请完成以下Java代码 | private I_M_InOut getReceiptOrNull(final int huId)
{
final I_M_InOut receipt = huId2inout.get(huId);
return receipt;
}
public List<I_M_InOut> getReceiptsToReverseFromHUs(final Collection<I_M_HU> huAwareList)
{
return getReceiptsToReverse(IHUAware.transformHUCollection(hus));
}
/**
* Get the receipts to be reversed based on given HUs.
*
* @param huAwareList
* @return receipts
*/
public List<I_M_InOut> getReceiptsToReverse(final Collection<? extends IHUAware> huAwareList)
{
if (huAwareList == null || huAwareList.isEmpty())
{
return ImmutableList.of();
}
return getReceiptsToReverse(huAwareList
.stream()
.map(huAware -> huAware.getM_HU().getM_HU_ID()));
}
public List<I_M_InOut> getReceiptsToReverseFromHUIds(final Collection<Integer> huIds)
{
if (huIds == null || huIds.isEmpty())
{
return ImmutableList.of();
}
return getReceiptsToReverse(huIds.stream());
}
private final List<I_M_InOut> getReceiptsToReverse(final Stream<Integer> huIds)
{
return huIds
.map(huId -> getReceiptOrNull(huId))
// skip if no receipt found because
// * it could be that user selected not a top level HU.... skip it for now
// * or we were really asked to as much as we can
.filter(receipt -> receipt != null)
.collect(GuavaCollectors.toImmutableList());
}
/**
* Get all HUs which are assigned to given receipts.
*
* @param receipts
* @return HUs
*/
public Set<I_M_HU> getHUsForReceipts(final Collection<? extends I_M_InOut> receipts)
{
final Set<I_M_HU> hus = new TreeSet<>(HUByIdComparator.instance);
for (final I_M_InOut receipt : receipts)
{
final int inoutId = receipt.getM_InOut_ID();
final Collection<I_M_HU> husForReceipt = inoutId2hus.get(inoutId);
if (Check.isEmpty(husForReceipt))
{
continue;
}
hus.addAll(husForReceipt);
}
return hus;
}
public static final class Builder | {
private I_M_ReceiptSchedule receiptSchedule;
private boolean tolerateNoHUsFound = false;
private Builder()
{
super();
}
public ReceiptCorrectHUsProcessor build()
{
return new ReceiptCorrectHUsProcessor(this);
}
public Builder setM_ReceiptSchedule(final I_M_ReceiptSchedule receiptSchedule)
{
this.receiptSchedule = receiptSchedule;
return this;
}
private I_M_ReceiptSchedule getM_ReceiptSchedule()
{
Check.assumeNotNull(receiptSchedule, "Parameter receiptSchedule is not null");
return receiptSchedule;
}
public Builder tolerateNoHUsFound()
{
tolerateNoHUsFound = true;
return this;
}
private boolean isFailOnNoHUsFound()
{
return !tolerateNoHUsFound;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\ReceiptCorrectHUsProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigInteger getEDICctop140VID() {
return ediCctop140VID;
}
/**
* Sets the value of the ediCctop140VID property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setEDICctop140VID(BigInteger value) {
this.ediCctop140VID = value;
}
/**
* 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 name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the discountAmt property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getDiscountAmt() {
return discountAmt; | }
/**
* Sets the value of the discountAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setDiscountAmt(BigDecimal value) {
this.discountAmt = value;
}
/**
* Gets the value of the discountBaseAmt property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getDiscountBaseAmt() {
return discountBaseAmt;
}
/**
* Sets the value of the discountBaseAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setDiscountBaseAmt(BigDecimal value) {
this.discountBaseAmt = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop140VType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public WidgetsBundle save(WidgetsBundle widgetsBundle, SecurityUser user) throws Exception {
ActionType actionType = widgetsBundle.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = widgetsBundle.getTenantId();
try {
WidgetsBundle savedWidgetsBundle = checkNotNull(widgetsBundleService.saveWidgetsBundle(widgetsBundle));
autoCommit(user, savedWidgetsBundle.getId());
logEntityActionService.logEntityAction(tenantId, savedWidgetsBundle.getId(), savedWidgetsBundle,
null, actionType, user);
return savedWidgetsBundle;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.WIDGETS_BUNDLE), widgetsBundle, actionType, user, e);
throw e;
}
}
@Override
public void delete(WidgetsBundle widgetsBundle, User user) {
ActionType actionType = ActionType.DELETED;
TenantId tenantId = widgetsBundle.getTenantId();
try {
widgetsBundleService.deleteWidgetsBundle(widgetsBundle.getTenantId(), widgetsBundle.getId());
logEntityActionService.logEntityAction(tenantId, widgetsBundle.getId(), widgetsBundle, null, actionType, user);
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.WIDGETS_BUNDLE), actionType, user, e, widgetsBundle.getId());
throw e; | }
}
@Override
public void updateWidgetsBundleWidgetTypes(WidgetsBundleId widgetsBundleId, List<WidgetTypeId> widgetTypeIds, User user) throws Exception {
widgetTypeService.updateWidgetsBundleWidgetTypes(user.getTenantId(), widgetsBundleId, widgetTypeIds);
autoCommit(user, widgetsBundleId);
}
@Override
public void updateWidgetsBundleWidgetFqns(WidgetsBundleId widgetsBundleId, List<String> widgetFqns, User user) throws Exception {
widgetTypeService.updateWidgetsBundleWidgetFqns(user.getTenantId(), widgetsBundleId, widgetFqns);
autoCommit(user, widgetsBundleId);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\widgets\bundle\DefaultWidgetsBundleService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(BigDecimal orderAmount) {
this.orderAmount = orderAmount;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getMerchantName() {
return merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
public String getMerchantOrderNo() {
return merchantOrderNo;
}
public void setMerchantOrderNo(String merchantOrderNo) { | this.merchantOrderNo = merchantOrderNo;
}
public String getPayKey() {
return payKey;
}
public void setPayKey(String payKey) {
this.payKey = payKey;
}
public Map<String, PayTypeEnum> getPayTypeEnumMap() {
return payTypeEnumMap;
}
public void setPayTypeEnumMap(Map<String, PayTypeEnum> payTypeEnumMap) {
this.payTypeEnumMap = payTypeEnumMap;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\RpPayGateWayPageShowVo.java | 2 |
请完成以下Java代码 | public class TimezoneDisplay {
public enum OffsetBase {
GMT, UTC
}
public List<String> getTimeZoneList(OffsetBase base) {
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
LocalDateTime now = LocalDateTime.now();
return availableZoneIds
.stream()
.map(ZoneId::of)
.sorted(new ZoneComparator())
.map(id -> String.format("(%s%s) %s", base, getOffset(now, id), id.getId()))
.collect(Collectors.toList());
}
private String getOffset(LocalDateTime dateTime, ZoneId id) {
return dateTime
.atZone(id)
.getOffset()
.getId()
.replace("Z", "+00:00");
}
private class ZoneComparator implements Comparator<ZoneId> {
@Override
public int compare(ZoneId zoneId1, ZoneId zoneId2) { | LocalDateTime now = LocalDateTime.now();
ZoneOffset offset1 = now
.atZone(zoneId1)
.getOffset();
ZoneOffset offset2 = now
.atZone(zoneId2)
.getOffset();
return offset1.compareTo(offset2);
}
}
} | repos\tutorials-master\core-java-modules\core-java-datetime-string-2\src\main\java\com\baeldung\timezonedisplay\TimezoneDisplay.java | 1 |
请完成以下Java代码 | public void setUltmtDbtr(PartyIdentification32 value) {
this.ultmtDbtr = value;
}
/**
* Gets the value of the cdtr property.
*
* @return
* possible object is
* {@link PartyIdentification32 }
*
*/
public PartyIdentification32 getCdtr() {
return cdtr;
}
/**
* Sets the value of the cdtr property.
*
* @param value
* allowed object is
* {@link PartyIdentification32 }
*
*/
public void setCdtr(PartyIdentification32 value) {
this.cdtr = value;
}
/**
* Gets the value of the cdtrAcct property.
*
* @return
* possible object is
* {@link CashAccount16 }
*
*/
public CashAccount16 getCdtrAcct() {
return cdtrAcct;
}
/**
* Sets the value of the cdtrAcct property.
*
* @param value
* allowed object is
* {@link CashAccount16 }
*
*/
public void setCdtrAcct(CashAccount16 value) {
this.cdtrAcct = value;
}
/**
* Gets the value of the ultmtCdtr property.
*
* @return
* possible object is
* {@link PartyIdentification32 }
*
*/
public PartyIdentification32 getUltmtCdtr() {
return ultmtCdtr;
}
/**
* Sets the value of the ultmtCdtr property.
*
* @param value
* allowed object is
* {@link PartyIdentification32 }
*
*/
public void setUltmtCdtr(PartyIdentification32 value) {
this.ultmtCdtr = value;
}
/** | * Gets the value of the tradgPty property.
*
* @return
* possible object is
* {@link PartyIdentification32 }
*
*/
public PartyIdentification32 getTradgPty() {
return tradgPty;
}
/**
* Sets the value of the tradgPty property.
*
* @param value
* allowed object is
* {@link PartyIdentification32 }
*
*/
public void setTradgPty(PartyIdentification32 value) {
this.tradgPty = value;
}
/**
* Gets the value of the prtry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prtry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrtry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProprietaryParty2 }
*
*
*/
public List<ProprietaryParty2> getPrtry() {
if (prtry == null) {
prtry = new ArrayList<ProprietaryParty2>();
}
return this.prtry;
}
} | 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\TransactionParty2.java | 1 |
请完成以下Java代码 | public DmnDeploymentEntity getDeployment() {
return deploymentEntity;
}
public List<DecisionEntity> getAllDecisions() {
return decisions;
}
public EngineResource getResourceForDecision(DecisionEntity decision) {
return mapDecisionsToResources.get(decision);
}
public DmnParse getDmnParseForDecision(DecisionEntity decision) {
return mapDecisionsToParses.get(decision);
}
public DmnDefinition getDmnDefinitionForDecision(DecisionEntity decision) {
DmnParse parse = getDmnParseForDecision(decision); | return (parse == null ? null : parse.getDmnDefinition());
}
public DecisionService getDecisionServiceForDecisionEntity(DecisionEntity decisionEntity) {
DmnDefinition dmnDefinition = getDmnDefinitionForDecision(decisionEntity);
return (dmnDefinition == null ? null : dmnDefinition.getDecisionServiceById(decisionEntity.getKey()));
}
public Decision getDecisionForDecisionEntity(DecisionEntity decisionEntity) {
DmnDefinition dmnDefinition = getDmnDefinitionForDecision(decisionEntity);
return (dmnDefinition == null ? null : dmnDefinition.getDecisionById(decisionEntity.getKey()));
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\deployer\ParsedDeployment.java | 1 |
请完成以下Java代码 | private static boolean isDefaultValuePresent(@Nullable String defaultValue)
{
return !Check.isEmpty(defaultValue);
}
@Override
public String toString()
{
return toStringWithoutMarkers();
}
@Override
public int hashCode()
{
if (_hashcode == null)
{
final int prime = 31;
int result = 1;
result = prime * result + (defaultValue == null ? 0 : defaultValue.hashCode());
result = prime * result + (modifiers == null ? 0 : modifiers.hashCode());
result = prime * result + (name == null ? 0 : name.hashCode());
_hashcode = result;
}
return _hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final CtxName other = (CtxName)obj;
if (defaultValue == null)
{
if (other.defaultValue != null)
{
return false;
}
}
else if (!defaultValue.equals(other.defaultValue))
{
return false;
}
if (modifiers == null) | {
if (other.modifiers != null)
{
return false;
}
}
else if (!modifiers.equals(other.modifiers))
{
return false;
}
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
return true;
}
public boolean equalsByName(@Nullable final CtxName other)
{
return other != null && this.name.equals(other.name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\CtxName.java | 1 |
请完成以下Java代码 | public static List<Indexed<String>> getOddIndexedStrings(List<String> names) {
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
.filter(i -> i.getIndex() % 2 == 1)
.collect(Collectors.toList());
return list;
}
public static List<String> getOddIndexedStrings(String[] names) {
List<String> oddIndexedNames = IntStream.range(0, names.length)
.filter(i -> i % 2 == 1)
.mapToObj(i -> names[i])
.collect(Collectors.toList());
return oddIndexedNames;
}
public static List<String> getOddIndexedStringsVersionTwo(String[] names) {
List<String> oddIndexedNames = Stream.of(names)
.zipWithIndex()
.filter(tuple -> tuple._2 % 2 == 1)
.map(tuple -> tuple._1)
.toJavaList();
return oddIndexedNames; | }
public static List<String> getEvenIndexedStringsUsingAtomicInteger(String[] names) {
AtomicInteger index = new AtomicInteger(0);
return Arrays.stream(names)
.filter(name -> index.getAndIncrement() % 2 == 0)
.collect(Collectors.toList());
}
public static List<String> getEvenIndexedStringsAtomicIntegerParallel(String[] names) {
AtomicInteger index = new AtomicInteger(0);
return Arrays.stream(names)
.parallel()
.filter(name -> index.getAndIncrement() % 2 == 0) .collect(Collectors.toList());
}
} | repos\tutorials-master\core-java-modules\core-java-streams\src\main\java\com\baeldung\stream\StreamIndices.java | 1 |
请完成以下Java代码 | public final class ReceiptMovementDateRule
{
public static final ReceiptMovementDateRule ORDER_DATE_PROMISED = new ReceiptMovementDateRule(Type.ORDER_DATE_PROMISED, null);
public static final ReceiptMovementDateRule EXTERNAL_DATE_IF_AVAIL = new ReceiptMovementDateRule(Type.EXTERNAL_DATE_IF_AVAIL, null);
public static final ReceiptMovementDateRule CURRENT_DATE = new ReceiptMovementDateRule(Type.CURRENT_DATE, null);
private enum Type
{
ORDER_DATE_PROMISED,
EXTERNAL_DATE_IF_AVAIL,
CURRENT_DATE,
FIXED_DATE,
}
@NonNull private final Type type;
@Nullable private final Instant fixedDate;
private ReceiptMovementDateRule(@NonNull final Type type, @Nullable final Instant fixedDate)
{
this.type = type;
this.fixedDate = fixedDate;
}
public interface CaseMapper<T>
{
T orderDatePromised();
T externalDateIfAvailable();
T currentDate();
T fixedDate(@NonNull Instant fixedDate);
} | public <T> T map(@NonNull final CaseMapper<T> mapper)
{
switch (type)
{
case ORDER_DATE_PROMISED:
return mapper.orderDatePromised();
case EXTERNAL_DATE_IF_AVAIL:
return mapper.externalDateIfAvailable();
case CURRENT_DATE:
return mapper.currentDate();
case FIXED_DATE:
final Instant fixedDate = Check.assumeNotNull(this.fixedDate, "Fixed date is set");
return mapper.fixedDate(fixedDate);
default:
throw new AdempiereException("Type not handled: " + type);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptMovementDateRule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SbomProperties {
/**
* Application SBOM configuration.
*/
private final Sbom application = new Sbom();
/**
* Additional SBOMs.
*/
private Map<String, Sbom> additional = new HashMap<>();
public Sbom getApplication() {
return this.application;
}
public Map<String, Sbom> getAdditional() {
return this.additional;
}
public void setAdditional(Map<String, Sbom> additional) {
this.additional = additional;
}
public static class Sbom {
/**
* Location to the SBOM. If null, the location will be auto-detected.
*/
private @Nullable String location;
/** | * Media type of the SBOM. If null, the media type will be auto-detected.
*/
private @Nullable MimeType mediaType;
public @Nullable String getLocation() {
return this.location;
}
public void setLocation(@Nullable String location) {
this.location = location;
}
public @Nullable MimeType getMediaType() {
return this.mediaType;
}
public void setMediaType(@Nullable MimeType mediaType) {
this.mediaType = mediaType;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\sbom\SbomProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MyGrantedAuthority implements GrantedAuthority {
private String url;
private String method;
public String getPermissionUrl() {
return url;
}
public void setPermissionUrl(String permissionUrl) {
this.url = permissionUrl;
}
public String getMethod() {
return method; | }
public void setMethod(String method) {
this.method = method;
}
public MyGrantedAuthority(String url, String method) {
this.url = url;
this.method = method;
}
@Override
public String getAuthority() {
return this.url + ";" + this.method;
}
} | repos\springBoot-master\springboot-springSecurity3\src\main\java\com\us\example\service\MyGrantedAuthority.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getSqlParser() {
return sqlParser;
}
public void setSqlParser(String sqlParser) {
this.sqlParser = sqlParser;
Optional.ofNullable(sqlParser).ifPresent(v -> properties.setProperty("sqlParser", v));
}
public Boolean getAsyncCount() {
return asyncCount;
}
public void setAsyncCount(Boolean asyncCount) {
this.asyncCount = asyncCount;
Optional.ofNullable(asyncCount).ifPresent(v -> properties.setProperty("asyncCount", v.toString()));
}
public String getCountSqlParser() {
return countSqlParser;
}
public void setCountSqlParser(String countSqlParser) {
this.countSqlParser = countSqlParser;
Optional.ofNullable(countSqlParser).ifPresent(v -> properties.setProperty("countSqlParser", v));
} | public String getOrderBySqlParser() {
return orderBySqlParser;
}
public void setOrderBySqlParser(String orderBySqlParser) {
this.orderBySqlParser = orderBySqlParser;
Optional.ofNullable(orderBySqlParser).ifPresent(v -> properties.setProperty("orderBySqlParser", v));
}
public String getSqlServerSqlParser() {
return sqlServerSqlParser;
}
public void setSqlServerSqlParser(String sqlServerSqlParser) {
this.sqlServerSqlParser = sqlServerSqlParser;
Optional.ofNullable(sqlServerSqlParser).ifPresent(v -> properties.setProperty("sqlServerSqlParser", v));
}
} | repos\pagehelper-spring-boot-master\pagehelper-spring-boot-autoconfigure\src\main\java\com\github\pagehelper\autoconfigure\PageHelperStandardProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private String serialize(EntityDescriptor entityDescriptor) {
return this.saml.serialize(entityDescriptor).prettyPrint(this.usePrettyPrint).serialize();
}
private String serialize(EntitiesDescriptor entities) {
return this.saml.serialize(entities).prettyPrint(this.usePrettyPrint).serialize();
}
/**
* Configure whether to sign the metadata, defaults to {@code false}.
*
* @since 6.4
*/
void setSignMetadata(boolean signMetadata) {
this.signMetadata = signMetadata;
}
/**
* A tuple containing an OpenSAML {@link EntityDescriptor} and its associated
* {@link RelyingPartyRegistration}
*
* @since 5.7
*/
static final class EntityDescriptorParameters { | private final EntityDescriptor entityDescriptor;
private final RelyingPartyRegistration registration;
EntityDescriptorParameters(EntityDescriptor entityDescriptor, RelyingPartyRegistration registration) {
this.entityDescriptor = entityDescriptor;
this.registration = registration;
}
EntityDescriptor getEntityDescriptor() {
return this.entityDescriptor;
}
RelyingPartyRegistration getRelyingPartyRegistration() {
return this.registration;
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\metadata\BaseOpenSamlMetadataResolver.java | 2 |
请完成以下Java代码 | public void setIsSyncExternalReferencesToRabbitMQ (final boolean IsSyncExternalReferencesToRabbitMQ)
{
set_Value (COLUMNNAME_IsSyncExternalReferencesToRabbitMQ, IsSyncExternalReferencesToRabbitMQ);
}
@Override
public boolean isSyncExternalReferencesToRabbitMQ()
{
return get_ValueAsBoolean(COLUMNNAME_IsSyncExternalReferencesToRabbitMQ);
}
@Override
public void setRemoteURL (final java.lang.String RemoteURL)
{
set_Value (COLUMNNAME_RemoteURL, RemoteURL);
}
@Override
public String getRemoteURL()
{
return get_ValueAsString(COLUMNNAME_RemoteURL);
}
@Override
public void setRouting_Key (final String Routing_Key)
{
set_Value (COLUMNNAME_Routing_Key, Routing_Key);
} | @Override
public String getRouting_Key()
{
return get_ValueAsString(COLUMNNAME_Routing_Key);
}
@Override
public void setAuthToken (final String AuthToken)
{
set_Value (COLUMNNAME_AuthToken, AuthToken);
}
@Override
public String getAuthToken()
{
return get_ValueAsString(COLUMNNAME_AuthToken);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_RabbitMQ_HTTP.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static class FallbackHeadersConfig {
private String executionExceptionTypeHeaderName = CB_EXECUTION_EXCEPTION_TYPE;
private String executionExceptionMessageHeaderName = CB_EXECUTION_EXCEPTION_MESSAGE;
private String rootCauseExceptionTypeHeaderName = CB_ROOT_CAUSE_EXCEPTION_TYPE;
private String rootCauseExceptionMessageHeaderName = CB_ROOT_CAUSE_EXCEPTION_MESSAGE;
public String getExecutionExceptionTypeHeaderName() {
return executionExceptionTypeHeaderName;
}
public void setExecutionExceptionTypeHeaderName(String executionExceptionTypeHeaderName) {
this.executionExceptionTypeHeaderName = executionExceptionTypeHeaderName;
}
public String getExecutionExceptionMessageHeaderName() {
return executionExceptionMessageHeaderName;
}
public void setExecutionExceptionMessageHeaderName(String executionExceptionMessageHeaderName) {
this.executionExceptionMessageHeaderName = executionExceptionMessageHeaderName;
} | public String getRootCauseExceptionTypeHeaderName() {
return rootCauseExceptionTypeHeaderName;
}
public void setRootCauseExceptionTypeHeaderName(String rootCauseExceptionTypeHeaderName) {
this.rootCauseExceptionTypeHeaderName = rootCauseExceptionTypeHeaderName;
}
public String getRootCauseExceptionMessageHeaderName() {
return rootCauseExceptionMessageHeaderName;
}
public void setRootCauseExceptionMessageHeaderName(String rootCauseExceptionMessageHeaderName) {
this.rootCauseExceptionMessageHeaderName = rootCauseExceptionMessageHeaderName;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\BeforeFilterFunctions.java | 2 |
请完成以下Java代码 | public FacetCollectorRequestBuilder<ModelType> setSource(final IFacetFilterable<ModelType> dataSource)
{
this.source_filterable = dataSource;
return this;
}
/**
* @param onlyFacetCategoriesPredicate
* @return facets collecting source to be used when collecting facets.
*/
public IQueryBuilder<ModelType> getSourceToUse(final Predicate<IFacetCategory> onlyFacetCategoriesPredicate)
{
Check.assumeNotNull(source_filterable, "source_filterable not null");
final IQueryBuilder<ModelType> queryBuilder = source_filterable.createQueryBuilder(onlyFacetCategoriesPredicate);
return queryBuilder;
}
/**
* Advice to collect facets only from given included facet categories. All other facet categories will be excluded.
*
* @param facetCategory
*/
public FacetCollectorRequestBuilder<ModelType> includeFacetCategory(final IFacetCategory facetCategory)
{
facetCategoryIncludesExcludes.include(facetCategory);
return this;
}
/**
* Advice to NOT collect facets from given exclude facet categories, even if they were added to include list.
*
* @param facetCategory
*/
public FacetCollectorRequestBuilder<ModelType> excludeFacetCategory(final IFacetCategory facetCategory)
{
facetCategoryIncludesExcludes.exclude(facetCategory); | return this;
}
/**
*
* @param facetCategory
* @return true if given facet category shall be considered when collecting facets
*/
public boolean acceptFacetCategory(final IFacetCategory facetCategory)
{
// Don't accept it if is excluded by includes/excludes list
if (!facetCategoryIncludesExcludes.build().test(facetCategory))
{
return false;
}
// Only categories which have "eager refresh" set (if asked)
if (onlyEagerRefreshCategories && !facetCategory.isEagerRefresh())
{
return false;
}
// accept the facet category
return true;
}
/**
* Collect facets only for categories which have {@link IFacetCategory#isEagerRefresh()}.
*/
public FacetCollectorRequestBuilder<ModelType> setOnlyEagerRefreshCategories()
{
this.onlyEagerRefreshCategories = true;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\FacetCollectorRequestBuilder.java | 1 |
请完成以下Java代码 | public class FlinkDataPipeline {
public static void capitalize() throws Exception {
String inputTopic = "flink_input";
String outputTopic = "flink_output";
String consumerGroup = "baeldung";
String address = "localhost:9092";
StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
FlinkKafkaConsumer<String> flinkKafkaConsumer = createStringConsumerForTopic(inputTopic, address, consumerGroup);
flinkKafkaConsumer.setStartFromEarliest();
DataStream<String> stringInputStream = environment.addSource(flinkKafkaConsumer);
FlinkKafkaProducer<String> flinkKafkaProducer = createStringProducer(outputTopic, address);
stringInputStream.map(new WordsCapitalizer())
.addSink(flinkKafkaProducer);
environment.execute();
}
public static void createBackup() throws Exception {
String inputTopic = "flink_input";
String outputTopic = "flink_output";
String consumerGroup = "baeldung"; | String kafkaAddress = "localhost:9092";
StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
FlinkKafkaConsumer<InputMessage> flinkKafkaConsumer = createInputMessageConsumer(inputTopic, kafkaAddress, consumerGroup);
flinkKafkaConsumer.setStartFromEarliest();
flinkKafkaConsumer.assignTimestampsAndWatermarks(new InputMessageTimestampAssigner());
FlinkKafkaProducer<Backup> flinkKafkaProducer = createBackupProducer(outputTopic, kafkaAddress);
DataStream<InputMessage> inputMessagesStream = environment.addSource(flinkKafkaConsumer);
inputMessagesStream.timeWindowAll(Time.hours(24))
.aggregate(new BackupAggregator())
.addSink(flinkKafkaProducer);
environment.execute();
}
public static void main(String[] args) throws Exception {
createBackup();
}
} | repos\tutorials-master\apache-kafka-2\src\main\java\com\baeldung\flink\FlinkDataPipeline.java | 1 |
请完成以下Java代码 | public Todo create(Todo item) {
if (null == item || null != item.id()) {
throw new IllegalArgumentException("item must exist without any id");
}
return mapper.map(repo.save(mapper.map(item)));
}
/**
* Aktualisiert ein Item im Datenbestand.
*
* @param item das zu ändernde Item mit ID
* @throws IllegalArgumentException
* wenn das Item oder dessen ID nicht belegt ist
* @throws NotFoundException
* wenn das Element mit der ID nicht gefunden wird
*/
public void update(Todo item) {
if (null == item || null == item.id()) {
throw new IllegalArgumentException("item must exist with an id");
}
// remove separat, um nicht neue Einträge hinzuzufügen (put allein würde auch ersetzen)
if (repo.existsById(item.id())) {
repo.save(mapper.map(item));
} else {
throw new NotFoundException();
}
}
/** | * Entfernt ein Item aus dem Datenbestand.
*
* @param id die ID des zu löschenden Items
* @throws NotFoundException
* wenn das Element mit der ID nicht gefunden wird
*/
public void delete(long id) {
if (repo.existsById(id)) {
repo.deleteById(id);
} else {
throw new NotFoundException();
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\java\com\baeldung\sample\control\TodosService.java | 1 |
请完成以下Java代码 | public static void setSelectAllOnFocus(final JComponent c)
{
if (c instanceof JTextComponent)
{
setSelectAllOnFocus((JTextComponent)c);
}
else
{
for (Component cc : c.getComponents())
{
if (cc instanceof JTextComponent)
{
setSelectAllOnFocus((JTextComponent)cc);
break;
}
}
}
}
public static void setSelectAllOnFocus(final JTextComponent c)
{
c.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
c.selectAll();
}
});
}
public static boolean isEmpty(Object editor)
{
if (editor == null)
{
return false;
}
if (editor instanceof CComboBox)
{
final CComboBox c = (CComboBox)editor;
return c.isSelectionNone();
}
else if (editor instanceof VDate)
{
VDate c = (VDate)editor;
return c.getTimestamp() == null;
}
else if (editor instanceof VLookup)
{
VLookup c = (VLookup)editor;
return c.getValue() == null;
}
else if (editor instanceof JTextComponent)
{
JTextComponent c = (JTextComponent)editor;
return Check.isEmpty(c.getText(), true);
}
//
log.warn("Component type not supported - "+editor.getClass());
return false;
}
public static boolean isEditable(Component c)
{
if (c == null)
return false;
if (!c.isEnabled())
return false;
if (c instanceof CEditor) | return ((CEditor)c).isReadWrite();
if (c instanceof JTextComponent)
return ((JTextComponent)c).isEditable();
//
log.warn("Unknown component type - "+c.getClass());
return false;
}
public static void focusNextNotEmpty(Component component, Collection<Component> editors)
{
boolean found = false;
Component last = null;
for (Component c : editors)
{
last = c;
if (found)
{
if (isEditable(c) && isEmpty(c))
{
c.requestFocus();
return;
}
}
else if (c == component)
{
found = true;
}
}
//
if (!found)
log.warn("Component not found - "+component);
if (found && last != null)
last.requestFocus();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\form\swing\SwingFieldsUtil.java | 1 |
请完成以下Java代码 | public class RestFilter implements ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter,
ClientResponseFilter {
/** logger */
private static final Logger logger = LoggerFactory.getLogger(RestFilter.class);
@Override
public void filter(ClientRequestContext context) throws IOException {
logHttpHeaders(context.getStringHeaders());
}
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
logHttpHeaders(responseContext.getHeaders());
}
@Override
public void filter(ContainerRequestContext context) throws IOException {
logHttpHeaders(context.getHeaders());
}
@Override
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException {
logHttpHeaders(responseContext.getStringHeaders());
} | protected void logHttpHeaders(MultivaluedMap<String, String> headers) {
StringBuilder msg = new StringBuilder("The HTTP headers are: \n");
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
msg.append(entry.getKey()).append(": ");
for (int i = 0; i < entry.getValue().size(); i++) {
msg.append(entry.getValue().get(i));
if (i < entry.getValue().size() - 1) {
msg.append(", ");
}
}
msg.append("\n");
}
logger.info(msg.toString());
}
} | repos\springBoot-master\springboot-dubbo\abel-user-provider\src\main\java\cn\abel\user\filter\RestFilter.java | 1 |
请完成以下Java代码 | public boolean isPublished ()
{
Object oo = get_Value(COLUMNNAME_IsPublished);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** 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;
} | /** Set Details.
@param TextDetails Details */
public void setTextDetails (String TextDetails)
{
set_Value (COLUMNNAME_TextDetails, TextDetails);
}
/** Get Details.
@return Details */
public String getTextDetails ()
{
return (String)get_Value(COLUMNNAME_TextDetails);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Topic Action.
@param TopicAction Topic Action */
public void setTopicAction (String TopicAction)
{
set_Value (COLUMNNAME_TopicAction, TopicAction);
}
/** Get Topic Action.
@return Topic Action */
public String getTopicAction ()
{
return (String)get_Value(COLUMNNAME_TopicAction);
}
/** Set Topic Status.
@param TopicStatus Topic Status */
public void setTopicStatus (String TopicStatus)
{
set_Value (COLUMNNAME_TopicStatus, TopicStatus);
}
/** Get Topic Status.
@return Topic Status */
public String getTopicStatus ()
{
return (String)get_Value(COLUMNNAME_TopicStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Topic.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AuthorExtractor {
private final JdbcTemplate jdbcTemplate;
public AuthorExtractor(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<AuthorDto> extract() {
String sql = "SELECT a.id, a.name, a.age, b.id, b.title "
+ "FROM author a INNER JOIN book b ON a.id = b.author_id";
List<AuthorDto> result = jdbcTemplate.query(sql, (ResultSet rs) -> {
final Map<Long, AuthorDto> authorsMap = new HashMap<>();
while (rs.next()) {
Long authorId = (rs.getLong("id"));
AuthorDto author = authorsMap.get(authorId); | if (author == null) {
author = new AuthorDto(rs.getLong("id"), rs.getString("name"),
rs.getInt("age"), new ArrayList());
}
BookDto book = new BookDto(rs.getLong("id"), rs.getString("title"));
author.addBook(book);
authorsMap.putIfAbsent(author.id(), author);
}
return new ArrayList<>(authorsMap.values());
});
return result;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoRecordJbcTemplate\src\main\java\com\bookstore\jdbcTemplate\dto\AuthorExtractor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RateLimitService
{
private static Logger log = LogManager.getLogger(RateLimitService.class);
private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
public Optional<RateLimit> extractRateLimit(final HttpHeaders httpHeaders)
{
final List<String> rateLimitRemaining = httpHeaders.get(RATE_LIMIT_REMAINING.getValue());
final List<String> rateLimitReset = httpHeaders.get(RATE_LIMIT_RESET.getValue());
if (!Check.isEmpty(rateLimitRemaining) && !Check.isEmpty(rateLimitReset))
{
final int remainingReq = NumberUtils.asInteger(rateLimitRemaining.get(0), 0);
final long utcSeconds = Long.parseLong(rateLimitReset.get(0));
final LocalDateTime rateLimitResetTimestamp = LocalDateTime.ofEpochSecond(utcSeconds,0, ZoneOffset.UTC);
return Optional.of(
RateLimit.builder()
.remainingReq(remainingReq)
.resetDate(rateLimitResetTimestamp)
.build() );
}
return Optional.empty();
}
public void waitForLimitReset(final RateLimit rateLimit)
{
final long msToLimitReset = MILLIS.between(LocalDateTime.now(ZoneId.of(UTC_TIMEZONE)), rateLimit.getResetDate());
Loggables.withLogger(log, Level.DEBUG).addLog("RateLimitService.waitForLimitReset() with rateLimit: {}, and time to wait {} ms", rateLimit, msToLimitReset);
if (msToLimitReset < 0)
{
//reset timestamp is in the past
return; | }
final int maxTimeToWait = sysConfigBL.getIntValue(MAX_TIME_TO_WAIT_FOR_LIMIT_RESET.getName(),
MAX_TIME_TO_WAIT_FOR_LIMIT_RESET.getDefaultValue() );
if (msToLimitReset > maxTimeToWait)
{
throw new AdempiereException("Limit Reset is too far in the future! aborting!")
.appendParametersToMessage()
.setParameter("RateLimit", rateLimit)
.setParameter("MaxMsToWaitForLimitReset", maxTimeToWait);
}
try
{
Thread.sleep(msToLimitReset);
}
catch (final InterruptedException e)
{
throw new AdempiereException(e.getMessage(), e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.issue.tracking.github\src\main\java\de\metas\issue\tracking\github\api\v3\service\RateLimitService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getAll() {
return this.all;
}
public void setAll(String all) {
this.all = all;
}
public String getCluster() {
return this.cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getDefaultAlias() {
return this.defaultAlias;
}
public void setDefaultAlias(String defaultAlias) {
this.defaultAlias = defaultAlias;
}
public String getGateway() {
return this.gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
public String getJmx() {
return this.jmx;
}
public void setJmx(String jmx) {
this.jmx = jmx;
} | public String getLocator() {
return this.locator;
}
public void setLocator(String locator) {
this.locator = locator;
}
public String getServer() {
return this.server;
}
public void setServer(String server) {
this.server = server;
}
public String getWeb() {
return this.web;
}
public void setWeb(String web) {
this.web = web;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SslProperties.java | 2 |
请完成以下Java代码 | private ImmutableList<ImpFormatColumn> retrieveColumns(@NonNull final ImpFormatId impFormatId)
{
return Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_AD_ImpFormat_Row.class)
.addEqualsFilter(I_AD_ImpFormat_Row.COLUMNNAME_AD_ImpFormat_ID, impFormatId)
.addOnlyActiveRecordsFilter()
.orderBy(I_AD_ImpFormat_Row.COLUMNNAME_SeqNo)
.create()
.stream(I_AD_ImpFormat_Row.class)
.map(this::toImpFormatRowOrNull)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
}
private ImpFormatColumn toImpFormatRowOrNull(final I_AD_ImpFormat_Row rowRecord)
{
final I_AD_Column adColumn = rowRecord.getAD_Column();
if (!adColumn.isActive())
{ | return null;
}
return ImpFormatColumn.builder()
.name(rowRecord.getName())
.columnName(adColumn.getColumnName())
.startNo(rowRecord.getStartNo())
.endNo(rowRecord.getEndNo())
.dataType(ImpFormatColumnDataType.ofCode(rowRecord.getDataType()))
.maxLength(adColumn.getFieldLength())
.dataFormat(rowRecord.getDataFormat())
.decimalSeparator(DecimalSeparator.ofNullableStringOrDot(rowRecord.getDecimalPoint()))
.divideBy100(rowRecord.isDivideBy100())
.constantValue(rowRecord.getConstantValue())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImpFormatRepository.java | 1 |
请完成以下Java代码 | public class Consumer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
private final TransferQueue<String> transferQueue;
private final String name;
final int numberOfMessagesToConsume;
final AtomicInteger numberOfConsumedMessages = new AtomicInteger();
Consumer(TransferQueue<String> transferQueue, String name, int numberOfMessagesToConsume) {
this.transferQueue = transferQueue;
this.name = name;
this.numberOfMessagesToConsume = numberOfMessagesToConsume;
}
@Override
public void run() {
for (int i = 0; i < numberOfMessagesToConsume; i++) {
try { | LOG.debug("Consumer: " + name + " is waiting to take element...");
String element = transferQueue.take();
longProcessing(element);
LOG.debug("Consumer: " + name + " received element: " + element);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void longProcessing(String element) throws InterruptedException {
numberOfConsumedMessages.incrementAndGet();
Thread.sleep(500);
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-collections-2\src\main\java\com\baeldung\transferqueue\Consumer.java | 1 |
请完成以下Java代码 | public static boolean isCompensationThrowing(PvmExecutionImpl execution, Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping) {
if (CompensationBehavior.isCompensationThrowing(execution)) {
ScopeImpl compensationThrowingActivity = execution.getActivity();
if (compensationThrowingActivity.isScope()) {
return activityExecutionMapping.get(compensationThrowingActivity) ==
activityExecutionMapping.get(compensationThrowingActivity.getFlowScope());
}
else {
// for transaction sub processes with cancel end events, the compensation throwing execution waits in the boundary event, not in the end
// event; cancel boundary events are currently not scope
return compensationThrowingActivity.getActivityBehavior() instanceof CancelBoundaryEventActivityBehavior;
}
}
else {
return false;
}
}
public static boolean isCompensationThrowing(PvmExecutionImpl execution) {
return isCompensationThrowing(execution, execution.createActivityExecutionMapping());
}
protected static PvmExecutionImpl findCompensationThrowingAncestorExecution(PvmExecutionImpl execution) {
ExecutionWalker walker = new ExecutionWalker(execution);
walker.walkUntil(new ReferenceWalker.WalkCondition<PvmExecutionImpl>() {
public boolean isFulfilled(PvmExecutionImpl element) {
return element == null || CompensationBehavior.isCompensationThrowing(element);
}
});
return walker.getCurrentElement();
}
/**
* See #CAM-10978
* Use case process instance with <code>asyncBefore</code> startEvent
* After unifying the history variable's creation<br>
* The following changed:<br>
* * variables will receive the <code>processInstanceId</code> as <code>activityInstanceId</code> in such cases (previously was the startEvent id)<br>
* * historic details have new <code>initial</code> property to track initial variables that process is started with<br> | * The jobs created prior <code>7.13</code> and not executed before do not have historic information of variables.
* This method takes care of that.
*/
public static void createMissingHistoricVariables(PvmExecutionImpl execution) {
Collection<VariableInstanceEntity> variables = ((ExecutionEntity) execution).getVariablesInternal();
if (variables != null && variables.size() > 0) {
// trigger historic creation if the history is not presented already
for (VariableInstanceEntity variable : variables) {
if (variable.wasCreatedBefore713()) {
VariableInstanceHistoryListener.INSTANCE.onCreate(variable, variable.getExecution());
}
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\LegacyBehavior.java | 1 |
请完成以下Java代码 | public UserQuery createUserQuery() {
return getIdmIdentityService().createUserQuery();
}
@Override
public NativeUserQuery createNativeUserQuery() {
return getIdmIdentityService().createNativeUserQuery();
}
@Override
public GroupQuery createGroupQuery() {
return getIdmIdentityService().createGroupQuery();
}
@Override
public NativeGroupQuery createNativeGroupQuery() {
return getIdmIdentityService().createNativeGroupQuery();
}
@Override
public List<Group> getPotentialStarterGroups(String processDefinitionId) {
return commandExecutor.execute(new GetPotentialStarterGroupsCmd(processDefinitionId));
}
@Override
public List<User> getPotentialStarterUsers(String processDefinitionId) {
return commandExecutor.execute(new GetPotentialStarterUsersCmd(processDefinitionId));
}
@Override
public void createMembership(String userId, String groupId) {
getIdmIdentityService().createMembership(userId, groupId);
}
@Override
public void deleteGroup(String groupId) {
getIdmIdentityService().deleteGroup(groupId);
}
@Override
public void deleteMembership(String userId, String groupId) {
getIdmIdentityService().deleteMembership(userId, groupId);
}
@Override
public boolean checkPassword(String userId, String password) {
return getIdmIdentityService().checkPassword(userId, password);
}
@Override | public void deleteUser(String userId) {
getIdmIdentityService().deleteUser(userId);
}
@Override
public void setUserPicture(String userId, Picture picture) {
getIdmIdentityService().setUserPicture(userId, picture);
}
@Override
public Picture getUserPicture(String userId) {
return getIdmIdentityService().getUserPicture(userId);
}
@Override
public void setAuthenticatedUserId(String authenticatedUserId) {
Authentication.setAuthenticatedUserId(authenticatedUserId);
}
@Override
public String getUserInfo(String userId, String key) {
return getIdmIdentityService().getUserInfo(userId, key);
}
@Override
public List<String> getUserInfoKeys(String userId) {
return getIdmIdentityService().getUserInfoKeys(userId);
}
@Override
public void setUserInfo(String userId, String key, String value) {
getIdmIdentityService().setUserInfo(userId, key, value);
}
@Override
public void deleteUserInfo(String userId, String key) {
getIdmIdentityService().deleteUserInfo(userId, key);
}
protected IdmIdentityService getIdmIdentityService() {
IdmIdentityService idmIdentityService = EngineServiceUtil.getIdmIdentityService(configuration);
if (idmIdentityService == null) {
throw new FlowableException("Trying to use idm identity service when it is not initialized");
}
return idmIdentityService;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\IdentityServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ReceiptScheduleExternalInfo
{
@Nullable
LocalDate movementDate;
@Nullable
LocalDate dateAcct;
@Nullable
ZonedDateTime dateReceived;
@Nullable
String externalId;
@Builder
public ReceiptScheduleExternalInfo(@Nullable final LocalDate movementDate, | @Nullable final LocalDate dateAcct,
@Nullable final ZonedDateTime dateReceived,
@Nullable final String externalId)
{
if (movementDate == null && dateReceived == null && Check.isBlank(externalId))
{
throw new AdempiereException("Empty object!");
}
this.movementDate = movementDate;
this.dateAcct = dateAcct;
this.dateReceived = dateReceived;
this.externalId = externalId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleExternalInfo.java | 2 |
请完成以下Java代码 | public static void setSelectAllOnFocus(final JTextComponent c)
{
c.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
c.selectAll();
}
});
}
public static boolean isEmpty(Object editor)
{
if (editor == null)
{
return false;
}
if (editor instanceof CComboBox)
{
final CComboBox c = (CComboBox)editor;
return c.isSelectionNone();
}
else if (editor instanceof VDate)
{
VDate c = (VDate)editor;
return c.getTimestamp() == null;
}
else if (editor instanceof VLookup)
{
VLookup c = (VLookup)editor;
return c.getValue() == null;
}
else if (editor instanceof JTextComponent)
{
JTextComponent c = (JTextComponent)editor;
return Check.isEmpty(c.getText(), true);
}
//
log.warn("Component type not supported - "+editor.getClass());
return false;
}
public static boolean isEditable(Component c)
{
if (c == null)
return false;
if (!c.isEnabled())
return false;
if (c instanceof CEditor)
return ((CEditor)c).isReadWrite();
if (c instanceof JTextComponent)
return ((JTextComponent)c).isEditable();
// | log.warn("Unknown component type - "+c.getClass());
return false;
}
public static void focusNextNotEmpty(Component component, Collection<Component> editors)
{
boolean found = false;
Component last = null;
for (Component c : editors)
{
last = c;
if (found)
{
if (isEditable(c) && isEmpty(c))
{
c.requestFocus();
return;
}
}
else if (c == component)
{
found = true;
}
}
//
if (!found)
log.warn("Component not found - "+component);
if (found && last != null)
last.requestFocus();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\form\swing\SwingFieldsUtil.java | 1 |
请完成以下Java代码 | public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@ManyToMany(cascade = CascadeType.MERGE)
@JoinTable(
name = "user_role",
joinColumns = {@JoinColumn(name = "USER_ID", referencedColumnName = "ID")},
inverseJoinColumns = {@JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")})
private List<Role> roles;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name; | }
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\SpringSecurity\src\main\java\spring\security\entities\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BpartnerProductRestController
{
private final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class);
private final IBPartnerProductDAO bpartnerProductsRepo = Services.get(IBPartnerProductDAO.class);
private final IProductBL productsService = Services.get(IProductBL.class);
@ApiOperation("For a BPartner's name and that partner's specific product-number or product-name, this operation returns the product's metasfresh search-key (i.e. `M_Product.Value`).<br>"
+ "Note that the respective `C_BPartner_Product` record needs to be flagged with `UsedForCustomer='Y'` to be found by this operation.")
@GetMapping("/query")
public ResponseEntity<JsonBPartnerProductResult> getByCustomerProductNo(
@ApiParam("`C_BPartner.Name` of the bpartner in question.")
@RequestParam("customerName") final String customerName,
@ApiParam("`C_BPartner_Product.ProductNo` or `.ProductName`.")
@RequestParam("customerProduct") final String customerProductSearchString)
{
final BPartnerId customerId = findCustomerId(customerName).orElse(null);
if (customerId == null)
{
return JsonBPartnerProductResult.notFound(trl("@NotFound@ @C_BPartner_ID@"));
}
final ProductId productId = findProductId(customerId, customerProductSearchString).orElse(null);
if (productId == null)
{
return JsonBPartnerProductResult.notFound(trl("@NotFound@ @M_Product_ID@"));
}
return JsonBPartnerProductResult.ok(JsonBPartnerProduct.builder()
.productNo(productsService.getProductValue(productId))
.build());
}
private Optional<BPartnerId> findCustomerId(final String customerName) | {
return bpartnersRepo.retrieveBPartnerIdBy(BPartnerQuery.builder()
.bpartnerName(customerName)
.build());
}
private Optional<ProductId> findProductId(final BPartnerId customerId, final String customerProductSearchString)
{
final Optional<ProductId> productIdByProductNo = bpartnerProductsRepo.getProductIdByCustomerProductNo(customerId, customerProductSearchString);
if (productIdByProductNo.isPresent())
{
return productIdByProductNo;
}
final Optional<ProductId> productIdByProductName = bpartnerProductsRepo.getProductIdByCustomerProductName(customerId, customerProductSearchString);
if (productIdByProductName.isPresent())
{
return productIdByProductName;
}
return Optional.empty();
}
private String trl(final String message)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
return msgBL.parseTranslation(RestApiUtilsV1.getAdLanguage(), message);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\bpartner_product\impl\BpartnerProductRestController.java | 2 |
请完成以下Java代码 | public I_M_Material_Tracking getMaterialTracking(final IContextAware context, final IAttributeSet attributeSet)
{
final int materialTrackingId = getMaterialTrackingId(context, attributeSet);
if (materialTrackingId <= 0)
{
return null;
}
final I_M_Material_Tracking materialTracking = InterfaceWrapperHelper.create(context.getCtx(), materialTrackingId, I_M_Material_Tracking.class, context.getTrxName());
Check.assume(materialTracking != null && materialTracking.getM_Material_Tracking_ID() == materialTrackingId,
"Material tracking record shall exist for ID={}", materialTrackingId);
return materialTracking;
}
@Override
public boolean isMaterialTrackingSet(final IContextAware context, final IAttributeSet attributeSet)
{
final int materialTrackingId = getMaterialTrackingId(context, attributeSet);
return materialTrackingId > 0;
}
private int getMaterialTrackingId(final IContextAware context, final IAttributeSet attributeSet)
{
if (!attributeSet.hasAttribute(M_Attribute_Value_MaterialTracking))
{
return -1;
}
final Object materialTrackingIdObj = attributeSet.getValue(M_Attribute_Value_MaterialTracking);
if (materialTrackingIdObj == null)
{
return -1; | }
final String materialTrackingIdStr = materialTrackingIdObj.toString();
return getMaterialTrackingIdFromMaterialTrackingIdStr(materialTrackingIdStr);
}
@Override
public boolean hasMaterialTrackingAttribute(@NonNull final AttributeSetInstanceId asiId)
{
if (asiId.isNone())
{
return false;
}
final Optional<AttributeId> materialTrackingAttributeId = getMaterialTrackingAttributeId();
if (!materialTrackingAttributeId.isPresent())
{
return false;
}
final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class);
final I_M_AttributeInstance materialTrackingAttributeInstance = asiBL.getAttributeInstance(asiId, materialTrackingAttributeId.get());
return materialTrackingAttributeInstance != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingAttributeBL.java | 1 |
请完成以下Java代码 | public java.lang.String getSecretKey_2FA()
{
return get_ValueAsString(COLUMNNAME_SecretKey_2FA);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSupervisor_ID (final int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Supervisor_ID);
}
@Override
public int getSupervisor_ID()
{
return get_ValueAsInt(COLUMNNAME_Supervisor_ID);
}
@Override
public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp)
{
throw new IllegalArgumentException ("Timestamp is virtual column"); }
@Override
public java.sql.Timestamp getTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_Timestamp);
}
@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);
}
@Override
public void setUnlockAccount (final @Nullable java.lang.String UnlockAccount)
{
set_Value (COLUMNNAME_UnlockAccount, UnlockAccount);
}
@Override
public java.lang.String getUnlockAccount()
{
return get_ValueAsString(COLUMNNAME_UnlockAccount);
}
@Override
public void setUserPIN (final @Nullable java.lang.String UserPIN)
{
set_Value (COLUMNNAME_UserPIN, UserPIN);
}
@Override
public java.lang.String getUserPIN()
{
return get_ValueAsString(COLUMNNAME_UserPIN);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User.java | 1 |
请完成以下Java代码 | public void setP_TradeDiscountRec_Acct (int P_TradeDiscountRec_Acct)
{
set_Value (COLUMNNAME_P_TradeDiscountRec_Acct, Integer.valueOf(P_TradeDiscountRec_Acct));
}
/** Get Trade Discount Received.
@return Trade Discount Receivable Account
*/
@Override
public int getP_TradeDiscountRec_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_TradeDiscountRec_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getP_UsageVariance_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_P_UsageVariance_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setP_UsageVariance_A(org.compiere.model.I_C_ValidCombination P_UsageVariance_A)
{
set_ValueFromPO(COLUMNNAME_P_UsageVariance_Acct, org.compiere.model.I_C_ValidCombination.class, P_UsageVariance_A);
}
/** Set Usage Variance.
@param P_UsageVariance_Acct
The Usage Variance account is the account used Manufacturing Order
*/
@Override
public void setP_UsageVariance_Acct (int P_UsageVariance_Acct)
{
set_Value (COLUMNNAME_P_UsageVariance_Acct, Integer.valueOf(P_UsageVariance_Acct));
}
/** Get Usage Variance.
@return The Usage Variance account is the account used Manufacturing Order
*/
@Override
public int getP_UsageVariance_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_UsageVariance_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getP_WIP_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class); | }
@Override
public void setP_WIP_A(org.compiere.model.I_C_ValidCombination P_WIP_A)
{
set_ValueFromPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, P_WIP_A);
}
/** Set Work In Process.
@param P_WIP_Acct
The Work in Process account is the account used Manufacturing Order
*/
@Override
public void setP_WIP_Acct (int P_WIP_Acct)
{
set_Value (COLUMNNAME_P_WIP_Acct, Integer.valueOf(P_WIP_Acct));
}
/** Get Work In Process.
@return The Work in Process account is the account used Manufacturing Order
*/
@Override
public int getP_WIP_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_WIP_Acct);
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_M_Product_Acct.java | 1 |
请完成以下Java代码 | private static final class LaneCardsSequence
{
private final int laneId;
private final List<Integer> cardIds;
public LaneCardsSequence(final int laneId, final List<Integer> cardIds)
{
this.laneId = laneId;
this.cardIds = new ArrayList<>(cardIds);
}
public LaneCardsSequence copy()
{
return new LaneCardsSequence(laneId, cardIds);
}
public int getLaneId()
{
return laneId;
}
private List<Integer> getCardIds()
{
return cardIds;
}
public void addCardIdAtPosition(final int cardId, final int position)
{
Preconditions.checkArgument(cardId > 0, "cardId > 0");
if (position < 0)
{
cardIds.remove((Object)cardId);
cardIds.add(cardId);
}
else if (position == Integer.MAX_VALUE || position > cardIds.size() - 1)
{ | cardIds.remove((Object)cardId);
cardIds.add(cardId);
}
else
{
cardIds.remove((Object)cardId);
cardIds.add(position, cardId);
}
}
public void removeCardId(final int cardId)
{
Preconditions.checkArgument(cardId > 0, "cardId > 0");
cardIds.remove((Object)cardId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\board\BoardDescriptorRepository.java | 1 |
请完成以下Java代码 | public int compare(final IQualityInspectionLine line1, final IQualityInspectionLine line2)
{
final int index1 = getIndex(line1);
final int index2 = getIndex(line2);
return index1 - index2;
}
private final int getIndex(final IQualityInspectionLine line)
{
Check.assumeNotNull(line, "line not null");
final QualityInspectionLineType type = line.getQualityInspectionLineType();
final Integer index = type2index.get(type);
if (index == null)
{
return INDEX_NotFound;
}
return index;
}
private final boolean hasType(final QualityInspectionLineType type)
{
return type2index.containsKey(type);
}
/**
* Remove from given lines those which their type is not specified in our list.
*
* NOTE: we assume the list is read-write.
*
* @param lines
*/
public void filter(final List<IQualityInspectionLine> lines)
{
for (final Iterator<IQualityInspectionLine> it = lines.iterator(); it.hasNext();)
{
final IQualityInspectionLine line = it.next();
final QualityInspectionLineType type = line.getQualityInspectionLineType();
if (!hasType(type))
{
it.remove(); | }
}
}
/**
* Sort given lines with this comparator.
*
* NOTE: we assume the list is read-write.
*
* @param lines
*/
public void sort(final List<IQualityInspectionLine> lines)
{
Collections.sort(lines, this);
}
/**
* Remove from given lines those which their type is not specified in our list. Then sort the result.
*
* NOTE: we assume the list is read-write.
*
* @param lines
*/
public void filterAndSort(final List<IQualityInspectionLine> lines)
{
filter(lines);
sort(lines);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\QualityInspectionLineByTypeComparator.java | 1 |
请完成以下Java代码 | public Builder setWidgetType(final DocumentFieldWidgetType widgetType)
{
this._widgetType = widgetType;
return this;
}
private DocumentFieldWidgetType getWidgetType()
{
Check.assumeNotNull(_widgetType, "Parameter widgetType is not null");
return _widgetType;
}
public Builder setMinPrecision(@NonNull final OptionalInt minPrecision)
{
this.minPrecision = minPrecision;
return this;
}
private OptionalInt getMinPrecision()
{
return minPrecision;
}
public Builder setSqlValueClass(final Class<?> sqlValueClass)
{
this._sqlValueClass = sqlValueClass;
return this;
}
private Class<?> getSqlValueClass()
{
if (_sqlValueClass != null)
{
return _sqlValueClass;
}
return getValueClass();
}
public Builder setLookupDescriptor(@Nullable final LookupDescriptor lookupDescriptor)
{
this._lookupDescriptor = lookupDescriptor;
return this;
}
public OptionalBoolean getNumericKey()
{
return _numericKey;
}
public Builder setKeyColumn(final boolean keyColumn)
{
this.keyColumn = keyColumn;
return this; | }
public Builder setEncrypted(final boolean encrypted)
{
this.encrypted = encrypted;
return this;
}
/**
* Sets ORDER BY priority and direction (ascending/descending)
*
* @param priority priority; if positive then direction will be ascending; if negative then direction will be descending
*/
public Builder setDefaultOrderBy(final int priority)
{
if (priority >= 0)
{
orderByPriority = priority;
orderByAscending = true;
}
else
{
orderByPriority = -priority;
orderByAscending = false;
}
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentFieldDataBindingDescriptor.java | 1 |
请完成以下Java代码 | public String getCustomerAddress() {return packageable.getCustomerAddress();}
public @NonNull InstantAndOrgId getPreparationDate() {return packageable.getPreparationDate();}
public @NonNull InstantAndOrgId getDeliveryDate() {return packageable.getDeliveryDate();}
public @Nullable OrderId getSalesOrderId() {return packageable.getSalesOrderId();}
public @Nullable String getSalesOrderDocumentNo() {return packageable.getSalesOrderDocumentNo();}
public @Nullable OrderAndLineId getSalesOrderAndLineIdOrNull() {return packageable.getSalesOrderAndLineIdOrNull();}
public @Nullable WarehouseTypeId getWarehouseTypeId() {return packageable.getWarehouseTypeId();}
public boolean isPartiallyPickedOrDelivered()
{
return packageable.getQtyPickedPlanned().signum() != 0
|| packageable.getQtyPickedNotDelivered().signum() != 0
|| packageable.getQtyPickedAndDelivered().signum() != 0;
}
public @NonNull ProductId getProductId() {return packageable.getProductId();}
public @NonNull String getProductName() {return packageable.getProductName();}
public @NonNull I_C_UOM getUOM() {return getQtyToDeliver().getUOM();}
public @NonNull Quantity getQtyToDeliver()
{ | return schedule != null
? schedule.getQtyToPick()
: packageable.getQtyToDeliver();
}
public @NonNull HUPIItemProductId getPackToHUPIItemProductId() {return packageable.getPackToHUPIItemProductId();}
public @NonNull Quantity getQtyToPick()
{
return schedule != null
? schedule.getQtyToPick()
: packageable.getQtyToPick();
}
public @Nullable UomId getCatchWeightUomId() {return packageable.getCatchWeightUomId();}
public @Nullable PPOrderId getPickFromOrderId() {return packageable.getPickFromOrderId();}
public @Nullable ShipperId getShipperId() {return packageable.getShipperId();}
public @NonNull AttributeSetInstanceId getAsiId() {return packageable.getAsiId();}
public Optional<ShipmentAllocationBestBeforePolicy> getBestBeforePolicy() {return packageable.getBestBeforePolicy();}
public @NonNull WarehouseId getWarehouseId() {return packageable.getWarehouseId();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageable.java | 1 |
请完成以下Java代码 | private Mono<CompleteMultipartUploadResponse> completeUpload(UploadState state) {
log.info("[I202] completeUpload: bucket={}, filekey={}, completedParts.size={}", state.bucket, state.filekey, state.completedParts.size());
CompletedMultipartUpload multipartUpload = CompletedMultipartUpload.builder()
.parts(state.completedParts.values())
.build();
return Mono.fromFuture(s3client.completeMultipartUpload(CompleteMultipartUploadRequest.builder()
.bucket(state.bucket)
.uploadId(state.uploadId)
.multipartUpload(multipartUpload)
.key(state.filekey)
.build()));
}
/**
* check result from an API call.
* @param result Result from an API call
*/
private static void checkResult(SdkResponse result) {
if (result.sdkHttpResponse() == null || !result.sdkHttpResponse().isSuccessful()) {
throw new UploadFailedException(result);
}
}
/**
* Holds upload state during a multipart upload
*/
static class UploadState { | final String bucket;
final String filekey;
String uploadId;
int partCounter;
Map<Integer, CompletedPart> completedParts = new HashMap<>();
int buffered = 0;
UploadState(String bucket, String filekey) {
this.bucket = bucket;
this.filekey = filekey;
}
}
} | repos\tutorials-master\aws-modules\aws-reactive\src\main\java\com\baeldung\aws\reactive\s3\UploadResource.java | 1 |
请完成以下Java代码 | public final class OidcScopes {
/**
* The {@code openid} scope is required for OpenID Connect Authentication Requests.
*/
public static final String OPENID = "openid";
/**
* The {@code profile} scope requests access to the default profile claims, which are:
* {@code name, family_name, given_name, middle_name, nickname, preferred_username,
* profile, picture, website, gender, birthdate, zoneinfo, locale, updated_at}.
*/
public static final String PROFILE = "profile";
/**
* The {@code email} scope requests access to the {@code email} and
* {@code email_verified} claims.
*/
public static final String EMAIL = "email"; | /**
* The {@code address} scope requests access to the {@code address} claim.
*/
public static final String ADDRESS = "address";
/**
* The {@code phone} scope requests access to the {@code phone_number} and
* {@code phone_number_verified} claims.
*/
public static final String PHONE = "phone";
private OidcScopes() {
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\OidcScopes.java | 1 |
请完成以下Java代码 | public Message getByAdMessage(@NonNull final String adMessage)
{
return getByAdMessage(AdMessageKey.of(adMessage));
}
@Nullable
public Message getByAdMessage(@NonNull final AdMessageKey adMessage)
{
return byAdMessage.get(adMessage);
}
public Stream<Message> stream() {return byAdMessage.values().stream();}
public Map<String, String> toStringMap(final String adLanguage, final String prefix, boolean removePrefix)
{
final Function<Message, String> keyFunction;
if (removePrefix)
{
final int beginIndex = prefix.length();
keyFunction = message -> message.getAdMessage().toAD_Message().substring(beginIndex);
}
else
{
keyFunction = message -> message.getAdMessage().toAD_Message();
} | return stream()
.filter(message -> message.getAdMessage().startsWith(prefix))
.collect(ImmutableMap.toImmutableMap(keyFunction, message -> message.getMsgText(adLanguage)));
}
public Optional<Message> getById(@NonNull final AdMessageId adMessageId)
{
return Optional.ofNullable(byId.get(adMessageId));
}
public Optional<AdMessageKey> getAdMessageKeyById(final AdMessageId adMessageId)
{
return getById(adMessageId).map(Message::getAdMessage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\MessagesMap.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductAvailableStocks
{
// Services
@NonNull final IHandlingUnitsBL handlingUnitsBL;
// Params
@NonNull final ImmutableSet<LocatorId> pickFromLocatorIds;
// State
@NonNull private final HashMap<ProductId, ProductAvailableStock> map = new HashMap<>();
@Builder(access = AccessLevel.PACKAGE)
private ProductAvailableStocks(
@NonNull final IHandlingUnitsBL handlingUnitsBL,
@NonNull final Set<LocatorId> pickFromLocatorIds)
{
Check.assumeNotEmpty(pickFromLocatorIds, "pickFromLocatorIds shall not be empty");
this.handlingUnitsBL = handlingUnitsBL;
this.pickFromLocatorIds = ImmutableSet.copyOf(pickFromLocatorIds);
}
public PickingJobCandidate allocate(PickingJobCandidate job)
{
final PickingJobCandidateProducts products = job.getProducts()
.updatingEachProduct(this::allocate);
return job.withProducts(products);
}
public PickingJobReference allocate(PickingJobReference job)
{
final PickingJobCandidateProducts products = job.getProducts()
.updatingEachProduct(this::allocate);
return job.withProducts(products);
}
private PickingJobCandidateProduct allocate(final PickingJobCandidateProduct product)
{
final Quantity qtyToDeliver = product.getQtyToDeliver();
if (qtyToDeliver == null)
{
return product;
}
final ProductId productId = product.getProductId();
final Quantity qtyAvailableToPick = allocateQty(productId, qtyToDeliver);
return product.withQtyAvailableToPick(qtyAvailableToPick);
}
public Quantity allocateQty(@NonNull final ProductId productId, @NonNull final Quantity qtyToDeliver)
{
return getByProductId(productId)
.allocateQty(qtyToDeliver)
.toZeroIfNegative();
}
private ProductAvailableStock getByProductId(final ProductId productId)
{
return CollectionUtils.getOrLoad(map, productId, this::loadByProductIds);
}
public void warmUpByProductIds(final Set<ProductId> productIds) | {
CollectionUtils.getAllOrLoad(map, productIds, this::loadByProductIds);
}
private Map<ProductId, ProductAvailableStock> loadByProductIds(final Set<ProductId> productIds)
{
final HashMap<ProductId, ProductAvailableStock> result = new HashMap<>();
productIds.forEach(productId -> result.put(productId, new ProductAvailableStock()));
streamHUProductStorages(productIds)
.forEach(huStorageProduct -> result.get(huStorageProduct.getProductId()).addQtyOnHand(huStorageProduct.getQty()));
return result;
}
private Stream<IHUProductStorage> streamHUProductStorages(final Set<ProductId> productIds)
{
final List<I_M_HU> hus = handlingUnitsBL.createHUQueryBuilder()
.onlyContextClient(false) // fails when running from non-context threads like websockets value producers
.addOnlyWithProductIds(productIds)
.addOnlyInLocatorIds(pickFromLocatorIds)
.setOnlyActiveHUs(true)
.list();
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
return storageFactory.streamHUProductStorages(hus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\hu\ProductAvailableStocks.java | 2 |
请完成以下Java代码 | public boolean isAsync(PvmExecutionImpl execution) {
return false;
}
public boolean isAsyncCapable() {
return false;
}
public void execute(PvmExecutionImpl execution) {
PvmExecutionImpl nextLeaf;
do {
nextLeaf = findNextLeaf(execution);
// nextLeaf can already be removed, if it was the concurrent parent of the previous leaf.
// In that case, DELETE_CASCADE_FIRE_ACTIVITY_END on the previousLeaf already removed
// nextLeaf, so calling DELETE_CASCADE_FIRE_ACTIVITY_END again would incorrectly
// invoke execution listeners
if (nextLeaf.isDeleteRoot() && nextLeaf.isRemoved()) {
return;
}
// propagate properties
PvmExecutionImpl deleteRoot = getDeleteRoot(execution);
if (deleteRoot != null) {
nextLeaf.setSkipCustomListeners(deleteRoot.isSkipCustomListeners());
nextLeaf.setSkipIoMappings(deleteRoot.isSkipIoMappings());
nextLeaf.setExternallyTerminated(deleteRoot.isExternallyTerminated());
}
PvmExecutionImpl subProcessInstance = nextLeaf.getSubProcessInstance();
if (subProcessInstance != null) {
if (deleteRoot.isSkipSubprocesses()) {
subProcessInstance.setSuperExecution(null);
} else {
subProcessInstance.deleteCascade(execution.getDeleteReason(), nextLeaf.isSkipCustomListeners(), nextLeaf.isSkipIoMappings(),
nextLeaf.isExternallyTerminated(), nextLeaf.isSkipSubprocesses());
}
}
nextLeaf.performOperation(DELETE_CASCADE_FIRE_ACTIVITY_END); | } while (!nextLeaf.isDeleteRoot());
}
protected PvmExecutionImpl findNextLeaf(PvmExecutionImpl execution) {
if (execution.hasChildren()) {
return findNextLeaf(execution.getExecutions().get(0));
}
return execution;
}
protected PvmExecutionImpl getDeleteRoot(PvmExecutionImpl execution) {
if(execution == null) {
return null;
} else if(execution.isDeleteRoot()) {
return execution;
} else {
return getDeleteRoot(execution.getParent());
}
}
public String getCanonicalName() {
return "delete-cascade";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationDeleteCascade.java | 1 |
请完成以下Java代码 | public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getSelector() {
return selector;
}
public void setSelector(String selector) {
this.selector = selector;
}
public String getSubscription() { | return subscription;
}
public void setSubscription(String subscription) {
this.subscription = subscription;
}
public String getConcurrency() {
return concurrency;
}
public void setConcurrency(String concurrency) {
this.concurrency = concurrency;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\JmsInboundChannelModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TaskModelAutoConfiguration {
//this bean will be automatically injected inside boot's ObjectMapper
@Bean
public Module customizeTaskModelObjectMapper() {
SimpleModule module = new SimpleModule("mapTaskRuntimeInterfaces", Version.unknownVersion());
SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver() {
//this is a workaround for https://github.com/FasterXML/jackson-databind/issues/2019
//once version 2.9.6 is related we can remove this @override method
@Override
public JavaType resolveAbstractType(DeserializationConfig config, BeanDescription typeDesc) {
return findTypeMapping(config, typeDesc.getType());
}
};
resolver.addMapping(Task.class, TaskImpl.class);
resolver.addMapping(TaskCandidateUser.class, TaskCandidateUserImpl.class);
resolver.addMapping(TaskCandidateGroup.class, TaskCandidateGroupImpl.class);
module.registerSubtypes(new NamedType(TaskResult.class, TaskResult.class.getSimpleName()));
module.registerSubtypes(new NamedType(ClaimTaskPayload.class, ClaimTaskPayload.class.getSimpleName()));
module.registerSubtypes(new NamedType(CompleteTaskPayload.class, CompleteTaskPayload.class.getSimpleName()));
module.registerSubtypes(new NamedType(SaveTaskPayload.class, SaveTaskPayload.class.getSimpleName()));
module.registerSubtypes(new NamedType(CreateTaskPayload.class, CreateTaskPayload.class.getSimpleName())); | module.registerSubtypes(new NamedType(DeleteTaskPayload.class, DeleteTaskPayload.class.getSimpleName()));
module.registerSubtypes(new NamedType(GetTasksPayload.class, GetTasksPayload.class.getSimpleName()));
module.registerSubtypes(
new NamedType(GetTaskVariablesPayload.class, GetTaskVariablesPayload.class.getSimpleName())
);
module.registerSubtypes(new NamedType(ReleaseTaskPayload.class, ReleaseTaskPayload.class.getSimpleName()));
module.registerSubtypes(new NamedType(UpdateTaskPayload.class, UpdateTaskPayload.class.getSimpleName()));
module.setAbstractTypes(resolver);
return module;
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-model-impl\src\main\java\org\activiti\api\task\conf\impl\TaskModelAutoConfiguration.java | 2 |
请完成以下Java代码 | public void setMacro (String Macro)
{
set_Value (COLUMNNAME_Macro, Macro);
}
/** Get Macro.
@return Macro
*/
public String getMacro ()
{
return (String)get_Value(COLUMNNAME_Macro);
}
/** 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 Sql SELECT.
@param SelectClause
SQL SELECT clause
*/
public void setSelectClause (String SelectClause)
{
set_Value (COLUMNNAME_SelectClause, SelectClause);
}
/** Get Sql SELECT.
@return SQL SELECT clause
*/
public String getSelectClause ()
{
return (String)get_Value(COLUMNNAME_SelectClause);
}
/** TokenType AD_Reference_ID=397 */
public static final int TOKENTYPE_AD_Reference_ID=397;
/** SQL Command = Q */
public static final String TOKENTYPE_SQLCommand = "Q";
/** Internal Link = I */
public static final String TOKENTYPE_InternalLink = "I";
/** External Link = E */
public static final String TOKENTYPE_ExternalLink = "E";
/** Style = S */
public static final String TOKENTYPE_Style = "S";
/** Set TokenType. | @param TokenType
Wiki Token Type
*/
public void setTokenType (String TokenType)
{
set_Value (COLUMNNAME_TokenType, TokenType);
}
/** Get TokenType.
@return Wiki Token Type
*/
public String getTokenType ()
{
return (String)get_Value(COLUMNNAME_TokenType);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WikiToken.java | 1 |
请完成以下Java代码 | public void run(String... args) {
LOGGER.info("WITH JDBC TEMPLATE APPROACH...");
LOGGER.info("Student id 10001 -> {}", repository.findById(10001L));
LOGGER.info("Inserting -> {}", repository.insert(new Student(10010L, "John", "A1234657")));
LOGGER.info("Update 10003 -> {}", repository.update(new Student(10001L, "Name-Updated", "New-Passport")));
repository.deleteById(10002L);
LOGGER.info("All users -> {}", repository.findAll());
LOGGER.info("With Json format users -> {}", repository.findAll());
// repository.findAll().forEach(student -> System.out.println(student.toJSON())); | LOGGER.info("WITH JDBC CLIENT APPROACH...");
LOGGER.info("Student id 10001 -> {}", jdbcClientRepository.findById(10001L));
LOGGER.info("Inserting -> {}", jdbcClientRepository.insert(new Student(10011L, "Ranga", "R1234657")));
LOGGER.info("Update 10011 -> {}", jdbcClientRepository.update(new Student(10011L, "Ranga Karanam", "New-Passport")));
jdbcClientRepository.deleteById(10002L);
LOGGER.info("All users -> {}", jdbcClientRepository.findAll());
}
} | repos\spring-boot-examples-master\spring-boot-2-jdbc-with-h2\src\main\java\com\in28minutes\springboot\jdbc\h2\example\SpringBoot2JdbcWithH2Application.java | 1 |
请完成以下Java代码 | private void process(
@NonNull final SecurPharmProduct product,
@NonNull final Action action,
@NonNull final InventoryId inventoryId)
{
if (action == Action.DECOMMISSION)
{
securPharmService.decommissionProductIfEligible(product, inventoryId);
}
else if (action == Action.UNDO_DECOMMISSION)
{
securPharmService.undoDecommissionProductIfEligible(product, inventoryId);
}
else
{
throw new AdempiereException("Invalid action: " + action);
}
}
private Action getActionToRun(@NonNull final InventoryId inventoryId)
{
final DocStatus inventoryDocStatus = Services.get(IInventoryBL.class).getDocStatus(inventoryId);
if (DocStatus.Completed.equals(inventoryDocStatus))
{
return Action.DECOMMISSION;
}
else if (DocStatus.Reversed.equals(inventoryDocStatus))
{
return Action.UNDO_DECOMMISSION;
}
else
{
return null;
}
} | private enum Action
{
DECOMMISSION, UNDO_DECOMMISSION
}
@Value
@Builder
private static class ProductsToProcess
{
@NonNull
Action action;
@NonNull
InventoryId inventoryId;
@NonNull
@Singular
ImmutableList<SecurPharmProduct> products;
public boolean isEmpty()
{
return getProducts().isEmpty();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\process\M_Inventory_SecurpharmActionRetry.java | 1 |
请完成以下Java代码 | public File save(byte[] bytes,String name) throws IOException {
File newFile = new File(FILE_PATH + File.separator + name);
if(!newFile.exists()){
newFile.createNewFile();
}
IOUtils.write(bytes,new FileOutputStream(newFile));
return img2txt(newFile);
}
private File img2txt(File file) throws IOException {
BufferedImage image = ImageIO.read(file);
BufferedImage scaled = getScaledImg(image);
char[][] array = getImageMatrix(scaled);
StringBuffer sb = new StringBuffer();
for (char[] cs : array) {
for (char c : cs) {
sb.append(c);
// System.out.print(c);
}
sb.append("\r\n");
// System.out.println();
}
String outName = file.getAbsolutePath() + ".txt";
File outFile = new File(outName);
IOUtils.write(sb.toString(), new FileOutputStream(outFile));
return outFile;
}
private static char[][] getImageMatrix(BufferedImage img) { | int w = img.getWidth(), h = img.getHeight();
char[][] rst = new char[w][h];
for (int i = 0; i < w; i++)
for (int j = 0; j < h; j++) {
int rgb = img.getRGB(i, j);
// 注意溢出
int r = Integer.valueOf(Integer.toBinaryString(rgb).substring(0, 8), 2);
int g = (rgb & 0xff00) >> 8;
int b = rgb & 0xff;
int gray = (int) (0.2126 * r + 0.7152 * g + 0.0722 * b);
// 把int gray转换成char
int len = toChar.length();
int base = 256 / len + 1;
int charIdx = gray / base;
rst[j][i] = toChar.charAt(charIdx); // 注意i和j的处理顺序,如果是rst[j][i],图像是逆时针90度打印的,仔细体会下getRGB(i,j)这
}
return rst;
}
private static BufferedImage getScaledImg(BufferedImage image) {
BufferedImage rst = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
rst.getGraphics().drawImage(image, 0, 0, width, height, null);
return rst;
}
} | repos\spring-boot-quick-master\quick-img2txt\src\main\java\com\quick\img2txt\Img2TxtService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Deployment deploy(String url, String pngUrl) {
Deployment deploy = createDeployment().addClasspathResource(url).addClasspathResource(pngUrl).deploy();
return deploy;
}
@Override
public Deployment deploy(String name, String tenantId, String category, ZipInputStream zipInputStream) {
return createDeployment().addZipInputStream(zipInputStream)
.name(name).category(category).tenantId(tenantId).deploy();
}
@Override
public Deployment deployBpmnAndDrl(String url, String drlUrl) {
Deployment deploy = createDeployment().addClasspathResource(url).addClasspathResource(drlUrl).deploy();
return deploy;
}
@Override
public Deployment deploy(String url, String name, String category) {
Deployment deploy = createDeployment().addClasspathResource(url).name(name).category(category).deploy();
return deploy;
}
@Override
public Deployment deploy(String url, String pngUrl, String name, String category) {
Deployment deploy = createDeployment().addClasspathResource(url).addClasspathResource(pngUrl)
.name(name).category(category).deploy();
return deploy;
}
@Override
public boolean exist(String processDefinitionKey) {
ProcessDefinitionQuery processDefinitionQuery
= createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey);
long count = processDefinitionQuery.count();
return count > 0 ? true : false;
}
@Override
public Deployment deploy(String name, String tenantId, String category, InputStream in) {
return createDeployment().addInputStream(name + BPMN_FILE_SUFFIX, in)
.name(name)
.tenantId(tenantId)
.category(category)
.deploy(); | }
@Override
public ProcessDefinition queryByProcessDefinitionKey(String processDefinitionKey) {
ProcessDefinition processDefinition
= createProcessDefinitionQuery()
.processDefinitionKey(processDefinitionKey)
.active().singleResult();
return processDefinition;
}
@Override
public Deployment deployName(String deploymentName) {
List<Deployment> list = repositoryService
.createDeploymentQuery()
.deploymentName(deploymentName).list();
Assert.notNull(list, "list must not be null");
return list.get(0);
}
@Override
public void addCandidateStarterUser(String processDefinitionKey, String userId) {
repositoryService.addCandidateStarterUser(processDefinitionKey, userId);
}
} | repos\spring-boot-quick-master\quick-flowable\src\main\java\com\quick\flowable\service\handler\ProcessHandler.java | 2 |
请完成以下Java代码 | public MessageEventSubscriptionEntity createMessageEventSubscription(
CommandContext commandContext,
DelegateExecution execution
) {
String messageName = getMessageName(execution);
Optional<String> correlationKey = getCorrelationKey(execution);
correlationKey.ifPresent(key -> assertNoExistingDuplicateEventSubscriptions(messageName, key, commandContext));
MessageEventSubscriptionEntity messageEvent = commandContext
.getEventSubscriptionEntityManager()
.insertMessageEvent(messageName, ExecutionEntity.class.cast(execution));
correlationKey.ifPresent(messageEvent::setConfiguration);
return messageEvent;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public MessagePayloadMappingProvider getMessagePayloadMappingProvider() {
return messagePayloadMappingProvider;
}
protected String evaluateExpression(String expression, DelegateExecution execution) {
return Optional.ofNullable(expressionManager.createExpression(expression))
.map(it -> it.getValue(execution))
.map(Object::toString) | .orElseThrow(() -> new ActivitiIllegalArgumentException("Expression '" + expression + "' is null"));
}
protected void assertNoExistingDuplicateEventSubscriptions(
String messageName,
String correlationKey,
CommandContext commandContext
) {
List<EventSubscriptionEntity> existing = commandContext
.getEventSubscriptionEntityManager()
.findEventSubscriptionsByName("message", messageName, null);
existing
.stream()
.filter(subscription -> Objects.equals(subscription.getConfiguration(), correlationKey))
.findFirst()
.ifPresent(subscription -> {
throw new ActivitiIllegalArgumentException(
"Duplicate message subscription '" +
subscription.getEventName() +
"' with correlation key '" +
subscription.getConfiguration() +
"'"
);
});
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultMessageExecutionContext.java | 1 |
请完成以下Java代码 | private void restoreHUsFromSnapshots(final I_M_Inventory inventory)
{
final String snapshotId = inventory.getSnapshot_UUID();
if (Check.isBlank(snapshotId))
{
throw new HUException("@NotFound@ @Snapshot_UUID@ (" + inventory + ")");
}
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
final List<Integer> topLevelHUIds = inventoryDAO.retrieveLinesForInventoryId(inventoryId, I_M_InventoryLine.class)
.stream()
.map(I_M_InventoryLine::getM_HU_ID)
.collect(ImmutableList.toImmutableList());
huSnapshotDAO.restoreHUs()
.setContext(PlainContextAware.newWithThreadInheritedTrx())
.setSnapshotId(snapshotId)
.setDateTrx(inventory.getMovementDate())
.addModelIds(topLevelHUIds)
.setReferencedModel(inventory) | .restoreFromSnapshot();
}
private void reverseEmptiesMovements(final I_M_Inventory inventory)
{
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
movementDAO.retrieveMovementsForInventoryQuery(inventoryId)
.addEqualsFilter(I_M_Inventory.COLUMNNAME_DocStatus, X_M_Inventory.DOCSTATUS_Completed)
.create()
.stream()
.forEach(emptiesMovement -> documentBL.processEx(emptiesMovement, X_M_Movement.DOCACTION_Reverse_Correct, X_M_Movement.DOCSTATUS_Reversed));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\interceptor\M_Inventory.java | 1 |
请完成以下Java代码 | public ReturnT<String> callback(List<HandleCallbackParam> callbackParamList) {
callbackThreadPool.execute(new Runnable() {
@Override
public void run() {
for (HandleCallbackParam handleCallbackParam: callbackParamList) {
ReturnT<String> callbackResult = callback(handleCallbackParam);
logger.debug(">>>>>>>>> JobApiController.callback {}, handleCallbackParam={}, callbackResult={}",
(callbackResult.getCode()== ReturnT.SUCCESS_CODE?"success":"fail"), handleCallbackParam, callbackResult);
}
}
});
return ReturnT.SUCCESS;
}
private ReturnT<String> callback(HandleCallbackParam handleCallbackParam) {
// valid log item
XxlJobLog log = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().load(handleCallbackParam.getLogId());
if (log == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "log item not found.");
}
if (log.getHandleCode() > 0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "log repeate callback."); // avoid repeat callback, trigger child job etc
}
// handle msg
StringBuffer handleMsg = new StringBuffer();
if (log.getHandleMsg()!=null) {
handleMsg.append(log.getHandleMsg()).append("<br>"); | }
if (handleCallbackParam.getHandleMsg() != null) {
handleMsg.append(handleCallbackParam.getHandleMsg());
}
// success, save log
log.setHandleTime(new Date());
log.setHandleCode(handleCallbackParam.getHandleCode());
log.setHandleMsg(handleMsg.toString());
XxlJobCompleter.updateHandleInfoAndFinish(log);
return ReturnT.SUCCESS;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\thread\JobCompleteHelper.java | 1 |
请完成以下Java代码 | public void enableModelValidatorSubsequentProcessing(final ModelValidator validator, final boolean processDirectly)
{
m_modelChangeSubsequent.put(validator, processDirectly);
}
public void disableModelValidatorSubsequentProcessing(final ModelValidator validator)
{
m_modelChangeSubsequent.remove(validator);
}
// public static final String CTX_InitEntityTypes = ModelValidationEngine.class.getCanonicalName() + "#InitEntityTypes";
/**
* Name of a dynamic attribute to disable model interceptors (i.e. validators) on ModelChange for a particular PO. Set the value to <code>true</code> if you want to bypass <b>all</b> model
* validators.
* <p>
*
* @FIXME [12:09:52] Teo metas: use org.adempiere.ad.persistence.ModelDynAttributeAccessor<ModelType, AttributeType> to define the dynamic attribute
*/
public static final String DYNATTR_DO_NOT_INVOKE_ON_MODEL_CHANGE = "DO_NOT_INVOKE_ON_MODEL_CHANGE";
private enum State
{
/** In this state, {@link #get()} does not attempt to initialize this model validator and basically returns a "no-op" instance. */
SKIP_INITIALIZATION,
/** In this state, the next invocation of {@link #get()} will to initialize the model validator before returning an instance. */
TO_BE_INITALIZED,
INITIALIZING,
INITIALIZED
}
private static State state = State.TO_BE_INITALIZED;
public static IAutoCloseable postponeInit()
{
changeStateToSkipInitialization(); | return ModelValidationEngine::changeStateToBeInitialized;
}
private static synchronized void changeStateToSkipInitialization()
{
Check.assumeEquals(state, State.TO_BE_INITALIZED);
state = State.SKIP_INITIALIZATION;
}
private static synchronized void changeStateToBeInitialized()
{
if (state == State.SKIP_INITIALIZATION)
{
state = State.TO_BE_INITALIZED;
}
}
} // ModelValidatorEngine | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\ModelValidationEngine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProcessApplicationStopService implements Service<ProcessApplicationStopService> {
private final static Logger LOGGER = Logger.getLogger(ProcessApplicationStopService.class.getName());
// for view-exposing ProcessApplicationComponents
protected InjectedValue<ComponentView> paComponentViewInjector = new InjectedValue<ComponentView>();
protected InjectedValue<ProcessApplicationInterface> noViewProcessApplication = new InjectedValue<ProcessApplicationInterface>();
protected InjectedValue<BpmPlatformPlugins> platformPluginsInjector = new InjectedValue<BpmPlatformPlugins>();
@Override
public ProcessApplicationStopService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
@Override
public void start(StartContext arg0) throws StartException {
// nothing to do
}
@Override
public void stop(StopContext arg0) {
ManagedReference reference = null;
try {
// get the process application component
ProcessApplicationInterface processApplication = null;
ComponentView componentView = paComponentViewInjector.getOptionalValue();
if(componentView != null) {
reference = componentView.createInstance();
processApplication = (ProcessApplicationInterface) reference.getInstance();
}
else {
processApplication = noViewProcessApplication.getValue(); | }
BpmPlatformPlugins bpmPlatformPlugins = platformPluginsInjector.getValue();
List<BpmPlatformPlugin> plugins = bpmPlatformPlugins.getPlugins();
for (BpmPlatformPlugin bpmPlatformPlugin : plugins) {
bpmPlatformPlugin.postProcessApplicationUndeploy(processApplication);
}
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception while invoking BpmPlatformPlugin.postProcessApplicationUndeploy", e);
}
finally {
if(reference != null) {
reference.release();
}
}
}
public InjectedValue<ProcessApplicationInterface> getNoViewProcessApplication() {
return noViewProcessApplication;
}
public InjectedValue<ComponentView> getPaComponentViewInjector() {
return paComponentViewInjector;
}
public InjectedValue<BpmPlatformPlugins> getPlatformPluginsInjector() {
return platformPluginsInjector;
}
} | repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ProcessApplicationStopService.java | 2 |
请完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setM_PricingSystem_ID (final int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_Value (COLUMNNAME_M_PricingSystem_ID, null);
else
set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID);
}
@Override
public int getM_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID);
} | @Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Contract_Change.java | 1 |
请完成以下Java代码 | public int getRetries() {
return retries;
}
public Date getDueDate() {
return dueDate;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public boolean isSuspended() {
return suspended; | }
public long getPriority() {
return priority;
}
public String getTenantId() {
return tenantId;
}
public Date getCreateTime() {
return createTime;
}
public String getBatchId() {
return batchId;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\JobDto.java | 1 |
请完成以下Java代码 | public void setPeriodType (String PeriodType)
{
set_ValueNoCheck (COLUMNNAME_PeriodType, PeriodType);
}
/** Get Period Type.
@return Period Type
*/
public String getPeriodType ()
{
return (String)get_Value(COLUMNNAME_PeriodType);
}
/** 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 Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Period.java | 1 |
请完成以下Java代码 | private TransportMod createTransportMod()
{
if (Check.isEmpty(exportFileFromEAN, true))
{
return null;
}
return TransportMod.builder()
.from(exportFileFromEAN)
.replacementViaEAN(exportFileViaEAN)
.build();
}
private PayloadMod createPayloadMod(
@NonNull final DunningToExport dunning,
@NonNull final XmlPayload xPayLoad)
{
return PayloadMod.builder()
.type(RequestType.REMINDER.getValue())
.reminder(createReminder(dunning))
.bodyMod(createBodyMod(dunning))
.build();
}
private XmlReminder createReminder(@NonNull final DunningToExport dunning)
{
final XmlReminder createReminder = XmlReminder.builder()
.requestDate(asXmlCalendar(dunning.getDunningDate()))
.requestTimestamp(BigInteger.valueOf(dunning.getDunningTimestamp().getEpochSecond()))
.requestId(dunning.getDocumentNumber())
.reminderText(dunning.getDunningText())
.reminderLevel("1")
.build();
return createReminder;
}
private BodyMod createBodyMod(
@NonNull final DunningToExport dunning)
{
return BodyMod
.builder()
.prologMod(createPrologMod(dunning.getMetasfreshVersion()))
.balanceMod(createBalanceMod(dunning))
.build();
}
private PrologMod createPrologMod(@NonNull final MetasfreshVersion metasfreshVersion)
{
final SoftwareMod softwareMod = createSoftwareMod(metasfreshVersion);
return PrologMod.builder()
.pkgMod(softwareMod)
.generatorMod(createSoftwareMod(metasfreshVersion))
.build();
}
private XMLGregorianCalendar asXmlCalendar(@NonNull final Calendar cal)
{
try
{
final GregorianCalendar gregorianCal = new GregorianCalendar(cal.getTimeZone()); | gregorianCal.setTime(cal.getTime());
return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCal);
}
catch (final DatatypeConfigurationException e)
{
throw new AdempiereException(e).appendParametersToMessage()
.setParameter("cal", cal);
}
}
private SoftwareMod createSoftwareMod(@NonNull final MetasfreshVersion metasfreshVersion)
{
final long versionNumber = metasfreshVersion.getMajor() * 100 + metasfreshVersion.getMinor(); // .. as advised in the documentation
return SoftwareMod
.builder()
.name("metasfresh")
.version(versionNumber)
.description(metasfreshVersion.getFullVersion())
.id(0L)
.copyright("Copyright (C) 2018 metas GmbH")
.build();
}
private BalanceMod createBalanceMod(@NonNull final DunningToExport dunning)
{
final Money amount = dunning.getAmount();
final Money alreadyPaidAmount = dunning.getAlreadyPaidAmount();
final BigDecimal amountDue = amount.getAmount().subtract(alreadyPaidAmount.getAmount());
return BalanceMod.builder()
.currency(amount.getCurrency())
.amount(amount.getAmount())
.amountDue(amountDue)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\dunning\DunningExportClientImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
public String getActivityType() {
return activityType;
}
public void setActivityType(String activityType) {
this.activityType = activityType;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public Boolean getFinished() {
return finished;
}
public void setFinished(Boolean finished) {
this.finished = finished;
}
public String getTaskAssignee() {
return taskAssignee;
}
public void setTaskAssignee(String taskAssignee) {
this.taskAssignee = taskAssignee;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
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;
}
public Set<String> getCalledProcessInstanceIds() {
return calledProcessInstanceIds;
}
public void setCalledProcessInstanceIds(Set<String> calledProcessInstanceIds) {
this.calledProcessInstanceIds = calledProcessInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceQueryRequest.java | 2 |
请完成以下Java代码 | public void setAD_UserGroup_User_Assign_ID (int AD_UserGroup_User_Assign_ID)
{
if (AD_UserGroup_User_Assign_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_User_Assign_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_User_Assign_ID, Integer.valueOf(AD_UserGroup_User_Assign_ID));
}
/** Get Users Group User Assignment.
@return Users Group User Assignment */
@Override
public int getAD_UserGroup_User_Assign_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_User_Assign_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); | }
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserGroup_User_Assign.java | 1 |
请完成以下Java代码 | public StringAttributeBuilder defaultValue(String defaultValue) {
return (StringAttributeBuilder) super.defaultValue(defaultValue);
}
@Override
public StringAttributeBuilder required() {
return (StringAttributeBuilder) super.required();
}
@Override
public StringAttributeBuilder idAttribute() {
return (StringAttributeBuilder) super.idAttribute();
}
/**
* Create a new {@link AttributeReferenceBuilder} for the reference source element instance
*
* @param referenceTargetElement the reference target model element instance
* @return the new attribute reference builder
*/
public <V extends ModelElementInstance> AttributeReferenceBuilder<V> qNameAttributeReference(Class<V> referenceTargetElement) {
AttributeImpl<String> attribute = (AttributeImpl<String>) build();
AttributeReferenceBuilderImpl<V> referenceBuilder = new QNameAttributeReferenceBuilderImpl<V>(attribute, referenceTargetElement);
setAttributeReference(referenceBuilder);
return referenceBuilder;
}
public <V extends ModelElementInstance> AttributeReferenceBuilder<V> idAttributeReference(Class<V> referenceTargetElement) {
AttributeImpl<String> attribute = (AttributeImpl<String>) build();
AttributeReferenceBuilderImpl<V> referenceBuilder = new AttributeReferenceBuilderImpl<V>(attribute, referenceTargetElement);
setAttributeReference(referenceBuilder);
return referenceBuilder;
}
@SuppressWarnings("rawtypes")
public <V extends ModelElementInstance> AttributeReferenceCollectionBuilder<V> idAttributeReferenceCollection(Class<V> referenceTargetElement, Class<? extends AttributeReferenceCollection> attributeReferenceCollection) {
AttributeImpl<String> attribute = (AttributeImpl<String>) build(); | AttributeReferenceCollectionBuilder<V> referenceBuilder = new AttributeReferenceCollectionBuilderImpl<V>(attribute, referenceTargetElement, attributeReferenceCollection);
setAttributeReference(referenceBuilder);
return referenceBuilder;
}
protected <V extends ModelElementInstance> void setAttributeReference(AttributeReferenceBuilder<V> referenceBuilder) {
if (this.referenceBuilder != null) {
throw new ModelException("An attribute cannot have more than one reference");
}
this.referenceBuilder = referenceBuilder;
}
@Override
public void performModelBuild(Model model) {
super.performModelBuild(model);
if (referenceBuilder != null) {
((ModelBuildOperation) referenceBuilder).performModelBuild(model);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\attribute\StringAttributeBuilderImpl.java | 1 |
请完成以下Java代码 | private void setIds(LegoSet legoSet) {
if (legoSet.getId() == 0) {
legoSet.setId(id.incrementAndGet());
}
var manual = legoSet.getManual();
if (manual != null) {
manual.setId((long) legoSet.getId());
}
}
@Override
public JdbcCustomConversions jdbcCustomConversions() {
return new JdbcCustomConversions(asList(new Converter<Clob, String>() {
@Nullable
@Override
public String convert(Clob clob) {
try {
return Math.toIntExact(clob.length()) == 0 //
? "" //
: clob.getSubString(1, Math.toIntExact(clob.length()));
} catch (SQLException e) {
throw new IllegalStateException("Failed to convert CLOB to String.", e); | }
}
}));
}
@Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(JdbcOperations operations) {
return new NamedParameterJdbcTemplate(operations);
}
@Bean
DataSourceInitializer initializer(DataSource dataSource) {
var initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource);
var script = new ClassPathResource("schema.sql");
var populator = new ResourceDatabasePopulator(script);
initializer.setDatabasePopulator(populator);
return initializer;
}
} | repos\spring-data-examples-main\jdbc\basics\src\main\java\example\springdata\jdbc\basics\aggregate\AggregateConfiguration.java | 1 |
请完成以下Java代码 | public static void createPeriodControls(Properties ctx, int AD_Client_ID, JavaProcess sp, String trxName)
{
s_log.info("AD_Client_ID=" + AD_Client_ID);
// Delete Duplicates
String sql = "DELETE FROM C_PeriodControl pc1 "
+ "WHERE (C_Period_ID, DocBaseType) IN "
+ "(SELECT C_Period_ID, DocBaseType "
+ "FROM C_PeriodControl pc2 "
+ "GROUP BY C_Period_ID, DocBaseType "
+ "HAVING COUNT(*) > 1)"
+ " AND C_PeriodControl_ID NOT IN "
+ "(SELECT MIN(C_PeriodControl_ID) "
+ "FROM C_PeriodControl pc3 "
+ "GROUP BY C_Period_ID, DocBaseType)";
int no = DB.executeUpdateAndIgnoreErrorOnFail(sql, false, trxName);
s_log.info("Duplicates deleted #" + no);
// Insert Missing
sql = "SELECT DISTINCT p.AD_Client_ID, p.C_Period_ID, dt.DocBaseType "
+ "FROM C_Period p"
+ " FULL JOIN C_DocType dt ON (p.AD_Client_ID=dt.AD_Client_ID) "
+ "WHERE p.AD_Client_ID=?"
+ " AND NOT EXISTS"
+ " (SELECT * FROM C_PeriodControl pc "
+ "WHERE pc.C_Period_ID=p.C_Period_ID AND pc.DocBaseType=dt.DocBaseType)";
PreparedStatement pstmt = null;
int counter = 0;
try
{
pstmt = DB.prepareStatement(sql, trxName);
pstmt.setInt(1, AD_Client_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
int Client_ID = rs.getInt(1);
int C_Period_ID = rs.getInt(2);
String DocBaseType = rs.getString(3);
s_log.info("AD_Client_ID=" + Client_ID
+ ", C_Period_ID=" + C_Period_ID + ", DocBaseType=" + DocBaseType);
//
MPeriodControl pc = new MPeriodControl (ctx, Client_ID, C_Period_ID, DocBaseType, trxName); | if (pc.save())
{
counter++;
s_log.debug(pc.toString());
}
else
s_log.warn("Not saved: " + pc);
}
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
s_log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
if (sp != null)
sp.addLog (0, null, new BigDecimal(counter), "@C_PeriodControl_ID@ @Created@");
s_log.info("Inserted #" + counter);
} // createPeriodControls
} // DocumentTypeVerify | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\DocumentTypeVerify.java | 1 |
请完成以下Java代码 | public static <T> T uiAsk(final String title, final String message, final T[] options, final T defaultOption)
{
final Object messageObj;
if (message != null && message.startsWith("<html>"))
{
final JTextPane tp = new JTextPane();
tp.setContentType("text/html");
tp.setText(message);
tp.setEditable(false);
tp.setAutoscrolls(true);
tp.addHyperlinkListener(DEFAULT_HyperlinkListener);
final JScrollPane jsp = new JScrollPane(tp);
jsp.setPreferredSize(new Dimension(1200, 500));
messageObj = jsp;
}
else
{
messageObj = message;
}
// Create the frame in which we will display the Option Dialog
// NOTE: we are doing this because we want to have this window in taskbar (and in Windows, Dialogs are not shown in taskbar)
final JFrame frame = new JFrame(title);
frame.setUndecorated(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setVisible(true); // make it visible, if we are not doing this, we will have no icon if task bar
final int responseIdx;
try
{
responseIdx = JOptionPane.showOptionDialog(
frame, // parentComponent
messageObj, // message
title,
JOptionPane.DEFAULT_OPTION, // optionType,
JOptionPane.WARNING_MESSAGE, // messageType,
null, // icon,
options, // options
defaultOption // initialValue
); | }
finally
{
// Make sure we are disposing the frame (note: it is not disposed by default)
frame.dispose();
}
if (responseIdx < 0)
{
// user closed the popup => defaultOption shall be returned
return defaultOption;
}
final T response = options[responseIdx];
return response;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\applier\impl\SwingUIScriptsApplierListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RefreshTokenAuthenticationProvider extends AbstractAuthenticationProvider {
private final JwtTokenFactory tokenFactory;
private final TokenOutdatingService tokenOutdatingService;
public RefreshTokenAuthenticationProvider(JwtTokenFactory jwtTokenFactory, UserAuthDetailsCache userAuthDetailsCache,
CustomerService customerService, TokenOutdatingService tokenOutdatingService) {
super(customerService, userAuthDetailsCache);
this.tokenFactory = jwtTokenFactory;
this.tokenOutdatingService = tokenOutdatingService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.notNull(authentication, "No authentication data provided");
RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();
SecurityUser unsafeUser = tokenFactory.parseRefreshToken(rawAccessToken.token());
UserPrincipal principal = unsafeUser.getUserPrincipal();
SecurityUser securityUser;
if (principal.getType() == UserPrincipal.Type.USER_NAME) {
securityUser = authenticateByUserId(TenantId.SYS_TENANT_ID, unsafeUser.getId());
} else { | securityUser = authenticateByPublicId(principal.getValue());
}
securityUser.setSessionId(unsafeUser.getSessionId());
if (tokenOutdatingService.isOutdated(rawAccessToken.token(), securityUser.getId())) {
throw new CredentialsExpiredException("Token is outdated");
}
return new RefreshAuthenticationToken(securityUser);
}
private SecurityUser authenticateByPublicId(String publicId) {
return super.authenticateByPublicId(publicId, "Refresh token", null);
}
@Override
public boolean supports(Class<?> authentication) {
return (RefreshAuthenticationToken.class.isAssignableFrom(authentication));
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\jwt\RefreshTokenAuthenticationProvider.java | 2 |
请完成以下Java代码 | public class NativeProcessInstanceQueryImpl
extends AbstractNativeQuery<NativeProcessInstanceQuery, ProcessInstance>
implements NativeProcessInstanceQuery {
private static final long serialVersionUID = 1L;
public NativeProcessInstanceQueryImpl(CommandContext commandContext) {
super(commandContext);
}
public NativeProcessInstanceQueryImpl(CommandExecutor commandExecutor) {
super(commandExecutor);
}
// results ////////////////////////////////////////////////////////////////
public List<ProcessInstance> executeList( | CommandContext commandContext,
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return commandContext
.getExecutionEntityManager()
.findProcessInstanceByNativeQuery(parameterMap, firstResult, maxResults);
}
public long executeCount(CommandContext commandContext, Map<String, Object> parameterMap) {
return commandContext
.getExecutionEntityManager()
// can use execution count, since the result type doesn't matter
.findExecutionCountByNativeQuery(parameterMap);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\NativeProcessInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | TemperatureSensor temperatureSensor(TemperatureReadingRepository repository) {
return new TemperatureSensor(repository);
}
@Bean
RegionConfigurer temperatureReadingsConfigurer() {
return new RegionConfigurer() {
@Override
public void configure(String beanName, PeerRegionFactoryBean<?, ?> regionBean) {
Optional.ofNullable(beanName)
.filter("TemperatureReadings"::equals)
.ifPresent(it -> regionBean.setStatisticsEnabled(true));
}
};
}
@Bean
@DependsOn("TemperatureReadings")
IndexFactoryBean temperatureReadingTemperatureIndex(GemFireCache gemfireCache) {
IndexFactoryBean temperatureTimestampIndex = new IndexFactoryBean();
temperatureTimestampIndex.setCache(gemfireCache); | temperatureTimestampIndex.setExpression("temperature");
temperatureTimestampIndex.setFrom("/TemperatureReadings");
temperatureTimestampIndex.setName("TemperatureReadingTemperatureIdx");
return temperatureTimestampIndex;
}
@Bean
@DependsOn("TemperatureReadings")
IndexFactoryBean temperatureReadingTimestampIndex(GemFireCache gemfireCache) {
IndexFactoryBean temperatureTimestampIndex = new IndexFactoryBean();
temperatureTimestampIndex.setCache(gemfireCache);
temperatureTimestampIndex.setExpression("timestamp");
temperatureTimestampIndex.setFrom("/TemperatureReadings");
temperatureTimestampIndex.setName("TemperatureReadingTimestampIdx");
return temperatureTimestampIndex;
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\boot\actuator\src\main\java\example\app\temp\geode\server\BootGeodeServerApplication.java | 2 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof User)) {
return false;
}
User that = (User) obj;
return this.getName().equals(that.getName());
}
@Override
public int hashCode() {
int hashValue = 17;
hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getName());
return hashValue;
}
@Override
public String toString() {
return getName();
}
public enum Role {
CLUSTER_OPERATOR,
DEVELOPER;
public static Role of(String name) {
return Arrays.stream(values()) | .filter(role -> role.name().equalsIgnoreCase(String.valueOf(name).trim()))
.findFirst()
.orElse(null);
}
public boolean isClusterOperator() {
return CLUSTER_OPERATOR.equals(this);
}
public boolean isDeveloper() {
return DEVELOPER.equals(this);
}
@Override
public String toString() {
return name().toLowerCase();
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\support\User.java | 1 |
请完成以下Java代码 | public final class LockOwner
{
public static enum OwnerType
{
None,
Any,
RealOwner,
};
private static final String OWNERNAME_Null = "NULL"; // use the string "NULL", because we don't want null to end up in a database.
public static final LockOwner NONE = new LockOwner(OWNERNAME_Null, OwnerType.None);
/**
* This instance is used to indicate that the lock owner is not a filter criterion
*/
public static final LockOwner ANY = new LockOwner(OWNERNAME_Null, OwnerType.Any);
/**
* Creates a new owner whose name starts with <code>"Unknown"</code> and ands with a unique suffix.
*/
public static LockOwner newOwner()
{
final String ownerNamePrefix = null;
return newOwner(ownerNamePrefix);
}
/**
* Creates a new owner whose name consists of the given <code>ownerNamePrefix</code> and a unique suffix.
*
*/
public static LockOwner newOwner(final String ownerNamePrefix)
{
final Object ownerNameUniquePart = UUID.randomUUID();
return newOwner(ownerNamePrefix, ownerNameUniquePart);
}
/**
* Creates a new owner whose name consists of the given <code>ownerNamePrefix</code> and the given <code>ownerNameUniquePart</code> which is supposed to be unique.
*
* @param ownerNamePrefix the owner name's prefix. <code>null</code> is substituted with <code>"Unknown"</code>.
*/
public static LockOwner newOwner(final String ownerNamePrefix, final Object ownerNameUniquePart)
{
Check.assumeNotNull(ownerNameUniquePart, "ownerNameUniquePart not null");
final String ownerNamePrefixToUse;
if (Check.isEmpty(ownerNamePrefix, true))
{
ownerNamePrefixToUse = "Unknown";
}
else
{
ownerNamePrefixToUse = ownerNamePrefix.trim();
}
final String ownerName = ownerNamePrefixToUse + "_" + ownerNameUniquePart;
return new LockOwner(ownerName, OwnerType.RealOwner);
}
/**
* Creates a new instance with "static" name.
* | * @param ownerName the name of the new owner. Other than with the <code>newOwner(...)</code> methods, nothing will be added to it.
* @return
*/
public static final LockOwner forOwnerName(final String ownerName)
{
Check.assumeNotEmpty(ownerName, "ownerName not empty");
return new LockOwner(ownerName, OwnerType.RealOwner);
}
private final String ownerName;
private final OwnerType ownerType;
private LockOwner(final String ownerName, final OwnerType ownerType)
{
Check.assumeNotNull(ownerName, "Param ownerName is not null");
this.ownerName = ownerName;
this.ownerType = ownerType;
}
public boolean isRealOwner()
{
return ownerType == OwnerType.RealOwner;
}
public boolean isRealOwnerOrNoOwner()
{
return isRealOwner()
|| isNoOwner();
}
public boolean isNoOwner()
{
return ownerType == OwnerType.None;
}
public boolean isAnyOwner()
{
return ownerType == OwnerType.Any;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\LockOwner.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StructDepartment {
@Id
@GeneratedValue
private Integer id;
@Column
private String departmentName;
@Embedded
@Column
private StructManager manager;
@Override
public String toString() {
return "Department{" +
"id=" + id +
", departmentName='" + departmentName + '\'' +
", manager=" + manager +
'}';
}
public StructDepartment(String departmentName, StructManager manager) {
this.departmentName = departmentName;
this.manager = manager; | }
public Integer getId() {
return id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public StructManager getManager() {
return manager;
}
public void setManager(StructManager manager) {
this.manager = manager;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\java\com\baeldung\hibernate\struct\entities\StructDepartment.java | 2 |
请完成以下Java代码 | public String toString() {
return combine(qualifier, localName);
}
public static String combine(String qualifier, String localName) {
if (qualifier == null || qualifier.isEmpty()) {
return localName;
}
else {
return qualifier + ":" + localName;
}
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + ((localName == null) ? 0 : localName.hashCode());
result = prime * result + ((qualifier == null) ? 0 : qualifier.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
QName other = (QName) obj; | if (localName == null) {
if (other.localName != null) {
return false;
}
} else if (!localName.equals(other.localName)) {
return false;
}
if (qualifier == null) {
if (other.qualifier != null) {
return false;
}
} else if (!qualifier.equals(other.qualifier)) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\QName.java | 1 |
请完成以下Java代码 | public void setImpex_ConnectorParam_ID (int Impex_ConnectorParam_ID)
{
if (Impex_ConnectorParam_ID < 1)
set_ValueNoCheck (COLUMNNAME_Impex_ConnectorParam_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Impex_ConnectorParam_ID, Integer.valueOf(Impex_ConnectorParam_ID));
}
/** Get Konnektor-Parameter.
@return Konnektor-Parameter */
public int getImpex_ConnectorParam_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Impex_ConnectorParam_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Parameter-Name.
@param ParamName Parameter-Name */
public void setParamName (String ParamName)
{
set_Value (COLUMNNAME_ParamName, ParamName);
}
/** Get Parameter-Name.
@return Parameter-Name */
public String getParamName ()
{
return (String)get_Value(COLUMNNAME_ParamName);
}
/** Set Parameterwert. | @param ParamValue Parameterwert */
public void setParamValue (String ParamValue)
{
set_Value (COLUMNNAME_ParamValue, ParamValue);
}
/** Get Parameterwert.
@return Parameterwert */
public String getParamValue ()
{
return (String)get_Value(COLUMNNAME_ParamValue);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_Impex_ConnectorParam.java | 1 |
请完成以下Java代码 | public Set<ProductId> getProductIds()
{
return productPricesByProductId.keySet();
}
public Money getProductPrice(@NonNull final ProductId productId)
{
final ProductPrice productPrice = productPricesByProductId.get(productId);
if (productPrice == null)
{
throw new AdempiereException("No product price found for " + productId + " in " + this);
}
return productPrice.getPrice();
}
@Value
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public static class ProductPrice
{
@JsonProperty("productId")
ProductId productId; | @JsonProperty("price")
Money price;
@Builder
@JsonCreator
private ProductPrice(
@JsonProperty("productId") @NonNull final ProductId productId,
@JsonProperty("price") @NonNull final Money price)
{
this.productId = productId;
this.price = price;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\InvoiceChangedEvent.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public int getRevisionNext() {
return revision + 1;
}
@Override
public int getRevision() {
return revision;
}
@Override
public void setRevision(int revision) {
this.revision = revision;
}
@Override
public boolean isInserted() {
return isInserted;
}
@Override
public void setInserted(boolean isInserted) {
this.isInserted = isInserted; | }
@Override
public boolean isUpdated() {
return isUpdated;
}
@Override
public void setUpdated(boolean isUpdated) {
this.isUpdated = isUpdated;
}
@Override
public boolean isDeleted() {
return isDeleted;
}
@Override
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
@Override
public Object getOriginalPersistentState() {
return originalPersistentState;
}
@Override
public void setOriginalPersistentState(Object persistentState) {
this.originalPersistentState = persistentState;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\AbstractEntity.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.