instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public final boolean isAvailable()
{
final I_AD_Form form = getAD_Form();
return form != null;
}
@Override
public final boolean isRunnable()
{
final I_AD_Form form = getAD_Form();
if (form == null)
{
return false;
}
if (!isFormRunnable())
{
return false;
}
return true;
}
/**
* Check if the form is available and shall be opened in current context.
*
* To be implemented in extending class.
*
* @return true if form is available and it shall be opened.
*/
protected boolean isFormRunnable()
{
// nothing at this level
return true;
}
@Override
public final void run()
{
final FormFrame formFrame = AEnv.createForm(getAD_Form());
if (formFrame == null)
{
return;
}
customizeBeforeOpen(formFrame);
AEnv.showCenterWindow(getCallingFrame(), formFrame);
}
protected void customizeBeforeOpen(final FormFrame formFrame)
{
// nothing on this level
}
/** @return the {@link Frame} in which this action was executed or <code>null</code> if not available. */
protected final Frame getCallingFrame()
{
final GridField gridField = getContext().getEditor().getField();
if (gridField == null)
{
return null;
}
final int windowNo = gridField.getWindowNo();
final Frame frame = Env.getWindow(windowNo);
return frame;
}
protected final int getAD_Form_ID()
{
return _adFormId;
} | private final synchronized I_AD_Form getAD_Form()
{
if (!_adFormLoaded)
{
_adForm = retrieveAD_Form();
_adFormLoaded = true;
}
return _adForm;
}
private final I_AD_Form retrieveAD_Form()
{
final IContextMenuActionContext context = getContext();
Check.assumeNotNull(context, "context not null");
final Properties ctx = context.getCtx();
// Check if user has access to Payment Allocation form
final int adFormId = getAD_Form_ID();
final Boolean formAccess = Env.getUserRolePermissions().checkFormAccess(adFormId);
if (formAccess == null || !formAccess)
{
return null;
}
// Retrieve the form
final I_AD_Form form = InterfaceWrapperHelper.create(ctx, adFormId, I_AD_Form.class, ITrx.TRXNAME_None);
// Translate it to user's language
final I_AD_Form formTrl = InterfaceWrapperHelper.translate(form, I_AD_Form.class);
return formTrl;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\OpenFormContextMenuAction.java | 1 |
请完成以下Java代码 | public class EntityCacheImpl implements EntityCache {
protected Map<Class<?>, Map<String, CachedEntity>> cachedObjects = new HashMap<
Class<?>,
Map<String, CachedEntity>
>();
@Override
public CachedEntity put(Entity entity, boolean storeState) {
Map<String, CachedEntity> classCache = cachedObjects.get(entity.getClass());
if (classCache == null) {
classCache = new HashMap<String, CachedEntity>();
cachedObjects.put(entity.getClass(), classCache);
}
CachedEntity cachedObject = new CachedEntity(entity, storeState);
classCache.put(entity.getId(), cachedObject);
return cachedObject;
}
@Override
@SuppressWarnings("unchecked")
public <T> T findInCache(Class<T> entityClass, String id) {
CachedEntity cachedObject = null;
Map<String, CachedEntity> classCache = cachedObjects.get(entityClass);
if (classCache == null) {
classCache = findClassCacheByCheckingSubclasses(entityClass);
}
if (classCache != null) {
cachedObject = classCache.get(id);
}
if (cachedObject != null) {
return (T) cachedObject.getEntity();
}
return null;
}
protected Map<String, CachedEntity> findClassCacheByCheckingSubclasses(Class<?> entityClass) {
for (Class<?> clazz : cachedObjects.keySet()) {
if (entityClass.isAssignableFrom(clazz)) {
return cachedObjects.get(clazz);
}
}
return null;
}
@Override
public void cacheRemove(Class<?> entityClass, String entityId) {
Map<String, CachedEntity> classCache = cachedObjects.get(entityClass);
if (classCache == null) {
return;
}
classCache.remove(entityId);
} | @Override
public <T> Collection<CachedEntity> findInCacheAsCachedObjects(Class<T> entityClass) {
Map<String, CachedEntity> classCache = cachedObjects.get(entityClass);
if (classCache != null) {
return classCache.values();
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public <T> List<T> findInCache(Class<T> entityClass) {
Map<String, CachedEntity> classCache = cachedObjects.get(entityClass);
if (classCache == null) {
classCache = findClassCacheByCheckingSubclasses(entityClass);
}
if (classCache != null) {
List<T> entities = new ArrayList<T>(classCache.size());
for (CachedEntity cachedObject : classCache.values()) {
entities.add((T) cachedObject.getEntity());
}
return entities;
}
return emptyList();
}
public Map<Class<?>, Map<String, CachedEntity>> getAllCachedEntities() {
return cachedObjects;
}
@Override
public void close() {}
@Override
public void flush() {}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\cache\EntityCacheImpl.java | 1 |
请完成以下Java代码 | public String toString() {
return "Person [name=" + name + ", nickname=" + nickname + ", age="
+ age + "]";
}
private String name;
private String nickname;
private int age;
public Person() {
}
public Person(String name, String nickname, int age) {
this.name = name;
this.nickname = nickname;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname; | }
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
} | repos\tutorials-master\orika\src\main\java\com\baeldung\orika\Person.java | 1 |
请完成以下Java代码 | public String getFinancial() {
return financial;
}
public void setFinancial(String financial) {
this.financial = financial;
}
public String getContactman() {
return contactman;
}
public void setContactman(String contactman) {
this.contactman = contactman;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCantonlev() {
return cantonlev;
}
public void setCantonlev(String cantonlev) {
this.cantonlev = cantonlev;
}
public String getTaxorgcode() {
return taxorgcode;
}
public void setTaxorgcode(String taxorgcode) {
this.taxorgcode = taxorgcode;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getUsing() {
return using;
} | public void setUsing(String using) {
this.using = using;
}
public String getUsingdate() {
return usingdate;
}
public void setUsingdate(String usingdate) {
this.usingdate = usingdate;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getQrcantonid() {
return qrcantonid;
}
public void setQrcantonid(String qrcantonid) {
this.qrcantonid = qrcantonid;
}
public String getDeclare() {
return declare;
}
public void setDeclare(String declare) {
this.declare = declare;
}
public String getDeclareisend() {
return declareisend;
}
public void setDeclareisend(String declareisend) {
this.declareisend = declareisend;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\canton\Canton.java | 1 |
请完成以下Java代码 | public int answer(int i)
{
return 0;
}
public int y(int i)
{
return result(i);
}
public String y2(int i)
{
return "";
}
public String yname(int i)
{
return "";
}
public String x(int i, int j)
{
return "";
}
public int ysize()
{
return 0;
}
public double prob(int i, int j)
{
return 0.0;
}
public double prob(int i)
{
return 0.0;
}
public double prob()
{
return 0.0;
}
public double alpha(int i, int j)
{
return 0.0;
}
public double beta(int i, int j)
{
return 0.0;
}
public double emissionCost(int i, int j)
{
return 0.0;
}
public double nextTransitionCost(int i, int j, int k)
{
return 0.0;
}
public double prevTransitionCost(int i, int j, int k)
{
return 0.0;
}
public double bestCost(int i, int j)
{
return 0.0;
}
public List<Integer> emissionVector(int i, int j)
{
return null;
} | public List<Integer> nextTransitionVector(int i, int j, int k)
{
return null;
}
public List<Integer> prevTransitionVector(int i, int j, int k)
{
return null;
}
public double Z()
{
return 0.0;
}
public boolean parse()
{
return true;
}
public boolean empty()
{
return true;
}
public boolean clear()
{
return true;
}
public boolean next()
{
return true;
}
public String parse(String str)
{
return "";
}
public String toString()
{
return "";
}
public String toString(String result, int size)
{
return "";
}
public String parse(String str, int size)
{
return "";
}
public String parse(String str, int size1, String result, int size2)
{
return "";
}
// set token-level penalty. It would be useful for implementing
// Dual decompositon decoding.
// e.g.
// "Dual Decomposition for Parsing with Non-Projective Head Automata"
// Terry Koo Alexander M. Rush Michael Collins Tommi Jaakkola David Sontag
public void setPenalty(int i, int j, double penalty)
{
}
public double penalty(int i, int j)
{
return 0.0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Tagger.java | 1 |
请完成以下Java代码 | public void setIsToleranceExceeded (final boolean IsToleranceExceeded)
{
set_Value (COLUMNNAME_IsToleranceExceeded, IsToleranceExceeded);
}
@Override
public boolean isToleranceExceeded()
{
return get_ValueAsBoolean(COLUMNNAME_IsToleranceExceeded);
}
@Override
public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setPP_Order_Weighting_RunCheck_ID (final int PP_Order_Weighting_RunCheck_ID)
{
if (PP_Order_Weighting_RunCheck_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_RunCheck_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_RunCheck_ID, PP_Order_Weighting_RunCheck_ID);
}
@Override
public int getPP_Order_Weighting_RunCheck_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_RunCheck_ID);
}
@Override
public org.eevolution.model.I_PP_Order_Weighting_Run getPP_Order_Weighting_Run()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_Weighting_Run_ID, org.eevolution.model.I_PP_Order_Weighting_Run.class);
}
@Override
public void setPP_Order_Weighting_Run(final org.eevolution.model.I_PP_Order_Weighting_Run PP_Order_Weighting_Run)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Weighting_Run_ID, org.eevolution.model.I_PP_Order_Weighting_Run.class, PP_Order_Weighting_Run);
}
@Override
public void setPP_Order_Weighting_Run_ID (final int PP_Order_Weighting_Run_ID)
{ | if (PP_Order_Weighting_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, PP_Order_Weighting_Run_ID);
}
@Override
public int getPP_Order_Weighting_Run_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_Run_ID);
}
@Override
public void setWeight (final BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Weighting_RunCheck.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getShipToReferenceId()
{
return shipToReferenceId;
}
public void setShipToReferenceId(String shipToReferenceId)
{
this.shipToReferenceId = shipToReferenceId;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
ShippingStep shippingStep = (ShippingStep)o;
return Objects.equals(this.shippingCarrierCode, shippingStep.shippingCarrierCode) &&
Objects.equals(this.shippingServiceCode, shippingStep.shippingServiceCode) &&
Objects.equals(this.shipTo, shippingStep.shipTo) &&
Objects.equals(this.shipToReferenceId, shippingStep.shipToReferenceId);
}
@Override
public int hashCode()
{
return Objects.hash(shippingCarrierCode, shippingServiceCode, shipTo, shipToReferenceId);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class ShippingStep {\n");
sb.append(" shippingCarrierCode: ").append(toIndentedString(shippingCarrierCode)).append("\n");
sb.append(" shippingServiceCode: ").append(toIndentedString(shippingServiceCode)).append("\n");
sb.append(" shipTo: ").append(toIndentedString(shipTo)).append("\n"); | sb.append(" shipToReferenceId: ").append(toIndentedString(shipToReferenceId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\ShippingStep.java | 2 |
请完成以下Java代码 | public String getName()
{
return name;
}
public String getTableName()
{
return tableName;
}
@Override
public String getIconName()
{
return iconName;
}
public static PPOrderLineType cast(final IViewRowType type)
{
return (PPOrderLineType)type;
}
public boolean canReceive()
{
return canReceive;
}
public boolean canIssue()
{
return canIssue;
}
public boolean isBOMLine()
{
return this == BOMLine_Component
|| this == BOMLine_Component_Service
|| this == BOMLine_ByCoProduct;
}
public boolean isMainProduct() | {
return this == MainProduct;
}
public boolean isHUOrHUStorage()
{
return this == HU_LU
|| this == HU_TU
|| this == HU_VHU
|| this == HU_Storage;
}
public static PPOrderLineType ofHUEditorRowType(final HUEditorRowType huType)
{
final PPOrderLineType type = huType2type.get(huType);
if (type == null)
{
throw new IllegalArgumentException("No type found for " + huType);
}
return type;
}
private static final ImmutableMap<HUEditorRowType, PPOrderLineType> huType2type = Stream.of(values())
.filter(type -> type.huType != null)
.collect(GuavaCollectors.toImmutableMapByKey(type -> type.huType));
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BasicAuthenticationProvider implements AuthenticationProvider {
@Autowired
protected IdentityService identityService;
@Autowired
protected IdmIdentityService idmIdentityService;
protected boolean verifyRestApiPrivilege;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userId = authentication.getName();
String password = authentication.getCredentials().toString();
boolean authenticated = idmIdentityService.checkPassword(userId, password);
if (authenticated) {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(1);
if (isVerifyRestApiPrivilege()) {
List<Privilege> privileges = idmIdentityService.createPrivilegeQuery().userId(userId).list();
for (Privilege privilege : privileges) {
grantedAuthorities.add(new SimpleGrantedAuthority(privilege.getName()));
}
} else {
// Always add the role when it's not verified: this makes the config easier (i.e. user needs to have it)
grantedAuthorities.add(new SimpleGrantedAuthority(SecurityConstants.PRIVILEGE_ACCESS_REST_API));
} | return new UsernamePasswordAuthenticationToken(userId, password, grantedAuthorities);
} else {
throw new BadCredentialsException("Authentication failed for this username and password");
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
public boolean isVerifyRestApiPrivilege() {
return verifyRestApiPrivilege;
}
public void setVerifyRestApiPrivilege(boolean verifyRestApiPrivilege) {
this.verifyRestApiPrivilege = verifyRestApiPrivilege;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\security\BasicAuthenticationProvider.java | 2 |
请完成以下Java代码 | public class X_AD_Product_Category_BoilerPlate extends org.compiere.model.PO implements I_AD_Product_Category_BoilerPlate, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -237579600L;
/** Standard Constructor */
public X_AD_Product_Category_BoilerPlate (final Properties ctx, final int AD_Product_Category_BoilerPlate_ID, @Nullable final String trxName)
{
super (ctx, AD_Product_Category_BoilerPlate_ID, trxName);
}
/** Load Constructor */
public X_AD_Product_Category_BoilerPlate (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_Product_Category_BoilerPlate_ID (final int AD_Product_Category_BoilerPlate_ID)
{
if (AD_Product_Category_BoilerPlate_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Product_Category_BoilerPlate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Product_Category_BoilerPlate_ID, AD_Product_Category_BoilerPlate_ID);
} | @Override
public int getAD_Product_Category_BoilerPlate_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Product_Category_BoilerPlate_ID);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Product_Category_BoilerPlate.java | 1 |
请完成以下Java代码 | public void setContinueParentPlanItemInstanceMap(Map<String, PlanItemInstanceEntity> continueParentPlanItemInstanceMap) {
this.continueParentPlanItemInstanceMap = continueParentPlanItemInstanceMap;
}
public void addContinueParentPlanItemInstance(String planItemInstanceId, PlanItemInstanceEntity continueParentPlanItemInstance) {
continueParentPlanItemInstanceMap.put(planItemInstanceId, continueParentPlanItemInstance);
}
public PlanItemInstanceEntity getContinueParentPlanItemInstance(String planItemInstanceId) {
return continueParentPlanItemInstanceMap.get(planItemInstanceId);
}
public Map<String, PlanItemMoveEntry> getMoveToPlanItemMap() {
return moveToPlanItemMap;
}
public void setMoveToPlanItemMap(Map<String, PlanItemMoveEntry> moveToPlanItemMap) {
this.moveToPlanItemMap = moveToPlanItemMap;
}
public PlanItemMoveEntry getMoveToPlanItem(String planItemId) {
return moveToPlanItemMap.get(planItemId);
}
public List<PlanItemMoveEntry> getMoveToPlanItems() {
return new ArrayList<>(moveToPlanItemMap.values());
}
public static class PlanItemMoveEntry {
protected PlanItem originalPlanItem;
protected PlanItem newPlanItem; | public PlanItemMoveEntry(PlanItem originalPlanItem, PlanItem newPlanItem) {
this.originalPlanItem = originalPlanItem;
this.newPlanItem = newPlanItem;
}
public PlanItem getOriginalPlanItem() {
return originalPlanItem;
}
public PlanItem getNewPlanItem() {
return newPlanItem;
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\MovePlanItemInstanceEntityContainer.java | 1 |
请完成以下Java代码 | public Map<String, Object> getTaskLocalVariables() {
Map<String, Object> variables = new HashMap<String, Object>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() != null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<String, Object>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
} | }
}
return variables;
}
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricTaskInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
writer.writeNamespace(prefix, namespaceURI);
}
public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException {
writer.writeDefaultNamespace(namespaceURI);
}
public void writeComment(String data) throws XMLStreamException {
writer.writeComment(data);
}
public void writeProcessingInstruction(String target) throws XMLStreamException {
writer.writeProcessingInstruction(target);
}
public void writeProcessingInstruction(String target, String data) throws XMLStreamException {
writer.writeProcessingInstruction(target, data);
}
public void writeCData(String data) throws XMLStreamException {
writer.writeCData(data);
}
public void writeDTD(String dtd) throws XMLStreamException {
writer.writeDTD(dtd);
}
public void writeEntityRef(String name) throws XMLStreamException {
writer.writeEntityRef(name);
}
public void writeStartDocument() throws XMLStreamException {
writer.writeStartDocument();
}
public void writeStartDocument(String version) throws XMLStreamException {
writer.writeStartDocument(version);
}
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
writer.writeStartDocument(encoding, version);
} | public void writeCharacters(String text) throws XMLStreamException {
writer.writeCharacters(text);
}
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
writer.writeCharacters(text, start, len);
}
public String getPrefix(String uri) throws XMLStreamException {
return writer.getPrefix(uri);
}
public void setPrefix(String prefix, String uri) throws XMLStreamException {
writer.setPrefix(prefix, uri);
}
public void setDefaultNamespace(String uri) throws XMLStreamException {
writer.setDefaultNamespace(uri);
}
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
writer.setNamespaceContext(context);
}
public NamespaceContext getNamespaceContext() {
return writer.getNamespaceContext();
}
public Object getProperty(String name) throws IllegalArgumentException {
return writer.getProperty(name);
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\DelegatingXMLStreamWriter.java | 1 |
请完成以下Java代码 | public String getListenerId() {
return this.listenerId;
}
/**
* Retrieve the consumer. Only populated if the listener is consumer-aware.
* Allows the listener to resume a paused consumer.
* @return the consumer.
* @since 2.0
*/
public Consumer<?, ?> getConsumer() {
return this.consumer;
}
/**
* Return true if the consumer was paused at the time the idle event was published.
* @return paused. | * @since 2.1.5
*/
public boolean isPaused() {
return this.paused;
}
@Override
public String toString() {
return "ListenerContainerPartitionIdleEvent [idleTime="
+ ((float) this.idleTime / 1000) + "s, listenerId=" + this.listenerId // NOSONAR magic #
+ ", container=" + getSource()
+ ", paused=" + this.paused
+ ", topicPartition=" + this.topicPartition + "]";
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\ListenerContainerPartitionIdleEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Session initSmppSession() {
try {
Connection connection = new TCPIPConnection(config.getHost(), config.getPort());
Session session = new Session(connection);
BindRequest bindRequest;
switch (config.getBindType()) {
case TX:
bindRequest = new BindTransmitter();
break;
case RX:
bindRequest = new BindReceiver();
break;
case TRX:
bindRequest = new BindTransciever();
break;
default:
throw new UnsupportedOperationException("Unsupported bind type " + config.getBindType());
}
bindRequest.setSystemId(config.getSystemId());
bindRequest.setPassword(config.getPassword());
byte interfaceVersion;
switch (config.getProtocolVersion()) {
case "3.3":
interfaceVersion = Data.SMPP_V33;
break;
case "3.4":
interfaceVersion = Data.SMPP_V34;
break;
default:
throw new UnsupportedOperationException("Unsupported SMPP version: " + config.getProtocolVersion());
}
bindRequest.setInterfaceVersion(interfaceVersion);
if (StringUtils.isNotEmpty(config.getSystemType())) {
bindRequest.setSystemType(config.getSystemType());
}
if (StringUtils.isNotEmpty(config.getAddressRange())) {
bindRequest.setAddressRange(config.getDestinationTon(), config.getDestinationNpi(), config.getAddressRange());
}
BindResponse bindResponse = session.bind(bindRequest);
log.debug("SMPP bind response: {}", bindResponse.debugString());
if (bindResponse.getCommandStatus() != 0) { | throw new IllegalStateException("Error status when binding: " + bindResponse.getCommandStatus());
}
return session;
} catch (Exception e) {
throw new IllegalArgumentException("Failed to establish SMPP session: " + ExceptionUtils.getRootCauseMessage(e), e);
}
}
private String prepareNumber(String number) {
if (config.getDestinationTon() == Data.GSM_TON_INTERNATIONAL) {
return StringUtils.removeStart(number, "+");
}
return number;
}
@Override
public void destroy() {
try {
smppSession.unbind();
smppSession.close();
} catch (TimeoutException | PDUException | IOException | WrongSessionStateException e) {
throw new RuntimeException(e);
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sms\smpp\SmppSmsSender.java | 2 |
请完成以下Java代码 | public PurchaseCandidateId getSinglePurchaseCandidateIdOrNull()
{
return CollectionUtils.singleElementOrNull(getPurchaseCandidateIds());
}
public OrderAndLineId getSingleSalesOrderAndLineIdOrNull()
{
return CollectionUtils.singleElementOrNull(getSalesOrderAndLineIds());
}
public PurchaseCandidatesGroup withProfitInfo(@Nullable final PurchaseProfitInfo newProfitInfo)
{
if (Objects.equals(getProfitInfoOrNull(), newProfitInfo))
{
return this;
}
return toBuilder().profitInfoOrNull(newProfitInfo).build();
}
public BPartnerId getVendorId()
{
return getVendorProductInfo().getVendorId();
}
public String getVendorProductNo()
{
return getVendorProductInfo().getVendorProductNo();
} | public ProductId getProductId()
{
return getVendorProductInfo().getProductId();
}
public AttributeSetInstanceId getAttributeSetInstanceId()
{
return attributeSetInstanceId;
}
public boolean isAggregatePOs()
{
if (!isAllowPOAggregation())
{
return false;
}
return getVendorProductInfo().isAggregatePOs();
}
public PurchaseCandidatesGroup allowingPOAggregation(final boolean allowPOAggregation)
{
if (this.isAllowPOAggregation() == allowPOAggregation)
{
return this;
}
return toBuilder().allowPOAggregation(allowPOAggregation).build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidatesGroup.java | 1 |
请完成以下Java代码 | public abstract class PerceptronTagger extends InstanceConsumer
{
/**
* 用StructurePerceptron实现在线学习
*/
protected final StructuredPerceptron model;
public PerceptronTagger(LinearModel model)
{
assert model != null;
this.model = model instanceof StructuredPerceptron ? (StructuredPerceptron) model : new StructuredPerceptron(model.featureMap, model.parameter);
}
public PerceptronTagger(StructuredPerceptron model)
{
assert model != null;
this.model = model;
}
public LinearModel getModel()
{
return model;
}
/**
* 在线学习
*
* @param instance
* @return
*/
public boolean learn(Instance instance)
{
if (instance == null) return false;
model.update(instance);
return true;
}
/**
* 在线学习
*
* @param sentence | * @return
*/
public boolean learn(Sentence sentence)
{
return learn(createInstance(sentence, model.featureMap));
}
/**
* 性能测试
*
* @param corpora 数据集
* @return 默认返回accuracy,有些子类可能返回P,R,F1
* @throws IOException
*/
public double[] evaluate(String corpora) throws IOException
{
return evaluate(corpora, this.getModel());
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronTagger.java | 1 |
请完成以下Java代码 | public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} | public Set<String> getRole() {
return role;
}
public void setRole(Set<String> role) {
this.role = role;
}
public Set<String> getPermission() {
return permission;
}
public void setPermission(Set<String> permission) {
this.permission = permission;
}
} | repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\domain\User.java | 1 |
请完成以下Java代码 | private static void encrypt(String plainText, Key key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(ENCRYPT_MODE, key);
byte[] cipherTextBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
logger.info(Base64.getEncoder().encodeToString(cipherTextBytes));
}
private static Key getRandomKey(String cipher, int keySize) {
byte[] randomKeyBytes = new byte[keySize / 8];
Random random = new Random();
random.nextBytes(randomKeyBytes);
return new SecretKeySpec(randomKeyBytes, cipher);
}
private static Key getSecureRandomKey(String cipher, int keySize) {
byte[] secureRandomKeyBytes = new byte[keySize / 8];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(secureRandomKeyBytes); | return new SecretKeySpec(secureRandomKeyBytes, cipher);
}
private static Key getKeyFromKeyGenerator(String cipher, int keySize) throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(cipher);
keyGenerator.init(keySize);
return keyGenerator.generateKey();
}
private static Key getPasswordBasedKey(String cipher, int keySize, char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] salt = new byte[100];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password, salt, 100000, keySize);
SecretKey pbeKey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(pbeKeySpec);
return new SecretKeySpec(pbeKey.getEncoded(), cipher);
}
} | repos\tutorials-master\core-java-modules\core-java-security-3\src\main\java\com\baeldung\secretkey\Main.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void seedCustomers() {
String[] queries = {
"INSERT INTO customers(email, name, contact) VALUES('John Smith','john.smith@example.com','+12126781345');",
"INSERT INTO customers(email, name, contact) VALUES('Mike Ross','mike.ross@example.com','+15466711147');",
"INSERT INTO customers(email, name, contact) VALUES('Martha Williams','martha.williams@example.com','+12790581941');"
};
for (String query : queries) {
execute(query);
}
}
private void seedRestaurants() {
String[] add = {
"5331 Redford Court, Montgomery AL 36116",
"43 West 4th Street, New York NY 10024",
"1693 Alice Court, Annapolis MD 21401"
};
String[] queries = {
"INSERT INTO restaurants(name, address, contact) VALUES('Mikes','+12121231345','" + add[0] + "');",
"INSERT INTO restaurants(name, address, contact) VALUES('Tamarind','+12412311147','" + add[1] + "');",
"INSERT INTO restaurants(name, address, contact) VALUES('Thai Place','+14790981941','" + add[2] + "');",
};
for (String query : queries) {
execute(query);
}
}
private void seedDrivers() {
String[] queries = {
"INSERT INTO drivers(name,contact) VALUES('Wayne Stevens','+12520711467');", | "INSERT INTO drivers(name,contact) VALUES('Jim Willis','+16466281981');",
"INSERT INTO drivers(name,contact) VALUES('Steven Carroll','+12612590430');",
"INSERT INTO drivers(name,contact) VALUES('Tom Cruise','+18659581430');"
};
for (String query : queries) {
execute(query);
}
}
boolean tableExists(String tableName) {
try {
Connection conn = DriverManager.getConnection(this.url);
DatabaseMetaData meta = conn.getMetaData();
ResultSet resultSet = meta.getTables(null, null, tableName, new String[] {"TABLE"});
boolean exists = resultSet.next();
conn.close();
return exists;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return false;
}
} | repos\tutorials-master\microservices-modules\saga-pattern\src\main\java\io\orkes\example\saga\dao\BaseDAO.java | 2 |
请完成以下Java代码 | public void resetCacheFor(@NonNull final I_DataEntry_Line dataEntryLineRecord)
{
if (dataEntryLineRecord.getDataEntry_Section_ID() > 0)
{
resetCacheFor(dataEntryLineRecord.getDataEntry_Section());
}
}
public void resetCacheFor(@NonNull final I_DataEntry_Section dataEntrySectionRecord)
{
if (dataEntrySectionRecord.getDataEntry_SubTab_ID() > 0)
{
resetCacheFor(dataEntrySectionRecord.getDataEntry_SubTab());
}
}
public void resetCacheFor(@NonNull final I_DataEntry_SubTab dataEntrySubGroupRecord)
{
if (dataEntrySubGroupRecord.getDataEntry_Tab_ID() > 0)
{ | resetCacheFor(dataEntrySubGroupRecord.getDataEntry_Tab());
}
}
public void resetCacheFor(@NonNull final I_DataEntry_Tab dataEntryGroupRecord)
{
final int windowId = dataEntryGroupRecord.getDataEntry_TargetWindow_ID();
if (windowId > 0)
{
documentDescriptorFactory.invalidateForWindow(WindowId.of(windowId));
final boolean forgetNotSavedDocuments = false;
documentCollection.cacheReset(forgetNotSavedDocuments);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\interceptor\DataEntryInterceptorUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String apiKeyValue = tokenExtractor.extract(request);
ApiKeyAuthRequest apiKeyAuthRequest = new ApiKeyAuthRequest(apiKeyValue);
return getAuthenticationManager().authenticate(new ApiKeyAuthenticationToken(apiKeyAuthRequest));
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authResult);
SecurityContextHolder.setContext(context);
chain.doFilter(request, response);
}
@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
if (!super.requiresAuthentication(request, response)) {
return false; | }
String header = request.getHeader(AUTHORIZATION_HEADER);
if (header == null) {
header = request.getHeader(AUTHORIZATION_HEADER_V2);
}
return header != null && header.startsWith(API_KEY_HEADER_PREFIX);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
SecurityContextHolder.clearContext();
failureHandler.onAuthenticationFailure(request, response, failed);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\pat\ApiKeyTokenAuthenticationProcessingFilter.java | 2 |
请完成以下Java代码 | public class TbTenantRuleEngineStats {
private final UUID tenantId;
private final AtomicInteger totalMsgCounter = new AtomicInteger(0);
private final AtomicInteger successMsgCounter = new AtomicInteger(0);
private final AtomicInteger tmpTimeoutMsgCounter = new AtomicInteger(0);
private final AtomicInteger tmpFailedMsgCounter = new AtomicInteger(0);
private final AtomicInteger timeoutMsgCounter = new AtomicInteger(0);
private final AtomicInteger failedMsgCounter = new AtomicInteger(0);
private final Map<String, AtomicInteger> counters = new HashMap<>();
public TbTenantRuleEngineStats(UUID tenantId) {
this.tenantId = tenantId;
counters.put(TbRuleEngineConsumerStats.TOTAL_MSGS, totalMsgCounter);
counters.put(TbRuleEngineConsumerStats.SUCCESSFUL_MSGS, successMsgCounter);
counters.put(TbRuleEngineConsumerStats.TIMEOUT_MSGS, timeoutMsgCounter);
counters.put(TbRuleEngineConsumerStats.FAILED_MSGS, failedMsgCounter);
counters.put(TbRuleEngineConsumerStats.TMP_TIMEOUT, tmpTimeoutMsgCounter);
counters.put(TbRuleEngineConsumerStats.TMP_FAILED, tmpFailedMsgCounter);
}
public void logSuccess() {
totalMsgCounter.incrementAndGet();
successMsgCounter.incrementAndGet();
}
public void logFailed() {
totalMsgCounter.incrementAndGet();
failedMsgCounter.incrementAndGet();
}
public void logTimeout() {
totalMsgCounter.incrementAndGet(); | timeoutMsgCounter.incrementAndGet();
}
public void logTmpFailed() {
totalMsgCounter.incrementAndGet();
tmpFailedMsgCounter.incrementAndGet();
}
public void logTmpTimeout() {
totalMsgCounter.incrementAndGet();
tmpTimeoutMsgCounter.incrementAndGet();
}
public void printStats() {
int total = totalMsgCounter.get();
if (total > 0) {
StringBuilder stats = new StringBuilder();
counters.forEach((label, value) -> {
stats.append(label).append(" = [").append(value.get()).append("]");
});
log.info("[{}] Stats: {}", tenantId, stats);
}
}
public void reset() {
counters.values().forEach(counter -> counter.set(0));
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbTenantRuleEngineStats.java | 1 |
请完成以下Java代码 | public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String firstName;
private String lastName;
/** Default constructor for JSON serialization */
public Student() {
}
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
} | public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Student student = (Student) o;
return Objects.equals(firstName, student.firstName) && Objects.equals(lastName, student.lastName);
}
@Override
public int hashCode() {
return super.hashCode();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-7\src\main\java\com\baeldung\map\readandwritefile\Student.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SysUserServiceImpl implements SysUserService {
private final SysUserRepository sysUserRepository;
private final PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser sysUser = sysUserRepository.findFirstByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found!"));
List<SimpleGrantedAuthority> roles = sysUser.getRoles().stream().map(sysRole -> new SimpleGrantedAuthority(sysRole.getName())).collect(Collectors.toList());
// 在这里手动构建 UserDetails 的默认实现
return new User(sysUser.getUsername(), sysUser.getPassword(), roles);
}
@Override
public List<SysUser> findAll() {
return sysUserRepository.findAll();
}
@Override
public SysUser findById(Long id) {
return sysUserRepository.findById(id).orElseThrow(() -> new RuntimeException("找不到用户"));
}
@Override | public void createUser(SysUser sysUser) {
sysUser.setId(null);
sysUserRepository.save(sysUser);
}
@Override
public void updateUser(SysUser sysUser) {
sysUser.setPassword(null);
sysUserRepository.save(sysUser);
}
@Override
public void updatePassword(Long id, String password) {
SysUser exist = findById(id);
exist.setPassword(passwordEncoder.encode(password));
sysUserRepository.save(exist);
}
@Override
public void deleteUser(Long id) {
sysUserRepository.deleteById(id);
}
} | repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\service\impl\SysUserServiceImpl.java | 2 |
请完成以下Java代码 | public FeelException unableToInitializeFeelEngine(Throwable cause) {
return new FeelException(exceptionMessage(
"011",
"Unable to initialize FEEL engine"),
cause
);
}
public FeelException unableToEvaluateExpression(String simpleUnaryTests, Throwable cause) {
return new FeelException(exceptionMessage(
"012",
"Unable to evaluate expression '{}'", simpleUnaryTests),
cause
);
}
public FeelConvertException unableToConvertValue(Object value, Class<?> type) {
return new FeelConvertException(exceptionMessage(
"013",
"Unable to convert value '{}' of type '{}' to type '{}'", value, value.getClass(), type),
value, type
);
}
public FeelConvertException unableToConvertValue(Object value, Class<?> type, Throwable cause) {
return new FeelConvertException(exceptionMessage(
"014",
"Unable to convert value '{}' of type '{}' to type '{}'", value, value.getClass(), type),
value, type, cause
);
}
public FeelConvertException unableToConvertValue(String feelExpression, FeelConvertException cause) {
Object value = cause.getValue();
Class<?> type = cause.getType();
return new FeelConvertException(exceptionMessage(
"015",
"Unable to convert value '{}' of type '{}' to type '{}' in expression '{}'", value, value.getClass(), type, feelExpression),
cause
);
} | public UnsupportedOperationException simpleExpressionNotSupported() {
return new UnsupportedOperationException(exceptionMessage(
"016",
"Simple Expression not supported by FEEL engine")
);
}
public FeelException unableToEvaluateExpressionAsNotInputIsSet(String simpleUnaryTests, FeelMissingVariableException e) {
return new FeelException(exceptionMessage(
"017",
"Unable to evaluate expression '{}' as no input is set. Maybe the inputExpression is missing or empty.", simpleUnaryTests),
e
);
}
public FeelMethodInvocationException invalidDateAndTimeFormat(String dateTimeString, Throwable cause) {
return new FeelMethodInvocationException(exceptionMessage(
"018",
"Invalid date and time format in '{}'", dateTimeString),
cause, "date and time", dateTimeString
);
}
public FeelMethodInvocationException unableToInvokeMethod(String simpleUnaryTests, FeelMethodInvocationException cause) {
String method = cause.getMethod();
String[] parameters = cause.getParameters();
return new FeelMethodInvocationException(exceptionMessage(
"019",
"Unable to invoke method '{}' with parameters '{}' in expression '{}'", method, parameters, simpleUnaryTests),
cause.getCause(), method, parameters
);
}
public FeelSyntaxException invalidListExpression(String feelExpression) {
String description = "List expression can not have empty elements";
return syntaxException("020", feelExpression, description);
}
} | repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\FeelEngineLogger.java | 1 |
请完成以下Java代码 | public int getM_Replenish_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Replenish_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
/**
* ReplenishType AD_Reference_ID=164
* Reference name: M_Replenish Type
*/
public static final int REPLENISHTYPE_AD_Reference_ID=164;
/** Maximalbestand beibehalten = 2 */
public static final String REPLENISHTYPE_MaximalbestandBeibehalten = "2";
/** Manuell = 0 */
public static final String REPLENISHTYPE_Manuell = "0";
/** Bei Unterschreitung Minimalbestand = 1 */
public static final String REPLENISHTYPE_BeiUnterschreitungMinimalbestand = "1";
/** Custom = 9 */
public static final String REPLENISHTYPE_Custom = "9";
/** Zuk?nftigen Bestand sichern = 7 */
public static final String REPLENISHTYPE_ZukNftigenBestandSichern = "7";
@Override
public void setReplenishType (final java.lang.String ReplenishType) | {
set_Value (COLUMNNAME_ReplenishType, ReplenishType);
}
@Override
public java.lang.String getReplenishType()
{
return get_ValueAsString(COLUMNNAME_ReplenishType);
}
@Override
public void setTimeToMarket (final int TimeToMarket)
{
set_Value (COLUMNNAME_TimeToMarket, TimeToMarket);
}
@Override
public int getTimeToMarket()
{
return get_ValueAsInt(COLUMNNAME_TimeToMarket);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Replenish.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MoveSuspendedJobToExecutableJobCmd implements Command<Job>, Serializable {
private static final long serialVersionUID = 1L;
protected String jobId;
protected JobServiceConfiguration jobServiceConfiguration;
public MoveSuspendedJobToExecutableJobCmd(String jobId, JobServiceConfiguration jobServiceConfiguration) {
this.jobId = jobId;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Job execute(CommandContext commandContext) {
if (jobId == null) { | throw new FlowableIllegalArgumentException("jobId and job is null");
}
SuspendedJobEntity job = jobServiceConfiguration.getSuspendedJobEntityManager().findById(jobId);
if (job == null) {
throw new JobNotFoundException(jobId);
}
return jobServiceConfiguration.getJobService().activateSuspendedJob(job);
}
public String getJobId() {
return jobId;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\MoveSuspendedJobToExecutableJobCmd.java | 2 |
请完成以下Java代码 | public static String getExpressionLanguage(DmnElementTransformContext context, LiteralExpression expression) {
return getExpressionLanguage(context, expression.getExpressionLanguage());
}
public static String getExpressionLanguage(DmnElementTransformContext context, UnaryTests expression) {
return getExpressionLanguage(context, expression.getExpressionLanguage());
}
protected static String getExpressionLanguage(DmnElementTransformContext context, String expressionLanguage) {
if (expressionLanguage != null) {
return expressionLanguage;
}
else {
return getGlobalExpressionLanguage(context);
}
}
protected static String getGlobalExpressionLanguage(DmnElementTransformContext context) {
String expressionLanguage = context.getModelInstance().getDefinitions().getExpressionLanguage();
if (!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN12.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN13.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN14.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN15.equals(expressionLanguage)) {
return expressionLanguage;
}
else {
return null;
}
}
public static String getExpression(LiteralExpression expression) {
return getExpression(expression.getText()); | }
public static String getExpression(UnaryTests expression) {
return getExpression(expression.getText());
}
protected static String getExpression(Text text) {
if (text != null) {
String textContent = text.getTextContent();
if (textContent != null && !textContent.isEmpty()) {
return textContent;
}
}
return null;
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DmnExpressionTransformHelper.java | 1 |
请完成以下Java代码 | public CardinalityOrderComparator<T> build()
{
return new CardinalityOrderComparator<>(this);
}
/**
* Convenient method to copy and sort a given list.
*
* @param list
* @return sorted list (as a new copy)
*/
public List<T> copyAndSort(final List<T> list)
{
final CardinalityOrderComparator<T> comparator = build();
final List<T> listSorted = new ArrayList<>(list);
Collections.sort(listSorted, comparator);
return listSorted;
}
/** | * Sets the list of all items.
* When sorting, this is the list which will give the cardinality of a given item (i.e. the indexOf).
*
* WARNING: the given cardinality list will be used on line, as it is and it won't be copied, because we don't know what indexOf implementation to use.
* So, please make sure you are not chaning the list in meantime.
*
* @param cardinalityList
* @return
*/
public Builder<T> setCardinalityList(final List<T> cardinalityList)
{
this.cardinalityList = cardinalityList;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\CardinalityOrderComparator.java | 1 |
请完成以下Java代码 | public RateType4Choice getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link RateType4Choice }
*
*/
public void setTp(RateType4Choice value) {
this.tp = value;
}
/**
* Gets the value of the vldtyRg property.
*
* @return
* possible object is
* {@link CurrencyAndAmountRange2 }
*
*/ | public CurrencyAndAmountRange2 getVldtyRg() {
return vldtyRg;
}
/**
* Sets the value of the vldtyRg property.
*
* @param value
* allowed object is
* {@link CurrencyAndAmountRange2 }
*
*/
public void setVldtyRg(CurrencyAndAmountRange2 value) {
this.vldtyRg = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\Rate3.java | 1 |
请完成以下Java代码 | public Response getPasswordPolicy() {
boolean isEnabled = getProcessEngine().getProcessEngineConfiguration().isEnablePasswordPolicy();
if (isEnabled) {
IdentityService identityService = getProcessEngine().getIdentityService();
return Response.status(Status.OK.getStatusCode())
.entity(PasswordPolicyDto.fromPasswordPolicy(identityService.getPasswordPolicy()))
.build();
} else {
return Response.status(Status.NOT_FOUND.getStatusCode()).build();
}
}
@Override
public Response checkPassword(PasswordPolicyRequestDto dto) {
boolean isEnabled = getProcessEngine().getProcessEngineConfiguration().isEnablePasswordPolicy();
if (isEnabled) {
IdentityService identityService = getProcessEngine().getIdentityService();
User user = null;
UserProfileDto profileDto = dto.getProfile();
if (profileDto != null) {
String id = sanitizeUserId(profileDto.getId());
user = identityService.newUser(id); | user.setFirstName(profileDto.getFirstName());
user.setLastName(profileDto.getLastName());
user.setEmail(profileDto.getEmail());
}
String candidatePassword = dto.getPassword();
PasswordPolicyResult result = identityService.checkPasswordAgainstPolicy(candidatePassword, user);
return Response.status(Status.OK.getStatusCode())
.entity(CheckPasswordPolicyResultDto.fromPasswordPolicyResult(result))
.build();
} else {
return Response.status(Status.NOT_FOUND.getStatusCode()).build();
}
}
protected String sanitizeUserId(String userId) {
return userId != null ? userId : "";
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\IdentityRestServiceImpl.java | 1 |
请完成以下Java代码 | public void setMeta_RobotsTag (String Meta_RobotsTag)
{
set_Value (COLUMNNAME_Meta_RobotsTag, Meta_RobotsTag);
}
/** Get Meta RobotsTag.
@return RobotsTag defines how search robots should handle this content
*/
public String getMeta_RobotsTag ()
{
return (String)get_Value(COLUMNNAME_Meta_RobotsTag);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject.java | 1 |
请完成以下Java代码 | public AlbertaCaregiver save(final @NonNull AlbertaCaregiver caregiver)
{
final I_C_BPartner_AlbertaCareGiver record = InterfaceWrapperHelper.loadOrNew(caregiver.getBPartnerAlbertaCaregiverId(), I_C_BPartner_AlbertaCareGiver.class);
record.setC_BPartner_ID(caregiver.getBPartnerId().getRepoId());
record.setC_BPartner_Caregiver_ID(caregiver.getCaregiverId().getRepoId());
record.setIsLegalCarer(caregiver.isLegalCarer());
record.setType_Contact(caregiver.getType() != null ? caregiver.getType().getCode() : null);
InterfaceWrapperHelper.save(record);
return toAlbertaCaregiver(record);
}
@NonNull
public Optional<AlbertaCaregiver> getByPatientAndCaregiver(
@NonNull final BPartnerId patientId,
@NonNull final BPartnerId caregiverId)
{
return queryBL.createQueryBuilder(I_C_BPartner_AlbertaCareGiver.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BPartner_AlbertaCareGiver.COLUMNNAME_C_BPartner_ID, patientId)
.addEqualsFilter(I_C_BPartner_AlbertaCareGiver.COLUMNNAME_C_BPartner_Caregiver_ID, caregiverId)
.create() | .firstOnlyOptional(I_C_BPartner_AlbertaCareGiver.class)
.map(this::toAlbertaCaregiver);
}
@NonNull
public AlbertaCaregiver toAlbertaCaregiver(@NonNull final I_C_BPartner_AlbertaCareGiver record)
{
final BPartnerAlbertaCaregiverId bPartnerAlbertaCaregiverId = BPartnerAlbertaCaregiverId.ofRepoId(record.getC_BPartner_AlbertaCareGiver_ID());
final BPartnerId bPartnerId = BPartnerId.ofRepoId(record.getC_BPartner_ID());
final BPartnerId caregiverId = BPartnerId.ofRepoId(record.getC_BPartner_Caregiver_ID());
return AlbertaCaregiver.builder()
.bPartnerAlbertaCaregiverId(bPartnerAlbertaCaregiverId)
.bPartnerId(bPartnerId)
.caregiverId(caregiverId)
.type(CaregiverType.ofCodeNullable(record.getType_Contact()))
.isLegalCarer(record.isLegalCarer())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\bpartner\caregiver\AlbertaCaregiverRepository.java | 1 |
请完成以下Java代码 | public abstract class CompilationUnit<T extends TypeDeclaration> {
private final String packageName;
private final String name;
private final List<T> typeDeclarations = new ArrayList<>();
/**
* Create a new instance with the package to use and the name of the type.
* @param packageName the package in which the source file should be located
* @param name the name of the file
*/
public CompilationUnit(String packageName, String name) {
Assert.hasText(packageName, "'packageName' must not be null");
Assert.hasText(name, "'name' must not be null");
this.packageName = packageName;
this.name = name;
}
/**
* Return the package name in which the file should reside.
* @return the package name
*/
public String getPackageName() {
return this.packageName;
} | /**
* Return the name of the source file.
* @return the name of the source file
*/
public String getName() {
return this.name;
}
public T createTypeDeclaration(String name) {
T typeDeclaration = doCreateTypeDeclaration(name);
this.typeDeclarations.add(typeDeclaration);
return typeDeclaration;
}
public List<T> getTypeDeclarations() {
return Collections.unmodifiableList(this.typeDeclarations);
}
protected abstract T doCreateTypeDeclaration(String name);
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\CompilationUnit.java | 1 |
请完成以下Java代码 | public ParallelGateway newInstance(ModelTypeInstanceContext instanceContext) {
return new ParallelGatewayImpl(instanceContext);
}
});
/** camunda extensions */
camundaAsyncAttribute = typeBuilder.booleanAttribute(CAMUNDA_ATTRIBUTE_ASYNC)
.namespace(CAMUNDA_NS)
.defaultValue(false)
.build();
typeBuilder.build();
}
@Override
public ParallelGatewayBuilder builder() {
return new ParallelGatewayBuilder((BpmnModelInstance) modelInstance, this);
}
/** camunda extensions */
/**
* @deprecated use isCamundaAsyncBefore() instead.
*/
@Deprecated
public boolean isCamundaAsync() {
return camundaAsyncAttribute.getValue(this); | }
/**
* @deprecated use setCamundaAsyncBefore(isCamundaAsyncBefore) instead.
*/
@Deprecated
public void setCamundaAsync(boolean isCamundaAsync) {
camundaAsyncAttribute.setValue(this, isCamundaAsync);
}
public ParallelGatewayImpl(ModelTypeInstanceContext context) {
super(context);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ParallelGatewayImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "http://localhost:8182/runtime/executions/5")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "null")
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
@ApiModelProperty(example = "null")
public String getParentUrl() {
return parentUrl;
}
public void setParentUrl(String parentUrl) {
this.parentUrl = parentUrl;
}
@ApiModelProperty(example = "null")
public String getSuperExecutionId() {
return superExecutionId;
}
public void setSuperExecutionId(String superExecutionId) {
this.superExecutionId = superExecutionId;
}
@ApiModelProperty(example = "null")
public String getSuperExecutionUrl() {
return superExecutionUrl;
}
public void setSuperExecutionUrl(String superExecutionUrl) {
this.superExecutionUrl = superExecutionUrl;
}
@ApiModelProperty(example = "5")
public String getProcessInstanceId() {
return processInstanceId;
} | public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@ApiModelProperty(example = "http://localhost:8182/runtime/process-instances/5")
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
public boolean isSuspended() {
return suspended;
}
public void setSuspended(boolean suspended) {
this.suspended = suspended;
}
@ApiModelProperty(example = "null")
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionResponse.java | 2 |
请完成以下Java代码 | void okB_actionPerformed(ActionEvent e) {
this.dispose();
}
void cancelB_actionPerformed(ActionEvent e) {
CANCELLED = true;
this.dispose();
}
void fontChanged(ActionEvent e) {
int[] sizes = {8,10,13,16,18,24,32};
int size = 16;
String face;
Font font = sample.getFont();
if (fontSizeCB.getSelectedIndex() > 0)
size = sizes[fontSizeCB.getSelectedIndex()-1];
if (fontFamilyCB.getSelectedIndex() >0)
face = (String)fontFamilyCB.getSelectedItem();
else face = font.getName();
sample.setFont(new Font(face,Font.PLAIN, size));
}
void colorB_actionPerformed(ActionEvent e) {
// Fix until Sun's JVM supports more locales...
UIManager.put(
"ColorChooser.swatchesNameText",
Local.getString("Swatches"));
UIManager.put("ColorChooser.hsbNameText", Local.getString("HSB"));
UIManager.put("ColorChooser.rgbNameText", Local.getString("RGB"));
UIManager.put(
"ColorChooser.swatchesRecentText",
Local.getString("Recent:"));
UIManager.put("ColorChooser.previewText", Local.getString("Preview")); | UIManager.put(
"ColorChooser.sampleText",
Local.getString("Sample Text")
+ " "
+ Local.getString("Sample Text"));
UIManager.put("ColorChooser.okText", Local.getString("OK"));
UIManager.put("ColorChooser.cancelText", Local.getString("Cancel"));
UIManager.put("ColorChooser.resetText", Local.getString("Reset"));
UIManager.put("ColorChooser.hsbHueText", Local.getString("H"));
UIManager.put("ColorChooser.hsbSaturationText", Local.getString("S"));
UIManager.put("ColorChooser.hsbBrightnessText", Local.getString("B"));
UIManager.put("ColorChooser.hsbRedText", Local.getString("R"));
UIManager.put("ColorChooser.hsbGreenText", Local.getString("G"));
UIManager.put("ColorChooser.hsbBlueText", Local.getString("B2"));
UIManager.put("ColorChooser.rgbRedText", Local.getString("Red"));
UIManager.put("ColorChooser.rgbGreenText", Local.getString("Green"));
UIManager.put("ColorChooser.rgbBlueText", Local.getString("Blue"));
Color c = JColorChooser.showDialog(this, Local.getString("Font color"),
Util.decodeColor(colorField.getText()));
if (c == null) return;
colorField.setText(Util.encodeColor(c));
Util.setColorField(colorField);
sample.setForeground(c);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\FontDialog.java | 1 |
请完成以下Java代码 | public void shutdown() {
if (scheduledExecutorService != null) {
scheduledExecutorService.shutdown();
}
}
protected Runnable createChangeDetectionRunnable() {
return new EventRegistryChangeDetectionRunnable(eventRegistryChangeDetectionManager);
}
public ScheduledExecutorService getScheduledExecutorService() {
return scheduledExecutorService;
}
public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) {
this.scheduledExecutorService = scheduledExecutorService;
}
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName; | }
public Runnable getChangeDetectionRunnable() {
return changeDetectionRunnable;
}
public void setChangeDetectionRunnable(Runnable changeDetectionRunnable) {
this.changeDetectionRunnable = changeDetectionRunnable;
}
public EventRegistryChangeDetectionManager getEventRegistryChangeDetectionManager() {
return eventRegistryChangeDetectionManager;
}
@Override
public void setEventRegistryChangeDetectionManager(EventRegistryChangeDetectionManager eventRegistryChangeDetectionManager) {
this.eventRegistryChangeDetectionManager = eventRegistryChangeDetectionManager;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\management\DefaultEventRegistryChangeDetectionExecutor.java | 1 |
请完成以下Java代码 | protected void doAfterPropertiesSet() throws Exception {
Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD);
}
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
CustomAuthenticationToken auth = (CustomAuthenticationToken) authentication;
UserDetails loadedUser;
try {
loadedUser = this.userDetailsService.loadUserByUsernameAndDomain(auth.getPrincipal()
.toString(), auth.getDomain());
} catch (UsernameNotFoundException notFound) {
if (authentication.getCredentials() != null) { | String presentedPassword = authentication.getCredentials()
.toString();
passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword);
}
throw notFound;
} catch (Exception repositoryProblem) {
throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
}
if (loadedUser == null) {
throw new InternalAuthenticationServiceException("UserDetailsService returned null, "
+ "which is an interface contract violation");
}
return loadedUser;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\loginextrafieldscustom\CustomUserDetailsAuthenticationProvider.java | 1 |
请完成以下Java代码 | public class SyntheticMethodDemo {
/**
* Class which contains two synthetic methods accessors to a private field.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* Field for which will be generated synthetic methods accessors. It's
* important that this field is private for this purpose.
*/
private String nestedField;
}
/**
* Gets the private nested field. We need to read the nested field in order | * to generate the synthetic getter.
*
* @return the {@link NestedClass#nestedField}
*/
public String getNestedField() {
return new NestedClass().nestedField;
}
/**
* Sets the private nested field. We need to write the nested field in order
* to generate the synthetic setter.
*
* @param nestedField
* the {@link NestedClass#nestedField}
*/
public void setNestedField(String nestedField) {
new NestedClass().nestedField = nestedField;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-8\src\main\java\com\baeldung\synthetic\SyntheticMethodDemo.java | 1 |
请完成以下Java代码 | public class HttpClientHeader {
public static HttpResponse<String> callWithCustomHeader(String url) throws URISyntaxException, IOException, InterruptedException {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.header("X-Our-Header-1", "value1")
.header("X-Our-Header-1", "value2")
.header("X-Our-Header-2", "value2")
.uri(new URI(url)).build();
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
public static HttpResponse<String> callWithCustomHeaderV2(String url) throws URISyntaxException, IOException, InterruptedException {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.headers("X-Our-Header-1", "value1", "X-Our-Header-1", "value2")
.uri(new URI(url)).build();
return httpClient.send(request, HttpResponse.BodyHandlers.ofString()); | }
public static HttpResponse<String> callWithCustomHeaderV3(String url) throws URISyntaxException, IOException, InterruptedException {
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.setHeader("X-Our-Header-1", "value1")
.setHeader("X-Our-Header-1", "value2")
.uri(new URI(url)).build();
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
} | repos\tutorials-master\core-java-modules\core-java-httpclient\src\main\java\com\baeldung\httpclient\HttpClientHeader.java | 1 |
请完成以下Java代码 | public String getAMQPQueueNameByTopicName(@NonNull final String topicName)
{
return queueConfigs.getByTopicNameOrDefault(topicName).getQueueName();
}
@NonNull
public String getAMQPExchangeNameByTopicName(@NonNull final String topicName)
{
return queueConfigs.getByTopicNameOrDefault(topicName).getExchangeName();
}
//
//
// -------------------------------------------------------------------------
//
//
@ToString(of = { "byTopicName", "defaultQueueConfiguration" })
private static class QueueConfigurationsMap
{
private final ImmutableList<IEventBusQueueConfiguration> list;
private final ImmutableMap<String, IEventBusQueueConfiguration> byTopicName;
private final IEventBusQueueConfiguration defaultQueueConfiguration;
QueueConfigurationsMap(final List<IEventBusQueueConfiguration> list)
{
final ImmutableMap.Builder<String, IEventBusQueueConfiguration> byTopicName = ImmutableMap.builder();
final ArrayList<DefaultQueueConfiguration> defaultQueueConfigurations = new ArrayList<>();
for (final IEventBusQueueConfiguration queueConfig : list)
{
queueConfig.getTopicName().ifPresent(topicName -> byTopicName.put(topicName, queueConfig));
if (queueConfig instanceof DefaultQueueConfiguration)
{
defaultQueueConfigurations.add((DefaultQueueConfiguration)queueConfig);
}
}
if (defaultQueueConfigurations.size() != 1)
{
throw new AdempiereException("There shall be exactly one default queue configuration but found " + defaultQueueConfigurations)
.setParameter("all configurations", list)
.appendParametersToMessage();
}
this.list = ImmutableList.copyOf(list);
this.byTopicName = byTopicName.build();
this.defaultQueueConfiguration = CollectionUtils.singleElement(defaultQueueConfigurations);
}
@Nullable
public IEventBusQueueConfiguration getByTopicNameOrNull(@NonNull final String topicName)
{
return byTopicName.get(topicName);
}
@NonNull
public IEventBusQueueConfiguration getByTopicNameOrDefault(@NonNull final String topicName) | {
return byTopicName.getOrDefault(topicName, defaultQueueConfiguration);
}
public QueueConfigurationsMap withQueueAdded(@NonNull final IEventBusQueueConfiguration queueConfig)
{
final ArrayList<IEventBusQueueConfiguration> newList = new ArrayList<>(list);
newList.add(queueConfig);
return new QueueConfigurationsMap(newList);
}
public QueueConfigurationsMap withQueueRemovedByTopicName(@NonNull final String topicName)
{
final IEventBusQueueConfiguration queueConfig = getByTopicNameOrNull(topicName);
return queueConfig != null ? withQueueRemoved(queueConfig) : this;
}
public QueueConfigurationsMap withQueueRemoved(@NonNull final IEventBusQueueConfiguration queueConfig)
{
final ArrayList<IEventBusQueueConfiguration> newList = new ArrayList<>(list);
newList.remove(queueConfig);
return new QueueConfigurationsMap(newList);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\RabbitMQDestinationResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<DashboardInfo> getDashboardsByIds(@Parameter(description = "A list of dashboard ids, separated by comma ','", array = @ArraySchema(schema = @Schema(type = "string")), required = true)
@RequestParam("dashboardIds") Set<UUID> dashboardUUIDs) throws ThingsboardException {
TenantId tenantId = getCurrentUser().getTenantId();
List<DashboardId> dashboardIds = new ArrayList<>();
for (UUID dashboardUUID : dashboardUUIDs) {
dashboardIds.add(new DashboardId(dashboardUUID));
}
List<DashboardInfo> dashboards = dashboardService.findDashboardInfoByIds(tenantId, dashboardIds);
return filterDashboardsByReadPermission(dashboards);
}
private Set<CustomerId> customerIdFromStr(String[] strCustomerIds) {
Set<CustomerId> customerIds = new HashSet<>();
if (strCustomerIds != null) {
for (String strCustomerId : strCustomerIds) {
customerIds.add(new CustomerId(UUID.fromString(strCustomerId)));
} | }
return customerIds;
}
private List<DashboardInfo> filterDashboardsByReadPermission(List<DashboardInfo> dashboards) {
return dashboards.stream().filter(dashboard -> {
try {
return accessControlService.hasPermission(getCurrentUser(), Resource.DASHBOARD, Operation.READ, dashboard.getId(), dashboard);
} catch (ThingsboardException e) {
return false;
}
}).collect(Collectors.toList());
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\DashboardController.java | 2 |
请完成以下Java代码 | private void onSessionUnsubribeEvent(final SessionUnsubscribeEvent event)
{
final WebsocketSubscriptionId subscriptionId = extractUniqueSubscriptionId(event);
final WebsocketTopicName topicName = activeSubscriptionsIndex.removeSubscriptionAndGetTopicName(subscriptionId);
websocketProducersRegistry.onTopicUnsubscribed(subscriptionId, topicName);
logger.debug("Unsubscribed from topicName={} [ subscriptionId={} ]", topicName, subscriptionId);
}
private void onSessionDisconnectEvent(final SessionDisconnectEvent event)
{
final WebsocketSessionId sessionId = WebsocketSessionId.ofString(event.getSessionId());
final Set<WebsocketTopicName> topicNames = activeSubscriptionsIndex.removeSessionAndGetTopicNames(sessionId);
websocketProducersRegistry.onSessionDisconnect(sessionId, topicNames);
logger.debug("Disconnected from topicName={} [ sessionId={} ]", topicNames, sessionId);
}
private static WebsocketTopicName extractTopicName(final AbstractSubProtocolEvent event)
{
return WebsocketTopicName.ofString(SimpMessageHeaderAccessor.getDestination(event.getMessage().getHeaders())); | }
private static WebsocketSubscriptionId extractUniqueSubscriptionId(final AbstractSubProtocolEvent event)
{
final MessageHeaders headers = event.getMessage().getHeaders();
final WebsocketSessionId sessionId = WebsocketSessionId.ofString(SimpMessageHeaderAccessor.getSessionId(headers));
final String simpSubscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
return WebsocketSubscriptionId.of(sessionId, Objects.requireNonNull(simpSubscriptionId, "simpSubscriptionId"));
}
@NonNull
private static Map<String, List<String>> extractNativeHeaders(@NonNull final AbstractSubProtocolEvent event)
{
final Object nativeHeaders = event.getMessage().getHeaders().get("nativeHeaders");
return Optional.ofNullable(nativeHeaders)
.filter(headers -> headers instanceof Map)
.filter(headers -> !((Map<?, ?>)headers).isEmpty())
.map(headers -> (Map<String, List<String>>)headers)
.map(ImmutableMap::copyOf)
.orElseGet(ImmutableMap::of);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\producers\WebSocketProducerConfiguration.java | 1 |
请完成以下Java代码 | public int getC_DocTypeInvoice_FinalSettlement_ID()
{
if (_invoiceDocTypeFinalSettlementId == null)
{
final String docSubType = IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_FinalSettlement;
_invoiceDocTypeFinalSettlementId = loadDocType(DocSubType.ofCode(docSubType));
}
return _invoiceDocTypeFinalSettlementId.getRepoId();
}
/**
* Returns true if the scrap percentage treshold is less than 100.
*/
@Override
public boolean isFeeForScrap()
{
return getScrapPercentageTreshold().compareTo(new BigDecimal("100")) < 0;
}
private DocTypeId loadDocType(final DocSubType docSubType)
{ | final IContextAware context = getContext();
final Properties ctx = context.getCtx();
final int adClientId = Env.getAD_Client_ID(ctx);
final int adOrgId = Env.getAD_Org_ID(ctx); // FIXME: not sure if it's ok
return Services.get(IDocTypeDAO.class).getDocTypeId(
DocTypeQuery.builder()
.docBaseType(X_C_DocType.DOCBASETYPE_APInvoice)
.docSubType(docSubType)
.adClientId(adClientId)
.adOrgId(adOrgId)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\AbstractQualityBasedConfig.java | 1 |
请完成以下Java代码 | 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 Other SQL Clause.
@param OtherClause
Other SQL Clause
*/
public void setOtherClause (String OtherClause)
{
set_Value (COLUMNNAME_OtherClause, OtherClause);
}
/** Get Other SQL Clause.
@return Other SQL Clause
*/
public String getOtherClause ()
{
return (String)get_Value(COLUMNNAME_OtherClause);
}
/** Set Post Processing.
@param PostProcessing
Process SQL after executing the query
*/
public void setPostProcessing (String PostProcessing)
{
set_Value (COLUMNNAME_PostProcessing, PostProcessing);
}
/** Get Post Processing.
@return Process SQL after executing the query
*/
public String getPostProcessing ()
{
return (String)get_Value(COLUMNNAME_PostProcessing);
}
/** Set Pre Processing.
@param PreProcessing
Process SQL before executing the query
*/
public void setPreProcessing (String PreProcessing)
{
set_Value (COLUMNNAME_PreProcessing, PreProcessing);
}
/** Get Pre Processing.
@return Process SQL before executing the query | */
public String getPreProcessing ()
{
return (String)get_Value(COLUMNNAME_PreProcessing);
}
/** 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);
}
/** 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_AD_AlertRule.java | 1 |
请完成以下Java代码 | public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getSourceExpression() {
return sourceExpression;
}
public void setSourceExpression(String sourceExpression) {
this.sourceExpression = sourceExpression;
} | public String getTargetExpression() {
return targetExpression;
}
public void setTargetExpression(String targetExpression) {
this.targetExpression = targetExpression;
}
public IOParameter clone() {
IOParameter clone = new IOParameter();
clone.setValues(this);
return clone;
}
public void setValues(IOParameter otherElement) {
super.setValues(otherElement);
setSource(otherElement.getSource());
setSourceExpression(otherElement.getSourceExpression());
setTarget(otherElement.getTarget());
setTargetExpression(otherElement.getTargetExpression());
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\IOParameter.java | 1 |
请完成以下Java代码 | public void setIsComplete (final boolean IsComplete)
{
set_Value (COLUMNNAME_IsComplete, IsComplete);
}
@Override
public boolean isComplete()
{
return get_ValueAsBoolean(COLUMNNAME_IsComplete);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPlannedAmt (final BigDecimal PlannedAmt)
{
set_Value (COLUMNNAME_PlannedAmt, PlannedAmt);
}
@Override
public BigDecimal getPlannedAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceActual (final @Nullable BigDecimal PriceActual)
{
set_Value (COLUMNNAME_PriceActual, PriceActual);
}
@Override
public BigDecimal getPriceActual()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceActual);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* ProjInvoiceRule AD_Reference_ID=383
* Reference name: C_Project InvoiceRule
*/
public static final int PROJINVOICERULE_AD_Reference_ID=383;
/** None = - */
public static final String PROJINVOICERULE_None = "-";
/** Committed Amount = C */
public static final String PROJINVOICERULE_CommittedAmount = "C";
/** Time&Material max Comitted = c */
public static final String PROJINVOICERULE_TimeMaterialMaxComitted = "c";
/** Time&Material = T */
public static final String PROJINVOICERULE_TimeMaterial = "T";
/** Product Quantity = P */
public static final String PROJINVOICERULE_ProductQuantity = "P";
@Override
public void setProjInvoiceRule (final java.lang.String ProjInvoiceRule)
{
set_Value (COLUMNNAME_ProjInvoiceRule, ProjInvoiceRule);
} | @Override
public java.lang.String getProjInvoiceRule()
{
return get_ValueAsString(COLUMNNAME_ProjInvoiceRule);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setStartDate (final @Nullable java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
@Override
public java.sql.Timestamp getStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectPhase.java | 1 |
请完成以下Java代码 | public void setAssignedQuantity (java.math.BigDecimal AssignedQuantity)
{
set_ValueNoCheck (COLUMNNAME_AssignedQuantity, AssignedQuantity);
}
/** Get Zugeordnete Menge.
@return Zugeordneter Menge in der Maßeinheit des jeweiligen Produktes
*/
@Override
public java.math.BigDecimal getAssignedQuantity ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssignedQuantity);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
@Override
public de.metas.contracts.model.I_C_Flatrate_RefundConfig getC_Flatrate_RefundConfig() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class);
}
@Override
public void setC_Flatrate_RefundConfig(de.metas.contracts.model.I_C_Flatrate_RefundConfig C_Flatrate_RefundConfig)
{
set_ValueFromPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class, C_Flatrate_RefundConfig);
}
/** Set C_Flatrate_RefundConfig.
@param C_Flatrate_RefundConfig_ID C_Flatrate_RefundConfig */
@Override
public void setC_Flatrate_RefundConfig_ID (int C_Flatrate_RefundConfig_ID)
{
if (C_Flatrate_RefundConfig_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, Integer.valueOf(C_Flatrate_RefundConfig_ID));
} | /** Get C_Flatrate_RefundConfig.
@return C_Flatrate_RefundConfig */
@Override
public int getC_Flatrate_RefundConfig_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_RefundConfig_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Vertrag-Rechnungskandidat.
@param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */
@Override
public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID)
{
if (C_Invoice_Candidate_Term_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID));
}
/** Get Vertrag-Rechnungskandidat.
@return Vertrag-Rechnungskandidat */
@Override
public int getC_Invoice_Candidate_Term_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment_Aggregate_V.java | 1 |
请在Spring Boot框架中完成以下Java代码 | default @Nullable String getSecurityProtocol() {
return null;
}
/**
* Returns the consumer configuration.
* @return the consumer configuration
*/
default Configuration getConsumer() {
return Configuration.of(getBootstrapServers(), getSslBundle(), getSecurityProtocol());
}
/**
* Returns the producer configuration.
* @return the producer configuration
*/
default Configuration getProducer() {
return Configuration.of(getBootstrapServers(), getSslBundle(), getSecurityProtocol());
}
/**
* Returns the admin configuration.
* @return the admin configuration
*/
default Configuration getAdmin() {
return Configuration.of(getBootstrapServers(), getSslBundle(), getSecurityProtocol());
}
/**
* Returns the Kafka Streams configuration.
* @return the Kafka Streams configuration
*/
default Configuration getStreams() {
return Configuration.of(getBootstrapServers(), getSslBundle(), getSecurityProtocol());
}
/**
* Kafka connection details configuration.
*/
interface Configuration {
/**
* Creates a new configuration with the given bootstrap servers.
* @param bootstrapServers the bootstrap servers
* @return the configuration
*/
static Configuration of(List<String> bootstrapServers) {
return Configuration.of(bootstrapServers, null, null);
}
/**
* Creates a new configuration with the given bootstrap servers and SSL bundle.
* @param bootstrapServers the bootstrap servers
* @param sslBundle the SSL bundle
* @return the configuration
*/
static Configuration of(List<String> bootstrapServers, SslBundle sslBundle) {
return Configuration.of(bootstrapServers, sslBundle, null);
}
/**
* Creates a new configuration with the given bootstrap servers, SSL bundle and
* security protocol.
* @param bootstrapServers the bootstrap servers
* @param sslBundle the SSL bundle
* @param securityProtocol the security protocol
* @return the configuration
*/
static Configuration of(List<String> bootstrapServers, @Nullable SslBundle sslBundle,
@Nullable String securityProtocol) {
return new Configuration() {
@Override
public List<String> getBootstrapServers() {
return bootstrapServers;
} | @Override
public @Nullable SslBundle getSslBundle() {
return sslBundle;
}
@Override
public @Nullable String getSecurityProtocol() {
return securityProtocol;
}
};
}
/**
* Returns the list of bootstrap servers.
* @return the list of bootstrap servers
*/
List<String> getBootstrapServers();
/**
* Returns the SSL bundle.
* @return the SSL bundle
*/
default @Nullable SslBundle getSslBundle() {
return null;
}
/**
* Returns the security protocol.
* @return the security protocol
*/
default @Nullable String getSecurityProtocol() {
return null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\KafkaConnectionDetails.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static void addGenericsForClass(Set<Class<?>> genericsToAdd, ResolvableType resolvableType) {
if (resolvableType.getSuperType().hasGenerics()) {
genericsToAdd.addAll(Arrays.stream(resolvableType.getSuperType().getGenerics())
.map(ResolvableType::toClass)
.collect(Collectors.toSet()));
}
}
private static void addSuperTypesForClass(ResolvableType resolvableType, Set<Class<?>> supertypesToAdd,
Set<Class<?>> genericsToAdd) {
ResolvableType superType = resolvableType.getSuperType();
if (!ResolvableType.NONE.equals(superType)) {
addGenericsForClass(genericsToAdd, superType);
supertypesToAdd.add(superType.toClass());
addSuperTypesForClass(superType, supertypesToAdd, genericsToAdd);
}
}
@SuppressWarnings({ "rawtypes" })
private static Set<Class<?>> getClassesToAdd() {
Set<Class<?>> classesToAdd = new HashSet<>();
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(Configurable.class));
Set<BeanDefinition> components = provider.findCandidateComponents(ROOT_GATEWAY_PACKAGE_NAME);
for (BeanDefinition component : components) {
Class clazz;
try { | clazz = Class.forName(component.getBeanClassName());
if (shouldRegisterClass(clazz)) {
classesToAdd.add(clazz);
}
}
catch (NoClassDefFoundError | ClassNotFoundException exception) {
if (LOG.isDebugEnabled()) {
LOG.debug(exception);
}
}
}
return classesToAdd;
}
private static boolean shouldRegisterClass(Class<?> clazz) {
Set<String> conditionClasses = beansConditionalOnClasses.getOrDefault(clazz, Collections.emptySet());
for (String conditionClass : conditionClasses) {
try {
ConfigurableHintsRegistrationProcessor.class.getClassLoader().loadClass(conditionClass);
}
catch (ClassNotFoundException e) {
return false;
}
}
return true;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\ConfigurableHintsRegistrationProcessor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void getImageAsByteArray(HttpServletResponse response) throws IOException {
final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
IOUtils.copy(in, response.getOutputStream());
}
@RequestMapping(value = "/image-byte-array", method = RequestMethod.GET)
@ResponseBody
public byte[] getImageAsByteArray() throws IOException {
final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
return IOUtils.toByteArray(in);
}
@RequestMapping(value = "/image-response-entity", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImageAsResponseEntity() throws IOException {
ResponseEntity<byte[]> responseEntity;
final HttpHeaders headers = new HttpHeaders(); | final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
byte[] media = IOUtils.toByteArray(in);
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
responseEntity = new ResponseEntity<>(media, headers, HttpStatus.OK);
return responseEntity;
}
@RequestMapping(value = "/image-resource", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Resource> getImageAsResource() {
final HttpHeaders headers = new HttpHeaders();
Resource resource = new ServletContextResource(servletContext, "/WEB-INF/images/image-example.jpg");
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-xml-2\src\main\java\com\baeldung\spring\controller\ImageController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static ClientId ofRepoId(final int repoId)
{
final ClientId clientId = ofRepoIdOrNull(repoId);
if (clientId == null)
{
throw new AdempiereException("Invalid AD_Client_ID: " + repoId);
}
return clientId;
}
public static ClientId ofRepoIdOrSystem(final int repoId)
{
final ClientId clientId = ofRepoIdOrNull(repoId);
return clientId != null ? clientId : SYSTEM;
}
public static Optional<ClientId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
@Nullable
public static ClientId ofRepoIdOrNull(final int repoId)
{
if (repoId == SYSTEM.repoId)
{
return SYSTEM;
}
else if (repoId == TRASH.repoId)
{
return TRASH;
}
else if (repoId == METASFRESH.repoId)
{
return METASFRESH;
}
else if (repoId <= 0)
{
return null;
}
else
{
return new ClientId(repoId);
}
}
public static final ClientId SYSTEM = new ClientId(0);
@VisibleForTesting
static final ClientId TRASH = new ClientId(99); | public static final ClientId METASFRESH = new ClientId(1000000);
int repoId;
private ClientId(final int repoId)
{
// NOTE: validation happens in ofRepoIdOrNull method
this.repoId = repoId;
}
public boolean isSystem()
{
return repoId == SYSTEM.repoId;
}
public boolean isTrash()
{
return repoId == TRASH.repoId;
}
public boolean isRegular()
{
return !isSystem() && !isTrash();
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final ClientId clientId)
{
return clientId != null ? clientId.getRepoId() : -1;
}
public static boolean equals(@Nullable final ClientId id1, @Nullable final ClientId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\ClientId.java | 2 |
请完成以下Java代码 | public org.compiere.model.I_M_Allergen_Trace getM_Allergen_Trace()
{
return get_ValueAsPO(COLUMNNAME_M_Allergen_Trace_ID, org.compiere.model.I_M_Allergen_Trace.class);
}
@Override
public void setM_Allergen_Trace(final org.compiere.model.I_M_Allergen_Trace M_Allergen_Trace)
{
set_ValueFromPO(COLUMNNAME_M_Allergen_Trace_ID, org.compiere.model.I_M_Allergen_Trace.class, M_Allergen_Trace);
}
@Override
public void setM_Allergen_Trace_ID (final int M_Allergen_Trace_ID)
{
if (M_Allergen_Trace_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Allergen_Trace_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Allergen_Trace_ID, M_Allergen_Trace_ID);
}
@Override
public int getM_Allergen_Trace_ID()
{ | return get_ValueAsInt(COLUMNNAME_M_Allergen_Trace_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Allergen_Trace_Trl.java | 1 |
请完成以下Java代码 | public void createMembership(String userId) {
ensureNotReadOnly();
userId = PathUtil.decodePathParam(userId);
identityService.createTenantUserMembership(resourceId, userId);
}
public void deleteMembership(String userId) {
ensureNotReadOnly();
userId = PathUtil.decodePathParam(userId);
identityService.deleteTenantUserMembership(resourceId, userId);
}
public ResourceOptionsDto availableOperations(UriInfo context) {
ResourceOptionsDto dto = new ResourceOptionsDto();
URI uri = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(TenantRestService.PATH) | .path(resourceId)
.path(TenantUserMembersResource.PATH)
.build();
if (!identityService.isReadOnly() && isAuthorized(DELETE)) {
dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete");
}
if (!identityService.isReadOnly() && isAuthorized(CREATE)) {
dto.addReflexiveLink(uri, HttpMethod.PUT, "create");
}
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\identity\impl\TenantUserMembersResourceImpl.java | 1 |
请完成以下Java代码 | public void setM_MovementLine_ID (int M_MovementLine_ID)
{
if (M_MovementLine_ID < 1)
set_Value (COLUMNNAME_M_MovementLine_ID, null);
else
set_Value (COLUMNNAME_M_MovementLine_ID, Integer.valueOf(M_MovementLine_ID));
}
/** Get Move Line.
@return Inventory Move document Line
*/
public int getM_MovementLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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 Scrapped Quantity.
@param ScrappedQty
The Quantity scrapped due to QA issues
*/
public void setScrappedQty (BigDecimal ScrappedQty)
{
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Scrapped Quantity. | @return The Quantity scrapped due to QA issues
*/
public BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Target Quantity.
@param TargetQty
Target Movement Quantity
*/
public void setTargetQty (BigDecimal TargetQty)
{
set_Value (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Target Quantity.
@return Target Movement Quantity
*/
public BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementLineConfirm.java | 1 |
请完成以下Java代码 | public Set<CtxName> getParameters()
{
if (_parameters == null)
{
if (isConstant())
{
_parameters = ImmutableSet.of();
}
else
{
final Set<CtxName> result = new LinkedHashSet<>(left.getParameters());
result.addAll(right.getParameters());
_parameters = ImmutableSet.copyOf(result);
}
}
return _parameters;
}
/**
* @return left expression; never null
*/
public ILogicExpression getLeft()
{
return left;
}
/**
* @return right expression; never null
*/
public ILogicExpression getRight()
{
return right;
}
/**
* @return logic operator; never null
*/
public String getOperator()
{
return operator;
}
@Override
public String toString()
{ | return getExpressionString();
}
@Override
public ILogicExpression evaluatePartial(final Evaluatee ctx)
{
if (isConstant())
{
return this;
}
final ILogicExpression leftExpression = getLeft();
final ILogicExpression newLeftExpression = leftExpression.evaluatePartial(ctx);
final ILogicExpression rightExpression = getRight();
final ILogicExpression newRightExpression = rightExpression.evaluatePartial(ctx);
final String logicOperator = getOperator();
if (newLeftExpression.isConstant() && newRightExpression.isConstant())
{
final BooleanEvaluator logicExprEvaluator = LogicExpressionEvaluator.getBooleanEvaluatorByOperator(logicOperator);
final boolean result = logicExprEvaluator.evaluateOrNull(newLeftExpression::constantValue, newRightExpression::constantValue);
return ConstantLogicExpression.of(result);
}
else if (Objects.equals(leftExpression, newLeftExpression)
&& Objects.equals(rightExpression, newRightExpression))
{
return this;
}
else
{
return LogicExpression.of(newLeftExpression, logicOperator, newRightExpression);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicExpression.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Long getId() {
return id;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final User user = (User) o;
if (!Objects.equals(id, user.id)) {
return false;
}
if (!Objects.equals(firstName, user.firstName)) {
return false;
} | return Objects.equals(secondName, user.secondName);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (secondName != null ? secondName.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", secondName='" + secondName + '\'' +
'}';
}
} | repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\xml\controller\User.java | 2 |
请完成以下Java代码 | private static List<ToolCall> sanitizeToolCalls(List<ToolCall> toolCalls) {
List<ToolCall> sanitized = new ArrayList<>(toolCalls.size());
int counter = 0;
for (ToolCall toolCall : toolCalls) {
counter++;
String id = toolCall.getId();
if (id == null || id.isBlank()) {
id = toolCall.getFunction().getName() + "-" + counter;
}
sanitized.add(new ToolCall(
toolCall.getIndex(),
id,
toolCall.getType(),
toolCall.getFunction()
));
} | return sanitized;
}
private static String toJson(Object value) {
try {
return MAPPER.writeValueAsString(value);
} catch (Exception ex) {
Client.LOGGER.log(Level.INFO,
"Falling back to toString() for tool output: {0}",
ex.getMessage()
);
return String.valueOf(value);
}
}
} | repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\simpleopenai\HandlingToolCallsInTheChatLoop.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void updateSubCnt(Long deptId){
if(deptId != null){
int count = deptRepository.countByPid(deptId);
deptRepository.updateSubCntById(count, deptId);
}
}
private List<DeptDto> deduplication(List<DeptDto> list) {
List<DeptDto> deptDtos = new ArrayList<>();
for (DeptDto deptDto : list) {
boolean flag = true;
for (DeptDto dto : list) {
if (dto.getId().equals(deptDto.getPid())) {
flag = false;
break;
}
}
if (flag){ | deptDtos.add(deptDto);
}
}
return deptDtos;
}
/**
* 清理缓存
* @param id /
*/
public void delCaches(Long id){
List<User> users = userRepository.findByRoleDeptId(id);
// 删除数据权限
redisUtils.delByKeys(CacheKey.DATA_USER, users.stream().map(User::getId).collect(Collectors.toSet()));
redisUtils.del(CacheKey.DEPT_ID + id);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DeptServiceImpl.java | 2 |
请完成以下Java代码 | protected void updateEntity(DbEntityOperation operation) {
final DbEntity dbEntity = operation.getEntity();
String updateStatement = dbSqlSessionFactory.getUpdateStatement(dbEntity);
ensureNotNull("no update statement for " + dbEntity.getClass() + " in the ibatis mapping files", "updateStatement", updateStatement);
LOG.executeDatabaseOperation("UPDATE", dbEntity);
try {
int rowsAffected = executeUpdate(updateStatement, dbEntity);
entityUpdatePerformed(operation, rowsAffected, null);
} catch (PersistenceException e) {
entityUpdatePerformed(operation, 0, e);
}
} | @Override
protected void updateBulk(DbBulkOperation operation) {
String statement = operation.getStatement();
Object parameter = operation.getParameter();
LOG.executeDatabaseBulkOperation("UPDATE", statement, parameter);
try {
int rowsAffected = executeUpdate(statement, parameter);
bulkUpdatePerformed(operation, rowsAffected, null);
} catch (PersistenceException e) {
bulkUpdatePerformed(operation, 0, e);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\SimpleDbSqlSession.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<OpenApiPermission> findByAuthId(String authId) {
return baseMapper.selectList(Wrappers.lambdaQuery(OpenApiPermission.class).eq(OpenApiPermission::getApiAuthId, authId));
}
@Override
public Result<?> getOpenApi(String apiAuthId) {
List<OpenApi> openApis = openApiService.list();
if (CollectionUtil.isEmpty(openApis)) {
return Result.error("接口不存在");
}
List<OpenApiPermission> openApiPermissions = baseMapper.selectList(Wrappers.<OpenApiPermission>lambdaQuery().eq(OpenApiPermission::getApiAuthId, apiAuthId));
if (CollectionUtil.isNotEmpty(openApiPermissions)) {
Map<String, OpenApi> openApiMap = openApis.stream().collect(Collectors.toMap(OpenApi::getId, o -> o));
for (OpenApiPermission openApiPermission : openApiPermissions) {
OpenApi openApi = openApiMap.get(openApiPermission.getApiId());
if (openApi!=null) {
openApi.setIfCheckBox("1");
}
}
}
return Result.ok(openApis);
} | @Override
public void add(OpenApiPermission openApiPermission) {
this.remove(Wrappers.<OpenApiPermission>lambdaQuery().eq(OpenApiPermission::getApiAuthId, openApiPermission.getApiAuthId()));
List<String> list = Arrays.asList(openApiPermission.getApiId().split(","));
if (CollectionUtil.isNotEmpty(list)) {
list.forEach(l->{
if (StrUtil.isNotEmpty(l)){
OpenApiPermission saveApiPermission = new OpenApiPermission();
saveApiPermission.setApiId(l);
saveApiPermission.setApiAuthId(openApiPermission.getApiAuthId());
this.save(saveApiPermission);
}
});
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\service\impl\OpenApiPermissionServiceImpl.java | 2 |
请完成以下Java代码 | public class Personne2 {
private String nom;
private String surnom;
private int age;
public Personne2() {
}
public Personne2(String nom, String surnom, int age) {
super();
this.nom = nom;
this.surnom = surnom;
this.age = age;
}
@Mapping("name")
public String getNom() {
return nom;
}
@Mapping("nickname")
public String getSurnom() { | return surnom;
}
public void setNom(String nom) {
this.nom = nom;
}
public void setSurnom(String surnom) {
this.surnom = surnom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
} | repos\tutorials-master\libraries-data\src\main\java\com\baeldung\dozer\Personne2.java | 1 |
请完成以下Java代码 | public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
/**
* Attribute AD_Reference_ID=541332
* Reference name: AD_User_Attribute
*/
public static final int ATTRIBUTE_AD_Reference_ID=541332;
/** Delegate = D */
public static final String ATTRIBUTE_Delegate = "D";
/** Politician = P */
public static final String ATTRIBUTE_Politician = "P";
/** Rechtsberater = R */
public static final String ATTRIBUTE_Rechtsberater = "R"; | /** Schätzer = S */
public static final String ATTRIBUTE_Schaetzer = "S";
/** Vorstand = V */
public static final String ATTRIBUTE_Vorstand = "V";
@Override
public void setAttribute (final java.lang.String Attribute)
{
set_Value (COLUMNNAME_Attribute, Attribute);
}
@Override
public java.lang.String getAttribute()
{
return get_ValueAsString(COLUMNNAME_Attribute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Attribute.java | 1 |
请完成以下Java代码 | private LicenseParam initLicenseParam() {
Preferences preferences = Preferences.userNodeForPackage(LicenseCreator.class);
//设置对证书内容加密的秘钥
CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
KeyStoreParam privateStoreParam = new CustomKeyStoreParam(LicenseCreator.class
, param.getPrivateKeysStorePath()
, param.getPrivateAlias()
, param.getStorePass()
, param.getKeyPass());
return new DefaultLicenseParam(param.getSubject()
, preferences
, privateStoreParam
, cipherParam);
}
/**
* <p>项目名称: true-license-demo </p>
* <p>文件名称: LicenseCreator.java </p>
* <p>方法描述: 设置证书生成正文信息 </p>
* <p>创建时间: 2020/10/10 13:34 </p>
*
* @return de.schlichtherle.license.LicenseContent
* @author 方瑞冬
* @version 1.0
*/
private LicenseContent initLicenseContent() {
LicenseContent licenseContent = new LicenseContent(); | licenseContent.setHolder(DEFAULT_HOLDER_AND_ISSUER);
licenseContent.setIssuer(DEFAULT_HOLDER_AND_ISSUER);
licenseContent.setSubject(param.getSubject());
licenseContent.setIssued(param.getIssuedTime());
licenseContent.setNotBefore(param.getIssuedTime());
licenseContent.setNotAfter(param.getExpiryTime());
licenseContent.setConsumerType(param.getConsumerType());
licenseContent.setConsumerAmount(param.getConsumerAmount());
licenseContent.setInfo(param.getDescription());
//扩展校验服务器硬件信息
licenseContent.setExtra(param.getLicenseCheckModel());
return licenseContent;
}
} | repos\springboot-demo-master\SoftwareLicense\src\main\java\com\et\license\license\LicenseCreator.java | 1 |
请完成以下Java代码 | public boolean hasVariable(String variableName) {
return variables.containsKey(variableName);
}
@Override
public Object getVariable(String variableName) {
return variables.get(variableName);
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public Map<String, Object> getPlanItemInstanceLocalVariables() { | return localVariables;
}
@Override
public PlanItem getPlanItem() {
return planItem;
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("planItemDefinitionId='" + planItemDefinitionId + "'")
.add("elementId='" + elementId + "'")
.add("caseInstanceId='" + caseInstanceId + "'")
.add("caseDefinitionId='" + caseDefinitionId + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\ReadOnlyDelegatePlanItemInstanceImpl.java | 1 |
请完成以下Java代码 | public UserQuery orderByUserFirstName() {
return orderBy(UserQueryProperty.FIRST_NAME);
}
@Override
public UserQuery orderByUserLastName() {
return orderBy(UserQueryProperty.LAST_NAME);
}
// results //////////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getUserEntityManager(commandContext).findUserCountByQueryCriteria(this);
}
@Override
public List<User> executeList(CommandContext commandContext) {
return CommandContextUtil.getUserEntityManager(commandContext).findUserByQueryCriteria(this);
}
// getters //////////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
public List<String> getIds() {
return ids;
}
public String getIdIgnoreCase() {
return idIgnoreCase;
}
public String getFirstName() {
return firstName;
}
public String getFirstNameLike() {
return firstNameLike;
}
public String getFirstNameLikeIgnoreCase() {
return firstNameLikeIgnoreCase;
}
public String getLastName() {
return lastName;
}
public String getLastNameLike() {
return lastNameLike;
}
public String getLastNameLikeIgnoreCase() { | return lastNameLikeIgnoreCase;
}
public String getEmail() {
return email;
}
public String getEmailLike() {
return emailLike;
}
public String getGroupId() {
return groupId;
}
public List<String> getGroupIds() {
return groupIds;
}
public String getFullNameLike() {
return fullNameLike;
}
public String getFullNameLikeIgnoreCase() {
return fullNameLikeIgnoreCase;
}
public String getDisplayName() {
return displayName;
}
public String getDisplayNameLike() {
return displayNameLike;
}
public String getDisplayNameLikeIgnoreCase() {
return displayNameLikeIgnoreCase;
}
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\UserQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InvoiceAndLineId implements RepoIdAware
{
int repoId;
@NonNull
InvoiceId invoiceId;
@Nullable
public static InvoiceAndLineId cast(@Nullable final RepoIdAware repoIdAware)
{
return (InvoiceAndLineId)repoIdAware;
}
public static InvoiceAndLineId ofRepoId(@NonNull final InvoiceId invoiceId, final int invoiceLineId)
{
return new InvoiceAndLineId(invoiceId, invoiceLineId);
}
public static InvoiceAndLineId ofRepoId(final int invoiceId, final int invoiceLineId)
{
return new InvoiceAndLineId(InvoiceId.ofRepoId(invoiceId), invoiceLineId);
}
@Nullable
public static InvoiceAndLineId ofRepoIdOrNull(
@Nullable final Integer invoiceId,
@Nullable final Integer invoiceLineId)
{
return invoiceId != null && invoiceId > 0 && invoiceLineId != null && invoiceLineId > 0
? ofRepoId(invoiceId, invoiceLineId)
: null;
}
@Nullable
public static InvoiceAndLineId ofRepoIdOrNull(
@Nullable final InvoiceId bpartnerId,
final int bpartnerLocationId)
{ | return bpartnerId != null && bpartnerLocationId > 0 ? ofRepoId(bpartnerId, bpartnerLocationId) : null;
}
private InvoiceAndLineId(@NonNull final InvoiceId invoiceId, final int invoiceLineId)
{
this.repoId = Check.assumeGreaterThanZero(invoiceLineId, "invoiceLineId");
this.invoiceId = invoiceId;
}
public static int toRepoId(@Nullable final InvoiceAndLineId invoiceAndLineId)
{
return toRepoIdOr(invoiceAndLineId, -1);
}
public static int toRepoIdOr(@Nullable final InvoiceAndLineId invoiceAndLineId, final int defaultValue)
{
return invoiceAndLineId != null ? invoiceAndLineId.getRepoId() : defaultValue;
}
public static boolean equals(final InvoiceAndLineId id1, final InvoiceAndLineId id2)
{
return Objects.equals(id1, id2);
}
public void assertInvoiceId(@NonNull final InvoiceId expectedInvoiceId)
{
if (!InvoiceId.equals(this.invoiceId, expectedInvoiceId))
{
throw new AdempiereException("InvoiceId does not match for " + this + ". Expected invoiceId was " + expectedInvoiceId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\invoice\InvoiceAndLineId.java | 2 |
请完成以下Java代码 | public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId,
Authentication principal, HttpServletRequest request) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.notNull(request, "request cannot be null");
return (T) this.getAuthorizedClients(request).get(clientRegistrationId);
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(request, "request cannot be null");
Assert.notNull(response, "response cannot be null");
Map<String, OAuth2AuthorizedClient> authorizedClients = this.getAuthorizedClients(request);
authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient);
request.getSession().setAttribute(this.sessionAttributeName, authorizedClients);
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.notNull(request, "request cannot be null");
Map<String, OAuth2AuthorizedClient> authorizedClients = this.getAuthorizedClients(request);
if (!authorizedClients.isEmpty()) {
if (authorizedClients.remove(clientRegistrationId) != null) {
if (!authorizedClients.isEmpty()) {
request.getSession().setAttribute(this.sessionAttributeName, authorizedClients);
}
else {
request.getSession().removeAttribute(this.sessionAttributeName);
} | }
}
}
@SuppressWarnings("unchecked")
private Map<String, OAuth2AuthorizedClient> getAuthorizedClients(HttpServletRequest request) {
HttpSession session = request.getSession(false);
Map<String, OAuth2AuthorizedClient> authorizedClients = (session != null)
? (Map<String, OAuth2AuthorizedClient>) session.getAttribute(this.sessionAttributeName) : null;
if (authorizedClients == null) {
authorizedClients = new HashMap<>();
}
return authorizedClients;
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\HttpSessionOAuth2AuthorizedClientRepository.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Desktop[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set System Color.
@param AD_Color_ID
Color for backgrounds or indicators
*/
public void setAD_Color_ID (int AD_Color_ID)
{
if (AD_Color_ID < 1)
set_Value (COLUMNNAME_AD_Color_ID, null);
else
set_Value (COLUMNNAME_AD_Color_ID, Integer.valueOf(AD_Color_ID));
}
/** Get System Color.
@return Color for backgrounds or indicators
*/
public int getAD_Color_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Color_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Desktop.
@param AD_Desktop_ID
Collection of Workbenches
*/
public void setAD_Desktop_ID (int AD_Desktop_ID)
{
if (AD_Desktop_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Desktop_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Desktop_ID, Integer.valueOf(AD_Desktop_ID));
}
/** Get Desktop.
@return Collection of Workbenches
*/
public int getAD_Desktop_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Desktop_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Image.
@param AD_Image_ID
Image or Icon
*/
public void setAD_Image_ID (int AD_Image_ID)
{
if (AD_Image_ID < 1)
set_Value (COLUMNNAME_AD_Image_ID, null);
else
set_Value (COLUMNNAME_AD_Image_ID, Integer.valueOf(AD_Image_ID));
}
/** Get Image. | @return Image or Icon
*/
public int getAD_Image_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Desktop.java | 1 |
请完成以下Java代码 | public void setPriority(int priority) {
activiti5Task.setPriority(priority);
}
@Override
public void setOwner(String owner) {
activiti5Task.setOwner(owner);
}
@Override
public void setAssignee(String assignee) {
activiti5Task.setAssignee(assignee);
}
@Override
public DelegationState getDelegationState() {
return activiti5Task.getDelegationState();
}
@Override
public void setDelegationState(DelegationState delegationState) {
activiti5Task.setDelegationState(delegationState);
}
@Override
public void setDueDate(Date dueDate) {
activiti5Task.setDueDate(dueDate);
}
@Override
public void setCategory(String category) {
activiti5Task.setCategory(category);
}
@Override | public void setParentTaskId(String parentTaskId) {
activiti5Task.setParentTaskId(parentTaskId);
}
@Override
public void setTenantId(String tenantId) {
activiti5Task.setTenantId(tenantId);
}
@Override
public void setFormKey(String formKey) {
activiti5Task.setFormKey(formKey);
}
@Override
public boolean isSuspended() {
return activiti5Task.isSuspended();
}
} | repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema productsSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName(webservicePortTypeName);
wsdl11Definition.setTargetNamespace(webserviceTargetNamespace);
wsdl11Definition.setLocationUri(locationUri);
wsdl11Definition.setSchema(productsSchema);
return wsdl11Definition;
}
@Bean
public XsdSchema productsSchema() {
return new SimpleXsdSchema(new ClassPathResource("products.xsd"));
}
@Bean
public Map<String, Product> getProducts()
{
Map<String, Product> map = new HashMap<>();
Product foldsack= new Product(); | foldsack.setId("1");
foldsack.setName("Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops");
foldsack.setDescription("Your perfect pack for everyday use and walks in the forest. ");
Product shirt= new Product();
shirt.setId("2");
shirt.setName("Mens Casual Premium Slim Fit T-Shirts");
shirt.setDescription("Slim-fitting style, contrast raglan long sleeve, three-button henley placket.");
map.put("1", foldsack);
map.put("2", shirt);
return map;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-2\src\main\java\com\baeldung\keycloak\keycloaksoap\WebServiceConfig.java | 2 |
请完成以下Java代码 | public List<String> shortcutFieldOrder() {
return Arrays.asList(GatewayFilter.NAME_KEY, GatewayFilter.VALUE_KEY, OVERRIDE_KEY);
}
@Override
public GatewayFilter apply(NameValueConfig config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange).then(Mono.fromRunnable(() -> addHeader(exchange, config)));
}
@Override
public String toString() {
String name = config.getName();
String value = config.getValue();
if (config instanceof Config) {
return filterToStringCreator(AddResponseHeaderGatewayFilterFactory.this)
.append(GatewayFilter.NAME_KEY, name != null ? name : "")
.append(GatewayFilter.VALUE_KEY, value != null ? value : "")
.append(OVERRIDE_KEY, ((Config) config).isOverride())
.toString();
}
return filterToStringCreator(AddResponseHeaderGatewayFilterFactory.this)
.append(name != null ? name : "", value != null ? value : "")
.toString();
}
};
}
void addHeader(ServerWebExchange exchange, NameValueConfig config) {
// if response has been commited, no more response headers will bee added.
if (!exchange.getResponse().isCommitted()) {
String name = Objects.requireNonNull(config.getName(), "name must not be null");
String rawValue = Objects.requireNonNull(config.getValue(), "value must not be null");
final String value = ServerWebExchangeUtils.expand(exchange, rawValue);
HttpHeaders headers = exchange.getResponse().getHeaders();
boolean override = true; // default is true
if (config instanceof Config) {
override = ((Config) config).isOverride();
}
if (override) {
headers.add(name, value);
}
else { | boolean headerIsMissingOrBlank = headers.getOrEmpty(name)
.stream()
.allMatch(h -> !StringUtils.hasText(h));
if (headerIsMissingOrBlank) {
headers.add(name, value);
}
}
}
}
public static class Config extends AbstractNameValueGatewayFilterFactory.NameValueConfig {
private boolean override = true;
public boolean isOverride() {
return override;
}
public Config setOverride(boolean override) {
this.override = override;
return this;
}
@Override
public String toString() {
return new ToStringCreator(this).append(NAME_KEY, name)
.append(VALUE_KEY, value)
.append(OVERRIDE_KEY, override)
.toString();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\AddResponseHeaderGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public BulkUpdateByQueryResult bulkUpdatePendingTransactions(boolean isForceSendingChangeEvents)
{
return bulkUpdateTransactions(SumUpTransactionQuery.ofStatus(SumUpTransactionStatus.PENDING), isForceSendingChangeEvents);
}
public BulkUpdateByQueryResult bulkUpdateTransactions(@NonNull SumUpTransactionQuery query, boolean isForceSendingChangeEvents)
{
return trxRepository.bulkUpdateByQuery(query, isForceSendingChangeEvents, this::updateTransactionFromRemote);
}
public SumUpTransaction refundTransaction(@NonNull final SumUpPOSRef posRef)
{
final SumUpTransactionExternalId id = findTransactionToRefundByPOSRef(posRef);
return refundTransaction(id);
}
private @NonNull SumUpTransactionExternalId findTransactionToRefundByPOSRef(final @NonNull SumUpPOSRef posRef)
{
if (posRef.getPosPaymentId() <= 0)
{
throw new AdempiereException("posPaymentId not provided");
}
final List<SumUpTransaction> trxs = trxRepository.stream(SumUpTransactionQuery.builder()
.status(SumUpTransactionStatus.SUCCESSFUL)
.posRef(posRef)
.build())
.filter(trx -> !trx.isRefunded())
.collect(Collectors.toList());
if (trxs.isEmpty())
{
throw new AdempiereException("No successful transactions found");
}
else if (trxs.size() != 1)
{ | throw new AdempiereException("More than successful transaction found");
}
else
{
return trxs.get(0).getExternalId();
}
}
public SumUpTransaction refundTransaction(@NonNull final SumUpTransactionExternalId id)
{
return trxRepository.updateById(id, trx -> {
final SumUpConfig config = configRepository.getById(trx.getConfigId());
final SumUpClient client = clientFactory.newClient(config);
client.setPosRef(trx.getPosRef());
client.refundTransaction(trx.getExternalId());
final JsonGetTransactionResponse remoteTrx = client.getTransactionById(trx.getExternalId());
return updateTransactionFromRemote(trx, remoteTrx);
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpService.java | 1 |
请完成以下Java代码 | public Expression getDueDateExpression() {
return dueDateExpression;
}
public void setDueDateExpression(Expression dueDateExpression) {
this.dueDateExpression = dueDateExpression;
}
public Expression getBusinessCalendarNameExpression() {
return businessCalendarNameExpression;
}
public void setBusinessCalendarNameExpression(Expression businessCalendarNameExpression) {
this.businessCalendarNameExpression = businessCalendarNameExpression;
}
public Expression getCategoryExpression() {
return categoryExpression;
}
public void setCategoryExpression(Expression categoryExpression) {
this.categoryExpression = categoryExpression;
}
public Map<String, List<TaskListener>> getTaskListeners() {
return taskListeners;
}
public void setTaskListeners(Map<String, List<TaskListener>> taskListeners) {
this.taskListeners = taskListeners;
}
public List<TaskListener> getTaskListener(String eventName) {
return taskListeners.get(eventName);
}
public void addTaskListener(String eventName, TaskListener taskListener) {
if (TaskListener.EVENTNAME_ALL_EVENTS.equals(eventName)) {
// In order to prevent having to merge the "all" tasklisteners with the ones for a specific eventName,
// every time "getTaskListener()" is called, we add the listener explicitly to the individual lists
this.addTaskListener(TaskListener.EVENTNAME_CREATE, taskListener);
this.addTaskListener(TaskListener.EVENTNAME_ASSIGNMENT, taskListener); | this.addTaskListener(TaskListener.EVENTNAME_COMPLETE, taskListener);
this.addTaskListener(TaskListener.EVENTNAME_DELETE, taskListener);
} else {
List<TaskListener> taskEventListeners = taskListeners.get(eventName);
if (taskEventListeners == null) {
taskEventListeners = new ArrayList<>();
taskListeners.put(eventName, taskEventListeners);
}
taskEventListeners.add(taskListener);
}
}
public Expression getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(Expression skipExpression) {
this.skipExpression = skipExpression;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\task\TaskDefinition.java | 1 |
请完成以下Java代码 | public class ElasticsearchProperties {
/**
* 请求协议
*/
private String schema = "http";
/**
* 集群名称
*/
private String clusterName = "elasticsearch";
/**
* 集群节点
*/
@NotNull(message = "集群节点不允许为空")
private List<String> clusterNodes = new ArrayList<>();
/**
* 连接超时时间(毫秒)
*/
private Integer connectTimeout = 1000;
/**
* socket 超时时间
*/
private Integer socketTimeout = 30000;
/**
* 连接请求超时时间
*/
private Integer connectionRequestTimeout = 500;
/**
* 每个路由的最大连接数量
*/
private Integer maxConnectPerRoute = 10;
/**
* 最大连接总数量
*/
private Integer maxConnectTotal = 30;
/**
* 索引配置信息
*/
private Index index = new Index();
/**
* 认证账户
*/
private Account account = new Account();
/**
* 索引配置信息
*/ | @Data
public static class Index {
/**
* 分片数量
*/
private Integer numberOfShards = 3;
/**
* 副本数量
*/
private Integer numberOfReplicas = 2;
}
/**
* 认证账户
*/
@Data
public static class Account {
/**
* 认证用户
*/
private String username;
/**
* 认证密码
*/
private String password;
}
} | repos\spring-boot-demo-master\demo-elasticsearch-rest-high-level-client\src\main\java\com\xkcoding\elasticsearch\config\ElasticsearchProperties.java | 1 |
请完成以下Java代码 | protected void checkUpdateProcess(CommandContext commandContext, JobDefinitionEntity jobDefinition) {
String processDefinitionId = jobDefinition.getProcessDefinitionId();
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateProcessDefinitionById(processDefinitionId);
if (cascade) {
checker.checkUpdateProcessInstanceByProcessDefinitionId(processDefinitionId);
}
}
}
protected void createJobDefinitionOperationLogEntry(UserOperationLogContext opLogContext, Long previousPriority,
JobDefinitionEntity jobDefinition) {
PropertyChange propertyChange = new PropertyChange(
JOB_DEFINITION_OVERRIDING_PRIORITY, previousPriority, jobDefinition.getOverridingJobPriority());
UserOperationLogContextEntry entry = UserOperationLogContextEntryBuilder
.entry(UserOperationLogEntry.OPERATION_TYPE_SET_PRIORITY, EntityTypes.JOB_DEFINITION)
.inContextOf(jobDefinition) | .propertyChanges(propertyChange)
.category(UserOperationLogEntry.CATEGORY_OPERATOR)
.create();
opLogContext.addEntry(entry);
}
protected void createCascadeJobsOperationLogEntry(UserOperationLogContext opLogContext, JobDefinitionEntity jobDefinition) {
// old value is unknown
PropertyChange propertyChange = new PropertyChange(
SetJobPriorityCmd.JOB_PRIORITY_PROPERTY, null, jobDefinition.getOverridingJobPriority());
UserOperationLogContextEntry entry = UserOperationLogContextEntryBuilder
.entry(UserOperationLogEntry.OPERATION_TYPE_SET_PRIORITY, EntityTypes.JOB)
.inContextOf(jobDefinition)
.propertyChanges(propertyChange)
.category(UserOperationLogEntry.CATEGORY_OPERATOR)
.create();
opLogContext.addEntry(entry);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetJobDefinitionPriorityCmd.java | 1 |
请完成以下Java代码 | public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
@Override
public void setPP_Order_ID (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_Value (COLUMNNAME_PP_Order_ID, null);
else
set_Value (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
@Override
public void setProcessed (final boolean Processed)
{ | set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyToPick (final BigDecimal QtyToPick)
{
set_Value (COLUMNNAME_QtyToPick, QtyToPick);
}
@Override
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Line.java | 1 |
请完成以下Java代码 | public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
} | public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc\src\main\java\com\baeldung\students\Student.java | 1 |
请完成以下Java代码 | public String getUserInfo(String userId, String key) {
return commandExecutor.execute(new GetUserInfoCmd(userId, key));
}
public List<String> getUserInfoKeys(String userId) {
return commandExecutor.execute(new GetUserInfoKeysCmd(userId, IdentityInfoEntity.TYPE_USERINFO));
}
public List<String> getUserAccountNames(String userId) {
return commandExecutor.execute(new GetUserInfoKeysCmd(userId, IdentityInfoEntity.TYPE_USERACCOUNT));
}
public void setUserInfo(String userId, String key, String value) {
commandExecutor.execute(new SetUserInfoCmd(userId, key, value));
}
public void deleteUserInfo(String userId, String key) {
commandExecutor.execute(new DeleteUserInfoCmd(userId, key));
}
public void deleteUserAccount(String userId, String accountName) {
commandExecutor.execute(new DeleteUserInfoCmd(userId, accountName));
}
public Account getUserAccount(String userId, String userPassword, String accountName) {
return commandExecutor.execute(new GetUserAccountCmd(userId, userPassword, accountName));
}
public void setUserAccount(String userId, String userPassword, String accountName, String accountUsername, String accountPassword, Map<String, String> accountDetails) { | commandExecutor.execute(new SetUserInfoCmd(userId, userPassword, accountName, accountUsername, accountPassword, accountDetails));
}
public void createTenantUserMembership(String tenantId, String userId) {
commandExecutor.execute(new CreateTenantUserMembershipCmd(tenantId, userId));
}
public void createTenantGroupMembership(String tenantId, String groupId) {
commandExecutor.execute(new CreateTenantGroupMembershipCmd(tenantId, groupId));
}
public void deleteTenantUserMembership(String tenantId, String userId) {
commandExecutor.execute(new DeleteTenantUserMembershipCmd(tenantId, userId));
}
public void deleteTenantGroupMembership(String tenantId, String groupId) {
commandExecutor.execute(new DeleteTenantGroupMembershipCmd(tenantId, groupId));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\IdentityServiceImpl.java | 1 |
请完成以下Java代码 | public class MulticastingClient {
private DatagramSocket socket;
private InetAddress group;
private int expectedServerCount;
private byte[] buf;
public MulticastingClient(int expectedServerCount) throws Exception {
this.expectedServerCount = expectedServerCount;
this.socket = new DatagramSocket();
this.group = InetAddress.getByName("230.0.0.0");
}
public int discoverServers(String msg) throws IOException {
copyMessageOnBuffer(msg);
multicastPacket();
return receivePackets();
}
private void copyMessageOnBuffer(String msg) {
buf = msg.getBytes();
}
private void multicastPacket() throws IOException {
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
socket.send(packet);
}
private int receivePackets() throws IOException {
int serversDiscovered = 0; | while (serversDiscovered != expectedServerCount) {
receivePacket();
serversDiscovered++;
}
return serversDiscovered;
}
private void receivePacket() throws IOException {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
}
public void close() {
socket.close();
}
} | repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\udp\multicast\MulticastingClient.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<SysThirdAccount> bindThirdAppAccount(@RequestBody SysThirdAccount sysThirdAccount){
SysThirdAccount thirdAccount = sysThirdAccountService.bindThirdAppAccountByUserId(sysThirdAccount);
return Result.ok(thirdAccount);
}
/**
* 删除第三方用户信息
* @param sysThirdAccount
* @return
*/
@DeleteMapping("/deleteThirdAccount")
public Result<String> deleteThirdAccountById(@RequestBody SysThirdAccount sysThirdAccount){
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
if(!sysUser.getId().equals(sysThirdAccount.getSysUserId())){
return Result.error("无权修改他人信息");
}
SysThirdAccount thirdAccount = sysThirdAccountService.getById(sysThirdAccount.getId());
if(null == thirdAccount){
return Result.error("未找到改第三方账户信息");
}
sysThirdAccountService.removeById(thirdAccount.getId());
return Result.ok("解绑成功");
}
//========================end 应用低代码账号设置第三方账号绑定 ================================
/**
* 获取企业微信绑定的用户信息
* @param request
* @return
*/
@GetMapping("/getThirdUserByWechat")
public Result<JwSysUserDepartVo> getThirdUserByWechat(HttpServletRequest request){
//获取企业微信配置
Integer tenantId = oConvertUtils.getInt(TokenUtils.getTenantIdByRequest(request),0);
SysThirdAppConfig config = appConfigService.getThirdConfigByThirdType(tenantId, MessageTypeEnum.QYWX.getType());
if (null != config) {
JwSysUserDepartVo list = wechatEnterpriseService.getThirdUserByWechat(tenantId);
return Result.ok(list);
}
return Result.error("企业微信尚未配置,请配置企业微信");
} | /**
* 同步企业微信部门和用户到本地
* @param jwUserDepartJson
* @param request
* @return
*/
@GetMapping("/sync/wechatEnterprise/departAndUser/toLocal")
public Result<SyncInfoVo> syncWechatEnterpriseDepartAndUserToLocal(@RequestParam(name = "jwUserDepartJson") String jwUserDepartJson,HttpServletRequest request){
int tenantId = oConvertUtils.getInt(TokenUtils.getTenantIdByRequest(request), 0);
SyncInfoVo syncInfoVo = wechatEnterpriseService.syncWechatEnterpriseDepartAndUserToLocal(jwUserDepartJson,tenantId);
return Result.ok(syncInfoVo);
}
/**
* 查询被绑定的企业微信用户
* @param request
* @return
*/
@GetMapping("/getThirdUserBindByWechat")
public Result<List<JwUserDepartVo>> getThirdUserBindByWechat(HttpServletRequest request){
int tenantId = oConvertUtils.getInt(TokenUtils.getTenantIdByRequest(request), 0);
List<JwUserDepartVo> jwSysUserDepartVos = wechatEnterpriseService.getThirdUserBindByWechat(tenantId);
return Result.ok(jwSysUserDepartVos);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\ThirdAppController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | 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 |
请完成以下Java代码 | public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Kommentar/Hilfe.
@param Help
Comment or Hint
*/
@Override
public void setHelp (java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Kommentar/Hilfe.
@return Comment or Hint
*/
@Override
public java.lang.String getHelp ()
{
return (java.lang.String)get_Value(COLUMNNAME_Help);
}
/** Set Order By Value.
@param IsOrderByValue
Order list using the value column instead of the name column
*/
@Override
public void setIsOrderByValue (boolean IsOrderByValue)
{
set_Value (COLUMNNAME_IsOrderByValue, Boolean.valueOf(IsOrderByValue));
}
/** Get Order By Value.
@return Order list using the value column instead of the name column
*/
@Override
public boolean isOrderByValue ()
{
Object oo = get_Value(COLUMNNAME_IsOrderByValue);
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
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/**
* ValidationType AD_Reference_ID=2
* Reference name: AD_Reference Validation Types
*/
public static final int VALIDATIONTYPE_AD_Reference_ID=2;
/** ListValidation = L */
public static final String VALIDATIONTYPE_ListValidation = "L"; | /** DataType = D */
public static final String VALIDATIONTYPE_DataType = "D";
/** TableValidation = T */
public static final String VALIDATIONTYPE_TableValidation = "T";
/** Set Validation type.
@param ValidationType
Different method of validating data
*/
@Override
public void setValidationType (java.lang.String ValidationType)
{
set_Value (COLUMNNAME_ValidationType, ValidationType);
}
/** Get Validation type.
@return Different method of validating data
*/
@Override
public java.lang.String getValidationType ()
{
return (java.lang.String)get_Value(COLUMNNAME_ValidationType);
}
/** Set Value Format.
@param VFormat
Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
@Override
public void setVFormat (java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
/** Get Value Format.
@return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
@Override
public java.lang.String getVFormat ()
{
return (java.lang.String)get_Value(COLUMNNAME_VFormat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Reference.java | 1 |
请完成以下Java代码 | public void repeat(CmmnActivityExecution execution, String standardEvent) {
CmmnActivity activity = execution.getActivity();
boolean repeat = false;
if (activity.getEntryCriteria().isEmpty()) {
List<String> events = activity.getProperties().get(CmmnProperties.REPEAT_ON_STANDARD_EVENTS);
if (events != null && events.contains(standardEvent)) {
repeat = evaluateRepetitionRule(execution);
}
}
else {
if (ENABLE.equals(standardEvent) || START.equals(standardEvent) || OCCUR.equals(standardEvent)) {
repeat = evaluateRepetitionRule(execution);
}
}
if (repeat) {
CmmnActivityExecution parent = execution.getParent();
// instantiate a new instance of given activity
List<CmmnExecution> children = parent.createChildExecutions(Arrays.asList(activity));
// start the lifecycle of the new instance
parent.triggerChildExecutionsLifecycle(children);
}
}
// helper //////////////////////////////////////////////////////////////////////
protected void ensureTransitionAllowed(CmmnActivityExecution execution, CaseExecutionState expected, CaseExecutionState target, String transition) {
String id = execution.getId();
CaseExecutionState currentState = execution.getCurrentState();
// the state "suspending" or "terminating" will set immediately
// inside the corresponding AtomicOperation, that's why the
// previous state will be used to ensure that the transition
// is allowed.
if (execution.isTerminating() || execution.isSuspending()) {
currentState = execution.getPreviousState();
}
// is the case execution already in the target state
if (target.equals(currentState)) {
throw LOG.isAlreadyInStateException(transition, id, target); | } else
// is the case execution in the expected state
if (!expected.equals(currentState)) {
throw LOG.unexpectedStateException(transition, id, expected, currentState);
}
}
protected void ensureNotCaseInstance(CmmnActivityExecution execution, String transition) {
if (execution.isCaseInstanceExecution()) {
String id = execution.getId();
throw LOG.impossibleTransitionException(transition, id);
}
}
protected CmmnActivity getActivity(CmmnActivityExecution execution) {
String id = execution.getId();
CmmnActivity activity = execution.getActivity();
ensureNotNull(PvmException.class, "Case execution '"+id+"': has no current activity.", "activity", activity);
return activity;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\PlanItemDefinitionActivityBehavior.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void persistAuthorWithBooks() {
Author author = new Author();
author.setName("Alicia Tom");
author.setAge(38);
author.setGenre("Anthology");
Paperback paperback = new Paperback();
paperback.setIsbn("002-AT");
paperback.setTitle("The beatles anthology");
paperback.setSizeIn("7.5 x 1.3 x 9.2");
paperback.setWeightLbs("2.7");
paperback.setAuthor(author);
Ebook ebook = new Ebook();
ebook.setIsbn("003-AT");
ebook.setTitle("Anthology myths");
ebook.setFormat("kindle");
ebook.setAuthor(author); | authorRepository.save(author);
paperbackRepository.save(paperback);
ebookRepository.save(ebook);
}
@Transactional
public void fetchAndRemovePaperback() {
Paperback paperback = paperbackRepository
.findByTitle("The beatles anthology");
paperbackRepository.delete(paperback);
}
@Transactional
public void fetchAndRemoveEbook() {
Ebook ebook = ebookRepository
.findByTitle("Anthology myths");
ebookRepository.delete(ebook);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootEntityListener\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | Stream<BOMCostPrice> streamCostPrices()
{
final Stream<BOMCostPrice> linesCostPrices = getLines().stream().map(BOMLine::getCostPrice);
return Stream.concat(Stream.of(getCostPrice()), linesCostPrices);
}
private ImmutableSet<CostElementId> getCostElementIds()
{
return streamCostPrices()
.flatMap(BOMCostPrice::streamCostElementIds)
.distinct()
.collect(ImmutableSet.toImmutableSet());
}
<T extends RepoIdAware> Set<T> getCostIds(@NonNull final Class<T> idType)
{
return streamCostPrices()
.flatMap(bomCostPrice -> bomCostPrice.streamIds(idType))
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet()); | }
public Set<ProductId> getProductIds()
{
final ImmutableSet.Builder<ProductId> productIds = ImmutableSet.builder();
productIds.add(getProductId());
getLines().forEach(bomLine -> productIds.add(bomLine.getComponentId()));
return productIds.build();
}
public ImmutableList<BOMCostElementPrice> getElementPrices()
{
return getCostPrice().getElementPrices();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\costing\BOM.java | 1 |
请完成以下Java代码 | public void setPickFrom_HU_ID (final int PickFrom_HU_ID)
{
if (PickFrom_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_PickFrom_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID);
}
@Override
public int getPickFrom_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID);
}
@Override
public void setPickFrom_Locator_ID (final int PickFrom_Locator_ID)
{
if (PickFrom_Locator_ID < 1)
set_Value (COLUMNNAME_PickFrom_Locator_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Locator_ID, PickFrom_Locator_ID);
}
@Override
public int getPickFrom_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID);
}
@Override
public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID)
{
if (PickFrom_Warehouse_ID < 1)
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID);
}
@Override
public int getPickFrom_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID);
}
@Override
public void setQtyPicked (final BigDecimal QtyPicked)
{
set_Value (COLUMNNAME_QtyPicked, QtyPicked);
}
@Override
public BigDecimal getQtyPicked()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyToPick (final BigDecimal QtyToPick)
{ | set_ValueNoCheck (COLUMNNAME_QtyToPick, QtyToPick);
}
@Override
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int REJECTREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D";
@Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_Value (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
/**
* Status AD_Reference_ID=541435
* Reference name: DD_OrderLine_Schedule_Status
*/
public static final int STATUS_AD_Reference_ID=541435;
/** NotStarted = NS */
public static final String STATUS_NotStarted = "NS";
/** InProgress = IP */
public static final String STATUS_InProgress = "IP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_DD_Order_MoveSchedule.java | 1 |
请完成以下Java代码 | public class ServerWebExchangeDelegatingServerAccessDeniedHandler implements ServerAccessDeniedHandler {
private final List<DelegateEntry> handlers;
private ServerAccessDeniedHandler defaultHandler = (exchange, ex) -> {
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
return exchange.getResponse().setComplete();
};
/**
* Creates a new instance
* @param handlers a list of {@link ServerWebExchangeMatcher}/
* {@link ServerAccessDeniedHandler} pairs that should be used. Each is considered in
* the order they are specified and only the first {@link ServerAccessDeniedHandler}
* is used. If none match, then the default {@link ServerAccessDeniedHandler} is used.
*/
public ServerWebExchangeDelegatingServerAccessDeniedHandler(DelegateEntry... handlers) {
this(Arrays.asList(handlers));
}
/**
* Creates a new instance
* @param handlers a list of {@link ServerWebExchangeMatcher}/
* {@link ServerAccessDeniedHandler} pairs that should be used. Each is considered in
* the order they are specified and only the first {@link ServerAccessDeniedHandler}
* is used. If none match, then the default {@link ServerAccessDeniedHandler} is used.
*/
public ServerWebExchangeDelegatingServerAccessDeniedHandler(List<DelegateEntry> handlers) {
Assert.notEmpty(handlers, "handlers cannot be null");
this.handlers = handlers;
}
@Override
public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
return Flux.fromIterable(this.handlers)
.filterWhen((entry) -> isMatch(exchange, entry))
.next()
.map(DelegateEntry::getAccessDeniedHandler)
.defaultIfEmpty(this.defaultHandler)
.flatMap((handler) -> handler.handle(exchange, denied));
}
/**
* Use this {@link ServerAccessDeniedHandler} when no {@link ServerWebExchangeMatcher}
* matches.
* @param accessDeniedHandler - the default {@link ServerAccessDeniedHandler} to use
*/
public void setDefaultAccessDeniedHandler(ServerAccessDeniedHandler accessDeniedHandler) {
Assert.notNull(accessDeniedHandler, "accessDeniedHandler cannot be null");
this.defaultHandler = accessDeniedHandler;
}
private Mono<Boolean> isMatch(ServerWebExchange exchange, DelegateEntry entry) {
ServerWebExchangeMatcher matcher = entry.getMatcher();
return matcher.matches(exchange).map(ServerWebExchangeMatcher.MatchResult::isMatch); | }
public static class DelegateEntry {
private final ServerWebExchangeMatcher matcher;
private final ServerAccessDeniedHandler accessDeniedHandler;
public DelegateEntry(ServerWebExchangeMatcher matcher, ServerAccessDeniedHandler accessDeniedHandler) {
this.matcher = matcher;
this.accessDeniedHandler = accessDeniedHandler;
}
public ServerWebExchangeMatcher getMatcher() {
return this.matcher;
}
public ServerAccessDeniedHandler getAccessDeniedHandler() {
return this.accessDeniedHandler;
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandler.java | 1 |
请完成以下Java代码 | public class X_CM_AccessMedia extends PO implements I_CM_AccessMedia, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_CM_AccessMedia (Properties ctx, int CM_AccessMedia_ID, String trxName)
{
super (ctx, CM_AccessMedia_ID, trxName);
/** if (CM_AccessMedia_ID == 0)
{
setCM_AccessProfile_ID (0);
setCM_Media_ID (0);
} */
}
/** Load Constructor */
public X_CM_AccessMedia (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 6 - System - Client
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_CM_AccessMedia[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException
{
return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name)
.getPO(getCM_AccessProfile_ID(), get_TrxName()); }
/** Set Web Access Profile.
@param CM_AccessProfile_ID
Web Access Profile
*/
public void setCM_AccessProfile_ID (int CM_AccessProfile_ID)
{
if (CM_AccessProfile_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID));
}
/** Get Web Access Profile.
@return Web Access Profile
*/
public int getCM_AccessProfile_ID ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_Media getCM_Media() throws RuntimeException
{
return (I_CM_Media)MTable.get(getCtx(), I_CM_Media.Table_Name)
.getPO(getCM_Media_ID(), get_TrxName()); }
/** Set Media Item.
@param CM_Media_ID
Contains media content like images, flash movies etc.
*/
public void setCM_Media_ID (int CM_Media_ID)
{
if (CM_Media_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Media_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Media_ID, Integer.valueOf(CM_Media_ID));
}
/** Get Media Item.
@return Contains media content like images, flash movies etc.
*/
public int getCM_Media_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Media_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessMedia.java | 1 |
请完成以下Java代码 | public void setQtyTU(final BigDecimal qtyPacks)
{
values.setQtyTU(qtyPacks);
}
@Override
public int getC_BPartner_ID()
{
final BPartnerId bpartnerId = olCandEffectiveValuesBL.getBPartnerEffectiveId(olCand);
return BPartnerId.toRepoId(bpartnerId);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
olCand.setC_BPartner_Override_ID(partnerId); | values.setBpartnerId(BPartnerId.ofRepoIdOrNull(partnerId));
}
@Override
public boolean isInDispute()
{
// order line has no IsInDispute flag
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OLCandHUPackingAware.java | 1 |
请完成以下Java代码 | public @NonNull String getColumnSql(@NonNull final String columnName)
{
return " cast_to_numeric_or_null (" + columnName + ") " ;
}
@Override
public String getValueSql(final Object value, final List<Object> params)
{
if (value instanceof ModelColumnNameValue<?>)
{
final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value;
return modelValue.getColumnName();
}
params.add(value); | return "?";
}
@Nullable
@Override
public Object convertValue(@Nullable final String columnName, @Nullable final Object value, @Nullable final Object model)
{
if (value == null)
{
return null;
}
return NumberUtils.asBigDecimal(value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\StringToNumericModifier.java | 1 |
请完成以下Java代码 | public static class Barcodes {
@XmlElement(name = "BarcodeNr")
protected List<String> barcodeNr;
/**
* Gets the value of the barcodeNr 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 barcodeNr property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getBarcodeNr().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String } | *
*
*/
public List<String> getBarcodeNr() {
if (barcodeNr == null) {
barcodeNr = new ArrayList<String>();
}
return this.barcodeNr;
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\SendungsRueckmeldung.java | 1 |
请完成以下Java代码 | public void actionPerformed (ActionEvent e)
{
// Show Dialog
MFColor cc = ColorEditor.showDialog(SwingUtils.getFrame(this), color);
if (cc == null)
{
log.info( "VColor.actionPerformed - no color");
return;
}
setBackgroundColor(cc); // set Button
repaint();
// Update Values
m_mTab.setValue("ColorType", cc.getType().getCode());
if (cc.isFlat())
{
setColor (cc.getFlatColor(), true);
}
else if (cc.isGradient())
{
setColor (cc.getGradientUpperColor(), true);
setColor (cc.getGradientLowerColor(), false);
m_mTab.setValue("RepeatDistance", new BigDecimal(cc.getGradientRepeatDistance()));
m_mTab.setValue("StartPoint", String.valueOf(cc.getGradientStartPoint()));
}
else if (cc.isLine())
{
setColor (cc.getLineBackColor(), true);
setColor (cc.getLineColor(), false);
m_mTab.getValue("LineWidth");
m_mTab.getValue("LineDistance");
}
else if (cc.isTexture())
{
setColor (cc.getTextureTaintColor(), true);
// URL url = cc.getTextureURL();
// m_mTab.setValue("AD_Image_ID");
m_mTab.setValue("ImageAlpha", new BigDecimal(cc.getTextureCompositeAlpha()));
}
color = cc;
} // actionPerformed | /**
* Set Color in Tab
* @param c Color
* @param primary true if primary false if secondary
*/
private void setColor (Color c, boolean primary)
{
String add = primary ? "" : "_1";
m_mTab.setValue("Red" + add, new BigDecimal(c.getRed()));
m_mTab.setValue("Green" + add, new BigDecimal(c.getGreen()));
m_mTab.setValue("Blue" + add, new BigDecimal(c.getBlue()));
} // setColor
// metas: Ticket#2011062310000013
@Override
public boolean isAutoCommit()
{
return false;
}
} // VColor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VColor.java | 1 |
请完成以下Java代码 | public void listAllObjectsInBucketPaginated(String bucketName, int pageSize) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(pageSize) // Set the maxKeys parameter to control the page size
.build();
ListObjectsV2Iterable listObjectsV2Iterable = s3Client.listObjectsV2Paginator(listObjectsV2Request);
long totalObjects = 0;
for (ListObjectsV2Response page : listObjectsV2Iterable) {
long retrievedPageSize = page.contents().stream()
.peek(System.out::println)
.reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
totalObjects += retrievedPageSize;
System.out.println("Page size: " + retrievedPageSize);
}
System.out.println("Total objects in the bucket: " + totalObjects);
}
public void listAllObjectsInBucketPaginatedWithPrefix(String bucketName, int pageSize, String prefix) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(pageSize) // Set the maxKeys parameter to control the page size
.prefix(prefix)
.build();
ListObjectsV2Iterable listObjectsV2Iterable = s3Client.listObjectsV2Paginator(listObjectsV2Request);
long totalObjects = 0;
for (ListObjectsV2Response page : listObjectsV2Iterable) {
long retrievedPageSize = page.contents().stream()
.peek(System.out::println) | .reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
totalObjects += retrievedPageSize;
System.out.println("Page size: " + retrievedPageSize);
}
System.out.println("Total objects in the bucket: " + totalObjects);
}
public void putObjects(String bucketName, List<File> files) {
try {
files.stream().forEach(file -> {
s3Client.putObject(PutObjectRequest.builder().bucket(bucketName).key(file.getName()).build(),
RequestBody.fromByteBuffer(file.getContent()));
System.out.println("Uploaded file: " + file.getName());
});
} catch (S3Exception e) {
System.err.println("Upload failed");
e.printStackTrace();
}
}
public void cleanup() {
this.s3Client.close();
}
} | repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\S3Service.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Receiver
{
/**
* Note that for now we don't include the email's active status, because the remote system is the source of truth for that.
*/
public static Receiver of(@NonNull final ContactPerson contactPerson)
{
final int id = StringUtils.trimBlankToOptional(contactPerson.getRemoteId()).map(Integer::parseInt).orElse(0);
return builder()
.id(id)
.email(contactPerson.getEmailAddressStringOrNull())
.build();
}
int id;
String email;
int imported;
int points;
int bounced;
String last_ip;
String last_location;
String last_client;
int groups_id;
long activated;
long registered;
long deactivated;
String source;
boolean active;
int stars;
Map<String, String> global_attributes;
Map<String, String> attributes;
@JsonCreator
@Builder
public Receiver(
@JsonProperty("id") int id,
@JsonProperty("email") String email,
@JsonProperty("imported") int imported,
@JsonProperty("points") int points,
@JsonProperty("bounced") int bounced,
@JsonProperty("last_ip") String last_ip,
@JsonProperty("last_location") String last_location,
@JsonProperty("last_client") String last_client,
@JsonProperty("groups_id") int groups_id,
@JsonProperty("activated") long activated,
@JsonProperty("registered") long registered,
@JsonProperty("deactivated") long deactivated,
@JsonProperty("source") String source,
@JsonProperty("active") boolean active,
@JsonProperty("stars") int stars,
@JsonProperty("global_attributes") @Singular Map<String, String> global_attributes,
@JsonProperty("attributes") @Singular Map<String, String> attributes)
{
this.id = id; | this.email = email;
this.imported = imported;
this.points = points;
this.bounced = bounced;
this.last_ip = last_ip;
this.last_location = last_location;
this.last_client = last_client;
this.groups_id = groups_id;
this.activated = activated;
this.registered = registered;
this.deactivated = deactivated;
this.source = source;
this.active = active;
this.stars = stars;
this.global_attributes = global_attributes;
this.attributes = attributes;
}
public ContactPersonRemoteUpdate toContactPersonUpdate()
{
return ContactPersonRemoteUpdate.builder()
.remoteId(String.valueOf(id))
.address(EmailAddress.of(email, DeactivatedOnRemotePlatform.ofIsActiveFlag(active)))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java\de\metas\marketing\gateway\cleverreach\restapi\models\Receiver.java | 2 |
请完成以下Java代码 | private ItemReader<TestData> multiFileItemReader() {
MultiResourceItemReader<TestData> reader = new MultiResourceItemReader<>();
reader.setDelegate(fileItemReader()); // 设置文件读取代理,方法可以使用前面文件读取中的例子
Resource[] resources = new Resource[]{
new ClassPathResource("file1"),
new ClassPathResource("file2")
};
reader.setResources(resources); // 设置多文件源
return reader;
}
private FlatFileItemReader<TestData> fileItemReader() {
FlatFileItemReader<TestData> reader = new FlatFileItemReader<>();
reader.setLinesToSkip(1); // 忽略第一行
// AbstractLineTokenizer的三个实现类之一,以固定分隔符处理行数据读取,
// 使用默认构造器的时候,使用逗号作为分隔符,也可以通过有参构造器来指定分隔符
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
// 设置属姓名,类似于表头
tokenizer.setNames("id", "field1", "field2", "field3"); | // 将每行数据转换为TestData对象
DefaultLineMapper<TestData> mapper = new DefaultLineMapper<>();
mapper.setLineTokenizer(tokenizer);
// 设置映射方式
mapper.setFieldSetMapper(fieldSet -> {
TestData data = new TestData();
data.setId(fieldSet.readInt("id"));
data.setField1(fieldSet.readString("field1"));
data.setField2(fieldSet.readString("field2"));
data.setField3(fieldSet.readString("field3"));
return data;
});
reader.setLineMapper(mapper);
return reader;
}
} | repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\MultiFileIteamReaderDemo.java | 1 |
请完成以下Java代码 | public static boolean contains(final CharSequence seq, final CharSequence searchSeq) {
return Strings.CS.contains(seq, searchSeq);
}
/**
* Use this to prevent org.postgresql.util.PSQLException: ERROR: invalid byte sequence for encoding "UTF8": 0x00
**/
public static boolean contains0x00(final String s) {
return s != null && s.contains("\u0000");
}
public static String randomNumeric(int length) {
return RandomStringUtils.secure().nextNumeric(length);
}
public static String random(int length) {
return RandomStringUtils.secure().next(length);
}
public static String random(int length, String chars) {
return RandomStringUtils.secure().next(length, chars);
}
public static String randomAlphanumeric(int count) {
return RandomStringUtils.secure().nextAlphanumeric(count);
}
public static String randomAlphabetic(int count) {
return RandomStringUtils.secure().nextAlphabetic(count);
}
public static String generateSafeToken(int length) {
byte[] bytes = new byte[length];
RANDOM.nextBytes(bytes);
Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
return encoder.encodeToString(bytes);
}
public static String generateSafeToken() {
return generateSafeToken(DEFAULT_TOKEN_LENGTH);
}
public static String truncate(String string, int maxLength) {
return truncate(string, maxLength, n -> "...[truncated " + n + " symbols]");
}
public static String truncate(String string, int maxLength, Function<Integer, String> truncationMarkerFunc) {
if (string == null || maxLength <= 0 || string.length() <= maxLength) {
return string;
} | int truncatedSymbols = string.length() - maxLength;
return string.substring(0, maxLength) + truncationMarkerFunc.apply(truncatedSymbols);
}
public static List<String> splitByCommaWithoutQuotes(String value) {
List<String> splitValues = List.of(value.trim().split("\\s*,\\s*"));
List<String> result = new ArrayList<>();
char lastWayInputValue = '#';
for (String str : splitValues) {
char startWith = str.charAt(0);
char endWith = str.charAt(str.length() - 1);
// if first value is not quote, so we return values after split
if (startWith != '\'' && startWith != '"') return splitValues;
// if value is not in quote, so we return values after split
if (startWith != endWith) return splitValues;
// if different way values, so don't replace quote and return values after split
if (lastWayInputValue != '#' && startWith != lastWayInputValue) return splitValues;
result.add(str.substring(1, str.length() - 1));
lastWayInputValue = startWith;
}
return result;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\StringUtils.java | 1 |
请完成以下Java代码 | public Builder setGrandTotal(final BigDecimal grandTotal)
{
this.grandTotal = grandTotal;
return this;
}
public Builder setGrandTotalConv(final BigDecimal grandTotalConv)
{
this.grandTotalConv = grandTotalConv;
return this;
}
public Builder setOpenAmtConv(final BigDecimal openAmtConv)
{
this.openAmtConv = openAmtConv;
return this;
}
public Builder setDiscount(final BigDecimal discount)
{
this.discount = discount;
return this;
}
public Builder setPaymentRequestAmt(final BigDecimal paymentRequestAmt)
{
Check.assumeNotNull(paymentRequestAmt, "paymentRequestAmt not null");
this.paymentRequestAmtSupplier = Suppliers.ofInstance(paymentRequestAmt);
return this;
}
public Builder setPaymentRequestAmt(final Supplier<BigDecimal> paymentRequestAmtSupplier)
{
this.paymentRequestAmtSupplier = paymentRequestAmtSupplier;
return this;
}
public Builder setMultiplierAP(final BigDecimal multiplierAP) | {
this.multiplierAP = multiplierAP;
return this;
}
public Builder setIsPrepayOrder(final boolean isPrepayOrder)
{
this.isPrepayOrder = isPrepayOrder;
return this;
}
public Builder setPOReference(final String POReference)
{
this.POReference = POReference;
return this;
}
public Builder setCreditMemo(final boolean creditMemo)
{
this.creditMemo = creditMemo;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceRow.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.