instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(ApplicationConfiguration.class); ctx.setServletContext(container); // Manage the lifecycle of the root application context container.addListener(new ContextLoaderListener(ctx)); ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.setLoadOnStartup(1); servlet.addMapping("/"); } // @Override // public void onStartup(ServletContext container) { // // Create the 'root' Spring application context
// AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); // rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class); // // // Manage the lifecycle of the root application context // container.addListener(new ContextLoaderListener(rootContext)); // // // Create the dispatcher servlet's Spring application context // AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext(); // dispatcherServlet.register(MvcConfig.class); // // // Register and map the dispatcher servlet // ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet)); // dispatcher.setLoadOnStartup(1); // dispatcher.addMapping("/"); // // } }
repos\tutorials-master\spring-web-modules\spring-mvc-forms-jsp\src\main\java\com\baeldung\springmvcforms\configuration\WebInitializer.java
2
请完成以下Java代码
public Object getValue(ELContext context, Object base, Object property) { if (base == null) { if (wrappedMap.containsKey(property)) { context.setPropertyResolved(true); return wrappedMap.get(property); } } return null; } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return true; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { if (base == null) { if (wrappedMap.containsKey(property)) {
throw new ActivitiException("Cannot set value of '" + property + "', it's readonly!"); } } } @Override public Class<?> getCommonPropertyType(ELContext context, Object arg) { return Object.class; } @Override public Class<?> getType(ELContext context, Object arg1, Object arg2) { return Object.class; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\el\ReadOnlyMapELResolver.java
1
请完成以下Java代码
private final String getSysConfigValue(final String sysConfigName) { final Map<String, String> properties = getPropertiesMap(); if (properties == null) // shall not happen { return null; } final String value = properties.get(sysConfigName); return value; } private Map<String, String> getPropertiesMap() { final Properties ctx = Env.getCtx(); final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(Env.getClientId(ctx), Env.getOrgId(ctx)); final boolean removePrefix = false; // keep the prefix, our BL is relying on that // Load the properties map from underlying database final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); return sysConfigBL.getValuesForPrefix(CFG_C_LOGGER_LEVEL_PREFIX, removePrefix, clientAndOrgId); } @Override public String dumpConfig() { final Map<String, String> propertiesMap = getPropertiesMap();
final StringBuilder out = new StringBuilder(); out.append("Customizer class: " + getClass().getName() + "\n"); out.append("Hostname (with dot): " + getHostNameWithDot() + "\n"); out.append("Logger settings from SysConfig (count=" + propertiesMap.size() + "):" + "\n"); for (final String key : propertiesMap.keySet()) { out.append("\t" + key + " = " + propertiesMap.get(key) + "\n"); } return out.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\SysConfigLoggerCustomizer.java
1
请完成以下Java代码
public int getC_Root_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_Root_BPartner_ID); } @Override public void setExternalSystem_Config_Alberta_ID (final int ExternalSystem_Config_Alberta_ID) { if (ExternalSystem_Config_Alberta_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Alberta_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Alberta_ID, ExternalSystem_Config_Alberta_ID); } @Override public int getExternalSystem_Config_Alberta_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Alberta_ID); } @Override public I_ExternalSystem_Config getExternalSystem_Config() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class); } @Override public void setExternalSystem_Config(final I_ExternalSystem_Config ExternalSystem_Config) { set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class, ExternalSystem_Config); } @Override public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID()
{ return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystemValue (final String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } @Override public void setPharmacy_PriceList_ID (final int Pharmacy_PriceList_ID) { if (Pharmacy_PriceList_ID < 1) set_Value (COLUMNNAME_Pharmacy_PriceList_ID, null); else set_Value (COLUMNNAME_Pharmacy_PriceList_ID, Pharmacy_PriceList_ID); } @Override public int getPharmacy_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_Pharmacy_PriceList_ID); } @Override public void setTenant (final String Tenant) { set_Value (COLUMNNAME_Tenant, Tenant); } @Override public String getTenant() { return get_ValueAsString(COLUMNNAME_Tenant); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Alberta.java
1
请完成以下Java代码
public final void put(final IView view) { views.put(view.getViewId(), PurchaseView.cast(view)); } @Nullable @Override public final PurchaseView getByIdOrNull(final ViewId viewId) { return views.getIfPresent(viewId); } public final PurchaseView getById(final ViewId viewId) { final PurchaseView view = getByIdOrNull(viewId); if (view == null) { throw new EntityNotFoundException("View " + viewId + " was not found"); } return view; } @Override public final void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { final PurchaseView view = views.getIfPresent(viewId); if (view == null || !view.isAllowClosingPerUserRequest()) { return; } if (closeAction.isDone()) { onViewClosedByUser(view); } views.invalidate(viewId); views.cleanUp(); // also cleanup to prevent views cache to grow. } @Override public final Stream<IView> streamAllViews() { return Stream.empty(); } @Override public final void invalidateView(final ViewId viewId) { final IView view = getByIdOrNull(viewId); if (view == null) { return; } view.invalidateAll(); } @Override public final PurchaseView createView(@NonNull final CreateViewRequest request) { final ViewId viewId = newViewId(); final List<PurchaseDemand> demands = getDemands(request); final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList = purchaseDemandWithCandidatesService.getOrCreatePurchaseCandidatesGroups(demands); final PurchaseRowsSupplier rowsSupplier = createRowsSupplier(viewId, purchaseDemandWithCandidatesList); final PurchaseView view = PurchaseView.builder() .viewId(viewId)
.rowsSupplier(rowsSupplier) .additionalRelatedProcessDescriptors(getAdditionalProcessDescriptors()) .build(); return view; } protected List<RelatedProcessDescriptor> getAdditionalProcessDescriptors() { return ImmutableList.of(); } private final PurchaseRowsSupplier createRowsSupplier( final ViewId viewId, final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList) { final PurchaseRowsSupplier rowsSupplier = PurchaseRowsLoader.builder() .purchaseDemandWithCandidatesList(purchaseDemandWithCandidatesList) .viewSupplier(() -> getByIdOrNull(viewId)) // needed for async stuff .purchaseRowFactory(purchaseRowFactory) .availabilityCheckService(availabilityCheckService) .build() .createPurchaseRowsSupplier(); return rowsSupplier; } protected final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { final AdProcessId processId = adProcessRepo.retrieveProcessIdByClassIfUnique(processClass); Preconditions.checkArgument(processId != null, "No AD_Process_ID found for %s", processClass); return RelatedProcessDescriptor.builder() .processId(processId) .displayPlace(DisplayPlace.ViewQuickActions) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseViewFactoryTemplate.java
1
请完成以下Java代码
public class PlanFragmentImpl extends PlanItemDefinitionImpl implements PlanFragment { protected static ChildElementCollection<PlanItem> planItemCollection; protected static ChildElementCollection<Sentry> sentryCollection; public PlanFragmentImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public Collection<PlanItem> getPlanItems() { return planItemCollection.get(this); } public Collection<Sentry> getSentrys() { return sentryCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanFragment.class, CMMN_ELEMENT_PLAN_FRAGMENT) .namespaceUri(CMMN11_NS) .extendsType(PlanItemDefinition.class) .instanceProvider(new ModelTypeInstanceProvider<PlanFragment>() { public PlanFragment newInstance(ModelTypeInstanceContext instanceContext) {
return new PlanFragmentImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); planItemCollection = sequenceBuilder.elementCollection(PlanItem.class) .build(); sentryCollection = sequenceBuilder.elementCollection(Sentry.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanFragmentImpl.java
1
请完成以下Java代码
default IQuery<T> addUnions(final Collection<IQuery<T>> queries, final boolean distinct) { queries.forEach(query -> addUnion(query, distinct)); return this; } /** * @return UNION DISTINCT {@link IQuery} reducer */ static <T> BinaryOperator<IQuery<T>> unionDistict() { return (previousDBQuery, dbQuery) -> { if (previousDBQuery == null) { return dbQuery; } else { previousDBQuery.addUnion(dbQuery, true); return previousDBQuery; } }; } /** * Creates a NEW selection from this query result. * * @return selection's or <code>null</code> if there were no records matching */ PInstanceId createSelection(); /** * Appends this query result to an existing selection. * * @param pinstanceId selection ID to be used * @return number of records inserted in selection */ int createSelection(PInstanceId pinstanceId); /** * Use the result of this query and insert it in given <code>toModelClass</code>'s table. * * @return executor which will assist you with the INSERT. */ <ToModelType> IQueryInsertExecutor<ToModelType, T> insertDirectlyInto(Class<ToModelType> toModelClass); /** * Return a stream of all records that match the query criteria. */ default Stream<T> stream() throws DBException { return list().stream(); }
default Stream<T> iterateAndStream() throws DBException { final Iterator<T> iterator = iterate(getModelClass()); final boolean parallel = false; return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), parallel); } default <ID extends RepoIdAware> Stream<ID> iterateAndStreamIds(@NonNull final IntFunction<ID> idMapper) throws DBException { final Iterator<ID> iterator = iterateIds(idMapper); final boolean parallel = false; return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), parallel); } /** * Return a stream of all records that match the query criteria. * * @param clazz all resulting models will be converted to this interface * @return Stream */ default <ET extends T> Stream<ET> stream(final Class<ET> clazz) throws DBException { return list(clazz).stream(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\IQuery.java
1
请完成以下Java代码
public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\r=\b\1\4\2\t\2\4"+ "\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t"+ "\13\4\f\t\f\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\7\3\7\3\b\3\b\3"+ "\t\6\t)\n\t\r\t\16\t*\3\n\6\n.\n\n\r\n\16\n/\3\13\5\13\63\n\13\3\13\3"+ "\13\3\f\6\f8\n\f\r\f\16\f9\3\f\3\f\2\2\r\3\3\5\4\7\5\t\6\13\7\r\b\17\t"+ "\21\n\23\13\25\f\27\r\3\2\5\4\2C\\c|\3\2\62;\4\2\13\13\"\"\2@\2\3\3\2"+ "\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17"+ "\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\3\31\3\2"+ "\2\2\5\33\3\2\2\2\7\35\3\2\2\2\t\37\3\2\2\2\13!\3\2\2\2\r#\3\2\2\2\17"+ "%\3\2\2\2\21(\3\2\2\2\23-\3\2\2\2\25\62\3\2\2\2\27\67\3\2\2\2\31\32\7"+ "?\2\2\32\4\3\2\2\2\33\34\7*\2\2\34\6\3\2\2\2\35\36\7+\2\2\36\b\3\2\2\2"+
"\37 \7,\2\2 \n\3\2\2\2!\"\7\61\2\2\"\f\3\2\2\2#$\7-\2\2$\16\3\2\2\2%&"+ "\7/\2\2&\20\3\2\2\2\')\t\2\2\2(\'\3\2\2\2)*\3\2\2\2*(\3\2\2\2*+\3\2\2"+ "\2+\22\3\2\2\2,.\t\3\2\2-,\3\2\2\2./\3\2\2\2/-\3\2\2\2/\60\3\2\2\2\60"+ "\24\3\2\2\2\61\63\7\17\2\2\62\61\3\2\2\2\62\63\3\2\2\2\63\64\3\2\2\2\64"+ "\65\7\f\2\2\65\26\3\2\2\2\668\t\4\2\2\67\66\3\2\2\289\3\2\2\29\67\3\2"+ "\2\29:\3\2\2\2:;\3\2\2\2;<\b\f\2\2<\30\3\2\2\2\7\2*/\629\3\b\2\2"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\LabeledExprLexer.java
1
请完成以下Java代码
private ProductPlanning findPP_Product_Planning(@NonNull final I_PP_Order ppOrderWithProductId) { final ProductPlanningQuery query = ProductPlanningQuery.builder() .orgId(OrgId.ofRepoIdOrAny(ppOrderWithProductId.getAD_Org_ID())) .warehouseId(WarehouseId.ofRepoIdOrNull(ppOrderWithProductId.getM_Warehouse_ID())) .plantId(ResourceId.ofRepoIdOrNull(ppOrderWithProductId.getS_Resource_ID())) .productId(ProductId.ofRepoId(ppOrderWithProductId.getM_Product_ID())) .includeWithNullProductId(false) .attributeSetInstanceId(AttributeSetInstanceId.ofRepoId(ppOrderWithProductId.getM_AttributeSetInstance_ID())) .build(); final ProductPlanning productPlanningOrig = productPlanningDAO.find(query).orElse(null); final ProductPlanning.ProductPlanningBuilder builder; if (productPlanningOrig == null) { builder = ProductPlanning.builder() .orgId(OrgId.ofRepoId(ppOrderWithProductId.getAD_Org_ID())) .warehouseId(WarehouseId.ofRepoIdOrNull(ppOrderWithProductId.getM_Warehouse_ID())) .plantId(ResourceId.ofRepoIdOrNull(ppOrderWithProductId.getS_Resource_ID())) .productId(ProductId.ofRepoId(ppOrderWithProductId.getM_Product_ID())); } else { builder = productPlanningOrig.toBuilder();
} builder.disallowSaving(true); final ProductId productId = ProductId.ofRepoId(ppOrderWithProductId.getM_Product_ID()); // pp itself might not have M_Product_ID>0, so we use the PP_Order's one if (productPlanningOrig == null || productPlanningOrig.getWorkflowId() == null) { final PPRoutingId routingId = routingRepo.getRoutingIdByProductId(productId); builder.workflowId(routingId); } if (productPlanningOrig == null || productPlanningOrig.getBomVersionsId() == null) { bomVersionsRepo.retrieveBOMVersionsId(productId).ifPresent(builder::bomVersionsId); } return builder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\callout\PP_Order.java
1
请完成以下Java代码
public void setIp(String ip) { this.ip = ip; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public Date getLastFetch() {
return lastFetch; } public void setLastFetch(Date lastFetch) { this.lastFetch = lastFetch; } @Override public String toString() { return "MetricPositionEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", hostname='" + hostname + '\'' + ", lastFetch=" + lastFetch + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricPositionEntity.java
1
请完成以下Java代码
public void setBinaryData(final I_AD_Archive archive, final byte[] data) { checkContext(); Check.assumeNotNull(archive, "archive not null"); final int archiveId = archive.getAD_Archive_ID(); final ArchiveSetDataRequest request = new ArchiveSetDataRequest(); request.setAdArchiveId(archiveId); request.setData(data); final ArchiveSetDataResponse response = endpoint.setArchiveData(request); final int tempArchiveId = response.getAdArchiveId(); transferData(archive, tempArchiveId); } private void transferData(final I_AD_Archive archive, final int fromTempArchiveId) { Check.assume(fromTempArchiveId > 0, "fromTempArchiveId > 0"); final Properties ctx = InterfaceWrapperHelper.getCtx(archive); final String trxName = InterfaceWrapperHelper.getTrxName(archive); final I_AD_Archive tempArchive = InterfaceWrapperHelper.create(ctx, fromTempArchiveId, I_AD_Archive.class, trxName);
Check.assumeNotNull(tempArchive, "Temporary archive not found for AD_Archive_ID={}", fromTempArchiveId); transferData(archive, tempArchive); InterfaceWrapperHelper.delete(tempArchive); } private void transferData(final I_AD_Archive archive, final I_AD_Archive fromTempArchive) { Check.assume(fromTempArchive.isFileSystem(), "Temporary archive {} shall be saved in filesystem", fromTempArchive); archive.setIsFileSystem(fromTempArchive.isFileSystem()); archive.setBinaryData(fromTempArchive.getBinaryData()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\RemoteArchiveStorage.java
1
请完成以下Java代码
public class ExportPPOrderRouteContext { @NonNull private final JsonExternalSystemRequest jsonExternalSystemRequest; @NonNull private final Integer ppOrderMetasfreshId; @NonNull private final DestinationDetails destinationDetails; @NonNull private final String pluTemplateFileBaseFolderName; private final boolean pluFileExportAuditEnabled; @Nullable private final String customQueryAdProcessValue; @NonNull private final JsonExternalSystemLeichMehlConfigProductMapping productMapping; @NonNull private final JsonExternalSystemLeichMehlPluFileConfigs pluFileConfigs; @Nullable @Getter(AccessLevel.NONE) private JsonResponseManufacturingOrder jsonResponseManufacturingOrder; @Nullable @Getter(AccessLevel.NONE) private JsonProduct jsonProduct; @Nullable private String customQueryProcessResponse; @Nullable @Getter(AccessLevel.NONE) private JsonPluFileAudit jsonPluFileAudit; @Nullable @Getter(AccessLevel.NONE) private String pluFileXmlContent; /** File of the PLU template file that was loaded from disk and who's XML was updated */ @Nullable @Getter(AccessLevel.NONE) private String pluTemplateFilename; @NonNull public JsonResponseManufacturingOrder getManufacturingOrderNonNull() { if (this.jsonResponseManufacturingOrder == null) { throw new RuntimeCamelException("JsonResponseManufacturingOrder cannot be null!"); } return this.jsonResponseManufacturingOrder; } @NonNull public JsonProduct getProductInfoNonNull() { if (this.jsonProduct == null) { throw new RuntimeCamelException("JsonProduct cannot be null!"); } return this.jsonProduct; } @NonNull public JsonPluFileAudit getJsonPluFileAuditNonNull() { if (this.jsonPluFileAudit == null) { throw new RuntimeCamelException("JsonPluFileAudit cannot be null!"); }
return this.jsonPluFileAudit; } @NonNull public String getUpdatedPLUFileContent() { if (this.pluFileXmlContent == null) { throw new RuntimeCamelException("pluFileXmlContent cannot be null!"); } return this.pluFileXmlContent; } @NonNull public String getPLUTemplateFilename() { if (this.pluTemplateFilename == null) { throw new RuntimeCamelException("filename cannot be null!"); } return this.pluTemplateFilename; } @NonNull public List<String> getPluFileConfigKeys() { return this.pluFileConfigs.getPluFileConfigs() .stream() .map(JsonExternalSystemLeichMehlPluFileConfig::getTargetFieldName) .collect(ImmutableList.toImmutableList()); } @Nullable public Integer getAdPInstance() { return JsonMetasfreshId.toValue(this.jsonExternalSystemRequest.getAdPInstanceId()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\pporder\ExportPPOrderRouteContext.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } } public static class WebClientConfiguration { //validity of the short-lived access token in secs (min: 60), don't make it too long private int accessTokenValidityInSeconds = 5 * 60; //validity of the refresh token in secs (defines the duration of "remember me") private int refreshTokenValidityInSecondsForRememberMe = 7 * 24 * 60 * 60; private String clientId = "web_app"; private String secret = "changeit"; public int getAccessTokenValidityInSeconds() { return accessTokenValidityInSeconds; }
public void setAccessTokenValidityInSeconds(int accessTokenValidityInSeconds) { this.accessTokenValidityInSeconds = accessTokenValidityInSeconds; } public int getRefreshTokenValidityInSecondsForRememberMe() { return refreshTokenValidityInSecondsForRememberMe; } public void setRefreshTokenValidityInSecondsForRememberMe(int refreshTokenValidityInSecondsForRememberMe) { this.refreshTokenValidityInSecondsForRememberMe = refreshTokenValidityInSecondsForRememberMe; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\uaa\src\main\java\com\baeldung\jhipster\uaa\config\UaaProperties.java
2
请完成以下Java代码
public class SignalEventHandler extends AbstractEventHandler { public static final String EVENT_HANDLER_TYPE = "signal"; @Override public String getEventHandlerType() { return EVENT_HANDLER_TYPE; } @Override public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, CommandContext commandContext) { if (eventSubscription.getExecutionId() != null) { super.handleEvent(eventSubscription, payload, commandContext); } else if (eventSubscription.getProcessDefinitionId() != null) { // Start event String processDefinitionId = eventSubscription.getProcessDefinitionId(); DeploymentManager deploymentCache = Context .getProcessEngineConfiguration() .getDeploymentManager(); ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) deploymentCache.findDeployedProcessDefinitionById(processDefinitionId); if (processDefinition == null) { throw new ActivitiObjectNotFoundException("No process definition found for id '" + processDefinitionId + "'", ProcessDefinition.class); } ActivityImpl startActivity = processDefinition.findActivity(eventSubscription.getActivityId());
if (startActivity == null) { throw new ActivitiException("Could no handle signal: no start activity found with id " + eventSubscription.getActivityId()); } ExecutionEntity processInstance = processDefinition.createProcessInstance(null, startActivity); if (processInstance == null) { throw new ActivitiException("Could not handle signal: no process instance started"); } if (payload != null) { if (payload instanceof Map) { Map<String, Object> variables = (Map<String, Object>) payload; processInstance.setVariables(variables); } } processInstance.start(); } else { throw new ActivitiException("Invalid signal handling: no execution nor process definition set"); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\event\SignalEventHandler.java
1
请完成以下Java代码
public class UserCredentials { private String username; private String password; private boolean rememberMe = false; public UserCredentials() {} 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 boolean isRememberMe() { return rememberMe; } public void setRememberMe(boolean rememberMe) { this.rememberMe = rememberMe; } @Override public String toString() { return "username = " + getUsername() + "\nrememberMe = " + isRememberMe(); } }
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\intro\models\UserCredentials.java
1
请在Spring Boot框架中完成以下Java代码
public class EffortControlQueueConfiguration implements IEventBusQueueConfiguration { public static final Topic EVENTBUS_TOPIC = Topic.distributed("de.metas.serviceprovider.eventbus.EffortControlEventRequest"); static final String QUEUE_NAME_SPEL = "#{metasfreshEffortControlQueue.name}"; private static final String QUEUE_BEAN_NAME = "metasfreshEffortControlQueue"; private static final String EXCHANGE_NAME_PREFIX = "metasfresh-effort-control-events"; @Value(RabbitMQEventBusConfiguration.APPLICATION_NAME_SPEL) private String appName; @Bean(QUEUE_BEAN_NAME) public AnonymousQueue effortControlQueue() { final NamingStrategy eventQueueNamingStrategy = new Base64UrlNamingStrategy(EVENTBUS_TOPIC.getName() + "." + appName + "-"); return new AnonymousQueue(eventQueueNamingStrategy); } @Bean public DirectExchange effortControlExchange() { return new DirectExchange(EXCHANGE_NAME_PREFIX); } @Bean public Binding effortControlBinding() { return BindingBuilder.bind(effortControlQueue())
.to(effortControlExchange()).with(EXCHANGE_NAME_PREFIX); } @Override public String getQueueName() { return effortControlQueue().getName(); } @Override public Optional<String> getTopicName() { return Optional.of(EVENTBUS_TOPIC.getName()); } @Override public String getExchangeName() { return effortControlExchange().getName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\queues\effort_control\EffortControlQueueConfiguration.java
2
请完成以下Java代码
public void setM_HU_PackagingCode(final de.metas.handlingunits.model.I_M_HU_PackagingCode M_HU_PackagingCode) { set_ValueFromPO(COLUMNNAME_M_HU_PackagingCode_ID, de.metas.handlingunits.model.I_M_HU_PackagingCode.class, M_HU_PackagingCode); } @Override public void setM_HU_PackagingCode_ID (final int M_HU_PackagingCode_ID) { if (M_HU_PackagingCode_ID < 1) set_Value (COLUMNNAME_M_HU_PackagingCode_ID, null); else set_Value (COLUMNNAME_M_HU_PackagingCode_ID, M_HU_PackagingCode_ID); } @Override public int getM_HU_PackagingCode_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID); } @Override public de.metas.handlingunits.model.I_M_HU_PI getM_HU_PI() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class); } @Override public void setM_HU_PI(final de.metas.handlingunits.model.I_M_HU_PI M_HU_PI) { set_ValueFromPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class, M_HU_PI); } @Override public void setM_HU_PI_ID (final int M_HU_PI_ID) { if (M_HU_PI_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); }
@Override public int getM_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID); } @Override public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID) { if (M_HU_PI_Version_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID); } @Override public int getM_HU_PI_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Version.java
1
请在Spring Boot框架中完成以下Java代码
public static String createLinkString(Map<String, String> params) { List<String> keys = new ArrayList<String>(params.keySet()); Collections.sort(keys); String prestr = ""; for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); String value = params.get(key); if (i == keys.size() - 1) {//拼接时,不包括最后一个&字符 prestr = prestr + key + "=" + value; } else { prestr = prestr + key + "=" + value + "&"; } } return prestr; } /** * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库) * @param sWord 要写入日志里的文本内容 */ public static void logResult(String sWord) { FileWriter writer = null; try { writer = new FileWriter(LOG_PATH + "alipay_log_" + System.currentTimeMillis()+".txt"); writer.write(sWord); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
} /** * 生成文件摘要 * @param strFilePath 文件路径 * @param file_digest_type 摘要算法 * @return 文件摘要结果 */ public static String getAbstract(String strFilePath, String file_digest_type) throws IOException { PartSource file = new FilePartSource(new File(strFilePath)); if(file_digest_type.equals("MD5")){ return DigestUtils.md5Hex(file.createInputStream()); } else if(file_digest_type.equals("SHA")) { return DigestUtils.sha256Hex(file.createInputStream()); } else { return ""; } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\AlipayCore.java
2
请在Spring Boot框架中完成以下Java代码
private void buildAndAttachContext(@NonNull final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); final String remoteUrl = request.getParameters().get(ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_HTTP_URL); if (Check.isBlank(remoteUrl)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_HTTP_URL); } final String authToken = request.getParameters().get(ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_AUTH_TOKEN); final ExportHURouteContext context = ExportHURouteContext.builder() .remoteUrl(remoteUrl) .authToken(authToken) .build(); exchange.setProperty(GRSSignumConstants.ROUTE_PROPERTY_EXPORT_HU_CONTEXT, context); } private void buildRetrieveHUCamelRequest(@NonNull final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
final String huIdentifier = request.getParameters().get(ExternalSystemConstants.PARAM_HU_ID); if (Check.isBlank(huIdentifier)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_HU_ID); } final JsonMetasfreshId externalSystemConfigId = request.getExternalSystemConfigId(); final JsonMetasfreshId adPInstanceId = request.getAdPInstanceId(); final RetrieveHUCamelRequest retrieveHUCamelRequest = RetrieveHUCamelRequest.builder() .huIdentifier(huIdentifier) .externalSystemConfigId(externalSystemConfigId) .adPInstanceId(adPInstanceId) .build(); exchange.getIn().setBody(retrieveHUCamelRequest); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\hu\GRSSignumExportHURouteBuilder.java
2
请在Spring Boot框架中完成以下Java代码
public DmnEngineConfigurator dmnEngineConfigurator(SpringDmnEngineConfiguration configuration) { SpringDmnEngineConfigurator dmnEngineConfigurator = new SpringDmnEngineConfigurator(); dmnEngineConfigurator.setDmnEngineConfiguration(configuration); invokeConfigurers(configuration); return dmnEngineConfigurator; } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(type = { "org.flowable.app.spring.SpringAppEngineConfiguration" }) public static class DmnEngineAppConfiguration extends BaseEngineConfigurationWithConfigurers<SpringDmnEngineConfiguration> { @Bean @ConditionalOnMissingBean(name = "dmnAppEngineConfigurationConfigurer") public EngineConfigurationConfigurer<SpringAppEngineConfiguration> dmnAppEngineConfigurationConfigurer( DmnEngineConfigurator dmnEngineConfigurator ) { return appEngineConfiguration -> appEngineConfiguration.addConfigurator(dmnEngineConfigurator);
} @Bean @ConditionalOnMissingBean public DmnEngineConfigurator dmnEngineConfigurator(SpringDmnEngineConfiguration configuration) { SpringDmnEngineConfigurator dmnEngineConfigurator = new SpringDmnEngineConfigurator(); dmnEngineConfigurator.setDmnEngineConfiguration(configuration); invokeConfigurers(configuration); return dmnEngineConfigurator; } } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\dmn\DmnEngineAutoConfiguration.java
2
请完成以下Java代码
public boolean isEnableSecureCookie() { return enableSecureCookie; } public void setEnableSecureCookie(boolean enableSecureCookie) { this.enableSecureCookie = enableSecureCookie; } public boolean isEnableSameSiteCookie() { return enableSameSiteCookie; } public void setEnableSameSiteCookie(boolean enableSameSiteCookie) { this.enableSameSiteCookie = enableSameSiteCookie; } public String getSameSiteCookieOption() { return sameSiteCookieOption; } public void setSameSiteCookieOption(String sameSiteCookieOption) { this.sameSiteCookieOption = sameSiteCookieOption; } public String getSameSiteCookieValue() { return sameSiteCookieValue; } public void setSameSiteCookieValue(String sameSiteCookieValue) { this.sameSiteCookieValue = sameSiteCookieValue; } public String getCookieName() { return cookieName; } public void setCookieName(String cookieName) { this.cookieName = cookieName; } public Map<String, String> getInitParams() { Map<String, String> initParams = new HashMap<>(); if (StringUtils.isNotBlank(targetOrigin)) { initParams.put("targetOrigin", targetOrigin); } if (denyStatus != null) { initParams.put("denyStatus", denyStatus.toString()); } if (StringUtils.isNotBlank(randomClass)) {
initParams.put("randomClass", randomClass); } if (!entryPoints.isEmpty()) { initParams.put("entryPoints", StringUtils.join(entryPoints, ",")); } if (enableSecureCookie) { // only add param if it's true; default is false initParams.put("enableSecureCookie", String.valueOf(enableSecureCookie)); } if (!enableSameSiteCookie) { // only add param if it's false; default is true initParams.put("enableSameSiteCookie", String.valueOf(enableSameSiteCookie)); } if (StringUtils.isNotBlank(sameSiteCookieOption)) { initParams.put("sameSiteCookieOption", sameSiteCookieOption); } if (StringUtils.isNotBlank(sameSiteCookieValue)) { initParams.put("sameSiteCookieValue", sameSiteCookieValue); } if (StringUtils.isNotBlank(cookieName)) { initParams.put("cookieName", cookieName); } return initParams; } @Override public String toString() { return joinOn(this.getClass()) .add("targetOrigin=" + targetOrigin) .add("denyStatus='" + denyStatus + '\'') .add("randomClass='" + randomClass + '\'') .add("entryPoints='" + entryPoints + '\'') .add("enableSecureCookie='" + enableSecureCookie + '\'') .add("enableSameSiteCookie='" + enableSameSiteCookie + '\'') .add("sameSiteCookieOption='" + sameSiteCookieOption + '\'') .add("sameSiteCookieValue='" + sameSiteCookieValue + '\'') .add("cookieName='" + cookieName + '\'') .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\CsrfProperties.java
1
请在Spring Boot框架中完成以下Java代码
public EmbeddingModel embeddingModel() { return OpenAiEmbeddingModel.builder() .apiKey(apiKey) .modelName(TEXT_EMBEDDING_3_SMALL) .build(); } @Bean public ContentRetriever contentRetriever(EmbeddingStore<TextSegment> embeddingStore, EmbeddingModel embeddingModel) { return EmbeddingStoreContentRetriever.builder() .embeddingStore(embeddingStore) .embeddingModel(embeddingModel) .maxResults(10) .minScore(0.8) .build(); } @Bean
public ChatLanguageModel chatModel() { return OpenAiChatModel.builder() .apiKey(apiKey) .modelName("gpt-4o-mini") .build(); } @Bean public ArticleBasedAssistant articleBasedAssistant(ChatLanguageModel chatModel, ContentRetriever contentRetriever) { return AiServices.builder(ArticleBasedAssistant.class) .chatLanguageModel(chatModel) .contentRetriever(contentRetriever) .build(); } }
repos\tutorials-master\libraries-llms-2\src\main\java\com\baeldung\chatbot\mongodb\configuration\ChatBotConfiguration.java
2
请完成以下Java代码
public static Builder with(OAuth2AuthorizationCodeRequestAuthenticationToken authentication) { return new Builder(authentication); } /** * A builder for {@link OAuth2AuthorizationCodeRequestAuthenticationContext}. */ public static final class Builder extends AbstractBuilder<OAuth2AuthorizationCodeRequestAuthenticationContext, Builder> { private Builder(OAuth2AuthorizationCodeRequestAuthenticationToken authentication) { super(authentication); } /** * Sets the {@link RegisteredClient registered client}. * @param registeredClient the {@link RegisteredClient} * @return the {@link Builder} for further configuration */ public Builder registeredClient(RegisteredClient registeredClient) { return put(RegisteredClient.class, registeredClient); } /** * Sets the {@link OAuth2AuthorizationRequest authorization request}. * @param authorizationRequest the {@link OAuth2AuthorizationRequest} * @return the {@link Builder} for further configuration */ public Builder authorizationRequest(OAuth2AuthorizationRequest authorizationRequest) { return put(OAuth2AuthorizationRequest.class, authorizationRequest); } /** * Sets the {@link OAuth2AuthorizationConsent authorization consent}. * @param authorizationConsent the {@link OAuth2AuthorizationConsent} * @return the {@link Builder} for further configuration */
public Builder authorizationConsent(OAuth2AuthorizationConsent authorizationConsent) { return put(OAuth2AuthorizationConsent.class, authorizationConsent); } /** * Builds a new {@link OAuth2AuthorizationCodeRequestAuthenticationContext}. * @return the {@link OAuth2AuthorizationCodeRequestAuthenticationContext} */ @Override public OAuth2AuthorizationCodeRequestAuthenticationContext build() { Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null"); return new OAuth2AuthorizationCodeRequestAuthenticationContext(getContext()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationCodeRequestAuthenticationContext.java
1
请完成以下Java代码
public class DiagnosticsRegistry { protected Map<String, CommandCounter> commands = new HashMap<>(); protected ApplicationServerImpl applicationServer; protected LicenseKeyDataImpl licenseKey; protected String camundaIntegration; protected Set<String> webapps = new HashSet<>(); public synchronized ApplicationServerImpl getApplicationServer() { if (applicationServer == null) { applicationServer = PlatformDiagnosticsRegistry.getApplicationServer(); } return applicationServer; } public synchronized void setApplicationServer(String applicationServerVersion) { this.applicationServer = new ApplicationServerImpl(applicationServerVersion); } public Map<String, CommandCounter> getCommands() { return commands; } public String getCamundaIntegration() { return camundaIntegration; } public void setCamundaIntegration(String camundaIntegration) { this.camundaIntegration = camundaIntegration; } public LicenseKeyDataImpl getLicenseKey() { return licenseKey; } public void setLicenseKey(LicenseKeyDataImpl licenseKey) { this.licenseKey = licenseKey; } public synchronized Set<String> getWebapps() { return webapps; } public synchronized void setWebapps(Set<String> webapps) { this.webapps = webapps; }
public void markOccurrence(String name) { markOccurrence(name, 1); } public void markOccurrence(String name, long times) { CommandCounter counter = commands.get(name); if (counter == null) { synchronized (commands) { if (counter == null) { counter = new CommandCounter(name); commands.put(name, counter); } } } counter.mark(times); } public synchronized void addWebapp(String webapp) { if (!webapps.contains(webapp)) { webapps.add(webapp); } } public void clearCommandCounts() { commands.clear(); } public void clear() { commands.clear(); licenseKey = null; applicationServer = null; webapps.clear(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\diagnostics\DiagnosticsRegistry.java
1
请完成以下Java代码
public static class Builder { private String firstName; private String lastName; private String email; private String username; private String password; private Collection<? extends GrantedAuthority> authorities; public Builder withFirstName(String firstName) { this.firstName = firstName; return this; } public Builder withLastName(String lastName) { this.lastName = lastName; return this; } public Builder withEmail(String email) { this.email = email; return this; }
public Builder withUsername(String username) { this.username = username; return this; } public Builder withPassword(String password) { this.password = password; return this; } public Builder withAuthorities(Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; return this; } public CustomUserDetails build() { return new CustomUserDetails(this); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-thymeleaf\src\main\java\com\baeldung\customuserdetails\CustomUserDetails.java
1
请在Spring Boot框架中完成以下Java代码
public class HDATE1 { @XmlElement(name = "DOCUMENTID", required = true) protected String documentid; @XmlElement(name = "DATEQUAL", required = true) protected String datequal; @XmlElement(name = "DATEFROM", required = true) protected String datefrom; @XmlElement(name = "DATETO") protected String dateto; @XmlElement(name = "DAYS") protected String days; /** * Gets the value of the documentid property. * * @return * possible object is * {@link String } * */ public String getDOCUMENTID() { return documentid; } /** * Sets the value of the documentid property. * * @param value * allowed object is * {@link String } * */ public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the datequal property. * * @return * possible object is * {@link String } * */ public String getDATEQUAL() { return datequal; } /** * Sets the value of the datequal property. * * @param value * allowed object is * {@link String } * */ public void setDATEQUAL(String value) { this.datequal = value; } /** * Gets the value of the datefrom property. * * @return * possible object is * {@link String } * */ public String getDATEFROM() { return datefrom;
} /** * Sets the value of the datefrom property. * * @param value * allowed object is * {@link String } * */ public void setDATEFROM(String value) { this.datefrom = value; } /** * Gets the value of the dateto property. * * @return * possible object is * {@link String } * */ public String getDATETO() { return dateto; } /** * Sets the value of the dateto property. * * @param value * allowed object is * {@link String } * */ public void setDATETO(String value) { this.dateto = value; } /** * Gets the value of the days property. * * @return * possible object is * {@link String } * */ public String getDAYS() { return days; } /** * Sets the value of the days property. * * @param value * allowed object is * {@link String } * */ public void setDAYS(String value) { this.days = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HDATE1.java
2
请在Spring Boot框架中完成以下Java代码
public Void packToGenericHU(final HuPackingInstructionsId genericPackingInstructionsId) { throw new AdempiereException(PACKING_TO_GENERIC_PACKING_ERROR_MSG) .appendParametersToMessage() .setParameter("GenericPackingInstructionsId", genericPackingInstructionsId); } }); InterfaceWrapperHelper.save(record); loader.addAlreadyLoadedFromDB(record); final PickingJobStepId pickingJobStepId = PickingJobStepId.ofRepoId(record.getM_Picking_Job_Step_ID()); step.getPickFromAlternatives() .forEach(pickFrom -> createStepHUAlternativeRecord( pickFrom, step.getProductId(), pickingJobStepId, pickingJobId, orgId)); } private void createStepHUAlternativeRecord( @NonNull final PickingJobCreateRepoRequest.StepPickFrom pickFrom, @NonNull final ProductId productId, @NonNull final PickingJobStepId pickingJobStepId, @NonNull final PickingJobId pickingJobId, @NonNull final OrgId orgId) { final I_M_Picking_Job_Step_HUAlternative record = InterfaceWrapperHelper.newInstance(I_M_Picking_Job_Step_HUAlternative.class); record.setM_Picking_Job_ID(pickingJobId.getRepoId()); record.setM_Picking_Job_Step_ID(pickingJobStepId.getRepoId()); record.setAD_Org_ID(orgId.getRepoId()); record.setM_Picking_Job_HUAlternative_ID(loader.getPickingJobHUAlternativeId(pickingJobId, pickFrom.getPickFromHUId(), productId).getRepoId()); record.setPickFrom_Warehouse_ID(pickFrom.getPickFromLocatorId().getWarehouseId().getRepoId()); record.setPickFrom_Locator_ID(pickFrom.getPickFromLocatorId().getRepoId()); record.setPickFrom_HU_ID(pickFrom.getPickFromHUId().getRepoId()); InterfaceWrapperHelper.save(record); loader.addAlreadyLoadedFromDB(record); }
private void createPickFromAlternative( @NonNull final PickFromAlternativeCreateRequest from, @NonNull final OrgId orgId) { final I_M_Picking_Job_HUAlternative record = InterfaceWrapperHelper.newInstance(I_M_Picking_Job_HUAlternative.class); record.setM_Picking_Job_ID(from.getPickingJobId().getRepoId()); record.setAD_Org_ID(orgId.getRepoId()); record.setPickFrom_Warehouse_ID(from.getPickFromLocatorId().getWarehouseId().getRepoId()); record.setPickFrom_Locator_ID(from.getPickFromLocatorId().getRepoId()); record.setPickFrom_HU_ID(from.getPickFromHUId().getRepoId()); record.setM_Product_ID(from.getProductId().getRepoId()); record.setC_UOM_ID(from.getQtyAvailable().getUomId().getRepoId()); record.setQtyAvailable(from.getQtyAvailable().toBigDecimal()); InterfaceWrapperHelper.save(record); loader.addAlreadyLoadedFromDB(record); PickingJobPickFromAlternativeId.ofRepoId(record.getM_Picking_Job_HUAlternative_ID()); } // // // @Value @Builder private static class PickFromAlternativeCreateRequest { @NonNull LocatorId pickFromLocatorId; @NonNull HuId pickFromHUId; @NonNull ProductId productId; @NonNull Quantity qtyAvailable; @NonNull PickingJobId pickingJobId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\PickingJobCreateRepoHelper.java
2
请完成以下Java代码
public class ProcessApplicationInfoImpl implements ProcessApplicationInfo { protected String name; protected List<ProcessApplicationDeploymentInfo> deploymentInfo; protected Map<String, String> properties; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<ProcessApplicationDeploymentInfo> getDeploymentInfo() {
return deploymentInfo; } public void setDeploymentInfo(List<ProcessApplicationDeploymentInfo> deploymentInfo) { this.deploymentInfo = deploymentInfo; } public Map<String, String> getProperties() { return properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\ProcessApplicationInfoImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean getDataSourceSafe() { return dataSourceSafe; } public void setDataSourceSafe(Boolean dataSourceSafe) { this.dataSourceSafe = dataSourceSafe; } public String getLowCodeMode() { return lowCodeMode; } public void setLowCodeMode(String lowCodeMode) { this.lowCodeMode = lowCodeMode; }
public Boolean getDisableSelectAll() { return disableSelectAll; } public void setDisableSelectAll(Boolean disableSelectAll) { this.disableSelectAll = disableSelectAll; } public Boolean getIsConcurrent() { return isConcurrent; } public void setIsConcurrent(Boolean isConcurrent) { this.isConcurrent = isConcurrent; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\vo\Firewall.java
2
请完成以下Java代码
protected void configureFactory(DocumentBuilderFactory dbf) { dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); ClassLoader classLoader = CmmnParser.class.getClassLoader(); dbf.setAttribute(JAXP_SCHEMA_SOURCE, new String[] { ReflectUtil.getResource(CMMN_10_SCHEMA_LOCATION, classLoader).toString(), ReflectUtil.getResource(CMMN_11_SCHEMA_LOCATION, classLoader).toString() } ); super.configureFactory(dbf); } @Override protected CmmnModelInstanceImpl createModelInstance(DomDocument document) { return new CmmnModelInstanceImpl((ModelImpl) Cmmn.INSTANCE.getCmmnModel(), Cmmn.INSTANCE.getCmmnModelBuilder(), document); }
@Override public CmmnModelInstanceImpl parseModelFromStream(InputStream inputStream) { try { return (CmmnModelInstanceImpl) super.parseModelFromStream(inputStream); } catch (ModelParseException e) { throw new CmmnModelException("Unable to parse model", e); } } @Override public CmmnModelInstanceImpl getEmptyModel() { return (CmmnModelInstanceImpl) super.getEmptyModel(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\CmmnParser.java
1
请在Spring Boot框架中完成以下Java代码
public void setC_TaxCategory_ID (final int C_TaxCategory_ID) { if (C_TaxCategory_ID < 1) set_Value (COLUMNNAME_C_TaxCategory_ID, null); else set_Value (COLUMNNAME_C_TaxCategory_ID, C_TaxCategory_ID); } @Override public int getC_TaxCategory_ID() { return get_ValueAsInt(COLUMNNAME_C_TaxCategory_ID); } @Override public void setC_Tax_ID (final int C_Tax_ID) { if (C_Tax_ID < 1) set_Value (COLUMNNAME_C_Tax_ID, null); else set_Value (COLUMNNAME_C_Tax_ID, C_Tax_ID); } @Override public int getC_Tax_ID() { return get_ValueAsInt(COLUMNNAME_C_Tax_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setExternalId (final java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @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 setPrice (final BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } @Override public BigDecimal getPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProductName (final java.lang.String ProductName) { set_Value (COLUMNNAME_ProductName, ProductName); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setScannedBarcode (final @Nullable java.lang.String ScannedBarcode) { set_Value (COLUMNNAME_ScannedBarcode, ScannedBarcode); } @Override public java.lang.String getScannedBarcode() { return get_ValueAsString(COLUMNNAME_ScannedBarcode); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_OrderLine.java
2
请完成以下Java代码
public int getExternalSystem_Config_ProCareManagement_LocalFile_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ProCareManagement_LocalFile_ID); } @Override public void setFrequency (final int Frequency) { set_Value (COLUMNNAME_Frequency, Frequency); } @Override public int getFrequency() { return get_ValueAsInt(COLUMNNAME_Frequency); } @Override public void setLocalRootLocation (final String LocalRootLocation) { set_Value (COLUMNNAME_LocalRootLocation, LocalRootLocation); } @Override public String getLocalRootLocation() { return get_ValueAsString(COLUMNNAME_LocalRootLocation); } @Override public void setProcessedDirectory (final String ProcessedDirectory) { set_Value (COLUMNNAME_ProcessedDirectory, ProcessedDirectory); } @Override public String getProcessedDirectory() { return get_ValueAsString(COLUMNNAME_ProcessedDirectory); } @Override public void setProductFileNamePattern (final @Nullable String ProductFileNamePattern) {
set_Value (COLUMNNAME_ProductFileNamePattern, ProductFileNamePattern); } @Override public String getProductFileNamePattern() { return get_ValueAsString(COLUMNNAME_ProductFileNamePattern); } @Override public void setPurchaseOrderFileNamePattern (final @Nullable String PurchaseOrderFileNamePattern) { set_Value (COLUMNNAME_PurchaseOrderFileNamePattern, PurchaseOrderFileNamePattern); } @Override public String getPurchaseOrderFileNamePattern() { return get_ValueAsString(COLUMNNAME_PurchaseOrderFileNamePattern); } @Override public void setWarehouseFileNamePattern (final @Nullable String WarehouseFileNamePattern) { set_Value (COLUMNNAME_WarehouseFileNamePattern, WarehouseFileNamePattern); } @Override public String getWarehouseFileNamePattern() { return get_ValueAsString(COLUMNNAME_WarehouseFileNamePattern); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ProCareManagement_LocalFile.java
1
请完成以下Java代码
public class SignatureCheckAspect { /** * 复用SignAuthInterceptor的签名验证逻辑 */ private final SignAuthInterceptor signAuthInterceptor = new SignAuthInterceptor(); /** * 验签切点:拦截所有标记了@SignatureCheck注解的方法 */ @Pointcut("@annotation(org.jeecg.config.sign.annotation.SignatureCheck)") private void signatureCheckPointCut() { } /** * 开始验签 */ @Before("signatureCheckPointCut()") public void doSignatureValidation(JoinPoint point) throws Exception { // 获取方法上的注解 MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); SignatureCheck signatureCheck = method.getAnnotation(SignatureCheck.class); log.info("AOP签名验证: {}.{}", method.getDeclaringClass().getSimpleName(), method.getName()); // 如果注解被禁用,直接返回 if (!signatureCheck.enabled()) { log.info("签名验证已禁用,跳过"); return; } ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes == null) { log.error("无法获取请求上下文"); throw new IllegalArgumentException("无法获取请求上下文"); } HttpServletRequest request = attributes.getRequest();
log.info("X-SIGN: {}, X-TIMESTAMP: {}", request.getHeader("X-SIGN"), request.getHeader("X-TIMESTAMP")); try { // 直接调用SignAuthInterceptor的验证逻辑 signAuthInterceptor.validateSignature(request); log.info("AOP签名验证通过"); } catch (IllegalArgumentException e) { // 使用注解中配置的错误消息,或者保留原始错误消息 String errorMessage = signatureCheck.errorMessage(); log.error("AOP签名验证失败: {}", e.getMessage()); if ("Sign签名校验失败!".equals(errorMessage)) { // 如果是默认错误消息,使用原始的详细错误信息 throw e; } else { // 如果是自定义错误消息,使用自定义消息 throw new IllegalArgumentException(errorMessage, e); } } catch (Exception e) { // 包装其他异常 String errorMessage = signatureCheck.errorMessage(); log.error("AOP签名验证异常: {}", e.getMessage()); throw new IllegalArgumentException(errorMessage, e); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\aspect\SignatureCheckAspect.java
1
请在Spring Boot框架中完成以下Java代码
public class ParentWithCascadeType { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST) private List<BidirectionalChildWithCascadeType> bidirectionalChildren; @OneToMany(cascade = CascadeType.PERSIST) @JoinColumn(name = "parent_id") private List<UnidirectionalChild> joinColumnUnidirectionalChildren; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public List<BidirectionalChildWithCascadeType> getChildren() { return bidirectionalChildren; }
public void setChildren(List<BidirectionalChildWithCascadeType> bidirectionalChildren) { this.bidirectionalChildren = bidirectionalChildren; } public void addChildren(List<BidirectionalChildWithCascadeType> bidirectionalChildren) { this.bidirectionalChildren = bidirectionalChildren; this.bidirectionalChildren.forEach(c -> c.setParent(this)); } public List<UnidirectionalChild> getJoinColumnUnidirectionalChildren() { return joinColumnUnidirectionalChildren; } public void setJoinColumnUnidirectionalChildren(List<UnidirectionalChild> joinColumnUnidirectionalChildren) { this.joinColumnUnidirectionalChildren = joinColumnUnidirectionalChildren; } }
repos\tutorials-master\persistence-modules\java-jpa-4\src\main\java\com\baeldung\jpa\savechildobjects\ParentWithCascadeType.java
2
请完成以下Java代码
public class CustomProperty extends BaseElement { protected String name; protected String simpleValue; protected ComplexDataType complexValue; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSimpleValue() { return simpleValue; } public void setSimpleValue(String simpleValue) { this.simpleValue = simpleValue; } public ComplexDataType getComplexValue() { return complexValue; }
public void setComplexValue(ComplexDataType complexValue) { this.complexValue = complexValue; } public CustomProperty clone() { CustomProperty clone = new CustomProperty(); clone.setValues(this); return clone; } public void setValues(CustomProperty otherProperty) { setName(otherProperty.getName()); setSimpleValue(otherProperty.getSimpleValue()); if (otherProperty.getComplexValue() != null && otherProperty.getComplexValue() instanceof DataGrid) { setComplexValue(((DataGrid) otherProperty.getComplexValue()).clone()); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\CustomProperty.java
1
请在Spring Boot框架中完成以下Java代码
public class SLSRPTExtensionType { @XmlElementRefs({ @XmlElementRef(name = "ReportingDate", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact", type = JAXBElement.class, required = false), @XmlElementRef(name = "ReportingPeriod", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact", type = JAXBElement.class, required = false), @XmlElementRef(name = "PointOfSales", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact", type = JAXBElement.class, required = false), @XmlElementRef(name = "SalesDate", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact", type = JAXBElement.class, required = false) }) protected List<JAXBElement<?>> reportingDateOrReportingPeriodAndPointOfSales; /** * Gets the value of the reportingDateOrReportingPeriodAndPointOfSales 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 reportingDateOrReportingPeriodAndPointOfSales property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReportingDateOrReportingPeriodAndPointOfSales().add(newItem); * </pre>
* * * <p> * Objects of the following type(s) are allowed in the list * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * {@link JAXBElement }{@code <}{@link PeriodType }{@code >} * {@link JAXBElement }{@code <}{@link String }{@code >} * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * * */ public List<JAXBElement<?>> getReportingDateOrReportingPeriodAndPointOfSales() { if (reportingDateOrReportingPeriodAndPointOfSales == null) { reportingDateOrReportingPeriodAndPointOfSales = new ArrayList<JAXBElement<?>>(); } return this.reportingDateOrReportingPeriodAndPointOfSales; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\SLSRPTExtensionType.java
2
请完成以下Java代码
public class VertragsdatenAbfragen { @XmlElement(namespace = "", required = true) protected String clientSoftwareKennung; @XmlElement(namespace = "") protected boolean manuelleAbfrage; /** * Gets the value of the clientSoftwareKennung property. * * @return * possible object is * {@link String } * */ public String getClientSoftwareKennung() { return clientSoftwareKennung; } /** * Sets the value of the clientSoftwareKennung property. * * @param value * allowed object is * {@link String } * */ public void setClientSoftwareKennung(String value) { this.clientSoftwareKennung = value;
} /** * Gets the value of the manuelleAbfrage property. * */ public boolean isManuelleAbfrage() { return manuelleAbfrage; } /** * Sets the value of the manuelleAbfrage property. * */ public void setManuelleAbfrage(boolean value) { this.manuelleAbfrage = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\VertragsdatenAbfragen.java
1
请在Spring Boot框架中完成以下Java代码
CassandraMappingContext cassandraMappingContext(CassandraManagedTypes cassandraManagedTypes, CassandraCustomConversions conversions) { CassandraMappingContext context = new CassandraMappingContext(); context.setManagedTypes(cassandraManagedTypes); context.setSimpleTypeHolder(conversions.getSimpleTypeHolder()); return context; } @Bean @ConditionalOnMissingBean CassandraConverter cassandraConverter(CassandraMappingContext mapping, CassandraCustomConversions conversions) { MappingCassandraConverter converter = new MappingCassandraConverter(mapping); converter.setCodecRegistry(() -> this.session.getContext().getCodecRegistry()); converter.setCustomConversions(conversions); converter.setUserTypeResolver(new SimpleUserTypeResolver(this.session)); return converter; } @Bean @ConditionalOnMissingBean(SessionFactory.class) SessionFactoryFactoryBean cassandraSessionFactory(Environment environment, CassandraConverter converter) { SessionFactoryFactoryBean session = new SessionFactoryFactoryBean(); session.setSession(this.session); session.setConverter(converter); Binder binder = Binder.get(environment);
binder.bind("spring.cassandra.schema-action", SchemaAction.class).ifBound(session::setSchemaAction); return session; } @Bean @ConditionalOnMissingBean(CqlOperations.class) CqlTemplate cqlTemplate(SessionFactory sessionFactory) { return new CqlTemplate(sessionFactory); } @Bean @ConditionalOnMissingBean(CassandraOperations.class) CassandraTemplate cassandraTemplate(CqlTemplate cqlTemplate, CassandraConverter converter) { return new CassandraTemplate(cqlTemplate, converter); } @Bean @ConditionalOnMissingBean CassandraCustomConversions cassandraCustomConversions() { return new CassandraCustomConversions(Collections.emptyList()); } }
repos\spring-boot-4.0.1\module\spring-boot-data-cassandra\src\main\java\org\springframework\boot\data\cassandra\autoconfigure\DataCassandraAutoConfiguration.java
2
请完成以下Java代码
private static List<String> readSqlList(File sqlFile) { List<String> sqlList = new ArrayList<>(); StringBuilder sb = new StringBuilder(); try (BufferedReader reader = Files.newBufferedReader(sqlFile.toPath(), StandardCharsets.UTF_8)) { String line; while ((line = reader.readLine()) != null) { log.info("line: {}", line); sb.append(line.trim()); if (line.trim().endsWith(";")) { sqlList.add(sb.toString()); // 清空 StringBuilder sb.setLength(0); } else { // 在行之间加一个空格 sb.append(" "); } } if (sb.length() > 0) { sqlList.add(sb.toString().trim()); } } catch (Exception e) { log.error("读取SQL文件时发生异常: {}", e.getMessage()); } return sqlList; } /** * 去除不安全的参数 * @param jdbcUrl /
* @return / */ private static String sanitizeJdbcUrl(String jdbcUrl) { // 定义不安全参数和其安全替代值 String[][] unsafeParams = { // allowLoadLocalInfile:允许使用 LOAD DATA LOCAL INFILE,可能导致文件泄露 {"allowLoadLocalInfile", "false"}, // allowUrlInLocalInfile:允许在 LOAD DATA LOCAL INFILE 中使用 URL,可能导致未经授权的文件访问 {"allowUrlInLocalInfile", "false"}, // autoDeserialize:允许自动反序列化对象,可能导致反序列化漏洞 {"autoDeserialize", "false"}, // allowNanAndInf:允许使用 NaN 和 Infinity 作为数字值,可能导致不一致的数据处理 {"allowNanAndInf", "false"}, // allowMultiQueries:允许在一个语句中执行多个查询,可能导致 SQL 注入攻击 {"allowMultiQueries", "false"}, // allowPublicKeyRetrieval:允许从服务器检索公钥,可能导致中间人攻击 {"allowPublicKeyRetrieval", "false"} }; // 替换不安全的参数 for (String[] param : unsafeParams) { jdbcUrl = jdbcUrl.replaceAll("(?i)" + param[0] + "=true", param[0] + "=" + param[1]); } return jdbcUrl; } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\util\SqlUtils.java
1
请完成以下Java代码
public I_M_Product getProductByResourceId(@NonNull final ResourceId resourceId) { final IProductDAO productsRepo = Services.get(IProductDAO.class); final ProductId productId = productsRepo.getProductIdByResourceId(resourceId); return productsRepo.getById(productId); } @Override public ProductId getProductIdByResourceId(final ResourceId resourceId) { final IProductDAO productsRepo = Services.get(IProductDAO.class); return productsRepo.getProductIdByResourceId(resourceId); }
@Override public TemporalUnit getResourceTemporalUnit(final ResourceId resourceId) { final ProductId resourceProductId = getProductIdByResourceId(resourceId); final I_C_UOM uom = Services.get(IProductBL.class).getStockUOM(resourceProductId); return UOMUtil.toTemporalUnit(uom); } @Override public I_C_UOM getResoureUOM(final ResourceId resourceId) { final I_M_Product product = Services.get(IResourceProductService.class).getProductByResourceId(resourceId); return Services.get(IProductBL.class).getStockUOM(product); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\impl\ResourceProductService.java
1
请完成以下Java代码
public class SpringTransactionInterceptor extends CommandInterceptor { protected PlatformTransactionManager transactionManager; protected int transactionPropagation; protected ProcessEngineConfigurationImpl processEngineConfiguration; /** * @deprecated use the {@link #SpringTransactionInterceptor(PlatformTransactionManager, int, ProcessEngineConfigurationImpl)} * constructor to ensure that concurrency conflicts that occur on * transaction commit are detected and handled in all cases */ @Deprecated public SpringTransactionInterceptor(PlatformTransactionManager transactionManager, int transactionPropagation) { this(transactionManager, transactionPropagation, null); } public SpringTransactionInterceptor(PlatformTransactionManager transactionManager, int transactionPropagation, ProcessEngineConfigurationImpl processEngineConfiguration) { this.transactionManager = transactionManager; this.transactionPropagation = transactionPropagation;
this.processEngineConfiguration = processEngineConfiguration; } @SuppressWarnings("unchecked") public <T> T execute(final Command<T> command) { TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.setPropagationBehavior(transactionPropagation); try { // don't use lambdas here => CAM-12810 return (T) transactionTemplate.execute((TransactionCallback) status -> next.execute(command)); } catch (TransactionSystemException ex) { throw ExceptionUtil.wrapPersistenceException(ex); } } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringTransactionInterceptor.java
1
请完成以下Java代码
private PPOrderLine toPPOrderLine( @NonNull final I_PP_Order_BOMLine ppOrderLineRecord, @NonNull final I_PP_Order ppOrderRecord) { final BOMComponentType componentType = BOMComponentType.ofCode(ppOrderLineRecord.getComponentType()); final boolean receipt = componentType.isReceipt(); final Instant issueOrReceiveDate = asInstant(receipt ? ppOrderRecord.getDatePromised() : ppOrderRecord.getDateStartSchedule()); final ProductId lineProductId = ProductId.ofRepoId(ppOrderLineRecord.getM_Product_ID()); final OrderBOMLineQuantities bomLineQuantities = ppOrderBOMBL.getQuantities(ppOrderLineRecord); final Quantity qtyRequiredInStockingUOM = uomConversionBL.convertToProductUOM(bomLineQuantities.getQtyRequired(), lineProductId); final Quantity qtyDeliveredInStockingUOM = uomConversionBL.convertToProductUOM(bomLineQuantities.getQtyIssuedOrReceived(), lineProductId); final WarehouseId warehouseId = WarehouseId.ofRepoId(ppOrderRecord.getM_Warehouse_ID()); final ReplenishInfo replenishInfo = replenishInfoRepository.getBy(ReplenishInfo.Identifier.of( warehouseId, // both from-warehouse and product are mandatory DB-columns LocatorId.ofRepoIdOrNull(warehouseId, ppOrderLineRecord.getM_Locator_ID()), ProductId.ofRepoId(ppOrderLineRecord.getM_Product_ID()))); return PPOrderLine.builder() .ppOrderLineData(PPOrderLineData.builder() .productDescriptor(productDescriptorFactory.createProductDescriptor(ppOrderLineRecord)) .description(ppOrderLineRecord.getDescription()) .productBomLineId(ppOrderLineRecord.getPP_Product_BOMLine_ID()) .qtyRequired(qtyRequiredInStockingUOM.toBigDecimal()) .qtyDelivered(qtyDeliveredInStockingUOM.toBigDecimal()) .issueOrReceiveDate(issueOrReceiveDate) .receipt(receipt)
.minMaxDescriptor(replenishInfo.toMinMaxDescriptor()) .build()) .ppOrderLineId(ppOrderLineRecord.getPP_Order_BOMLine_ID()) .build(); } @VisibleForTesting public static MaterialDispoGroupId getMaterialDispoGroupIdOrNull(@NonNull final I_PP_Order ppOrderRecord) { return ATTR_PPORDER_REQUESTED_EVENT_GROUP_ID.getValue(ppOrderRecord); } public static void setMaterialDispoGroupId( @NonNull final I_PP_Order ppOrderRecord, @Nullable final MaterialDispoGroupId materialDispoGroupId) { ATTR_PPORDER_REQUESTED_EVENT_GROUP_ID.setValue(ppOrderRecord, materialDispoGroupId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\PPOrderPojoConverter.java
1
请完成以下Java代码
public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); } /** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */ public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null);
else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public class UnpackV2ResponseRouteBuilder extends EndpointRouteBuilder { public final static String UNPACK_V2_API_RESPONSE = "UnpackV2ApiResponse"; public final static String UNPACK_V2_API_RESPONSE_PROCESSOR_ID = "UnpackV2ApiResponse_Processor_id"; @Override public void configure() { //@formatter:off from(direct(UNPACK_V2_API_RESPONSE)) .routeId(UNPACK_V2_API_RESPONSE) .doTry() .unmarshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonApiResponse.class)) .process(UnpackV2ResponseRouteBuilder::extractResponseContent).id(UNPACK_V2_API_RESPONSE_PROCESSOR_ID) .marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), Object.class)) .doCatch(Throwable.class)
.log(LoggingLevel.DEBUG, "Failed to unpack V2 response! Assuming that is was not wrapped into "+JsonApiResponse.class.getName()+" to begin with.") .endDoTry(); //@formatter:on } private static void extractResponseContent(@NonNull final Exchange exchange) { final JsonApiResponse jsonApiResponse = exchange.getIn().getBody(JsonApiResponse.class); if (jsonApiResponse == null) { throw new RuntimeCamelException("Empty exchange body! No JsonApiResponse present!"); } exchange.getIn().setBody(jsonApiResponse.getEndpointResponse()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v2\UnpackV2ResponseRouteBuilder.java
2
请完成以下Java代码
public Source from(@NonNull String... keys) { String[] resolvedKeys = Arrays.stream(ArrayUtils.nullSafeArray(keys, String.class)) .filter(StringUtils::hasText) .collect(Collectors.toList()) .toArray(new String[0]); return new Source(resolvedKeys); } protected interface TriFunction<T, U, V, R> { R apply(T t, U u, V v); } public class Source { private final String[] keys; private Source(@NonNull String[] keys) { Assert.notNull(keys, "The String array of keys must not be null"); this.keys = keys; } public void to(String key) { to(key, v -> v); } public void to(@NonNull String key, @NonNull Function<String, Object> function) { String[] keys = this.keys; Assert.state(keys.length == 1, String.format("Source size [%d] cannot be transformed as one argument", keys.length)); Map<String, String> source = getSource(); if (Arrays.stream(keys).allMatch(source::containsKey)) { getTarget().put(key, function.apply(source.get(keys[0])));
} } public void to(String key, TriFunction<String, String, String, Object> function) { String[] keys = this.keys; Assert.state(keys.length == 3, String.format("Source size [%d] cannot be consumed as three arguments", keys.length)); Map<String, String> source = getSource(); if (Arrays.stream(keys).allMatch(source::containsKey)) { getTarget().put(key, function.apply(source.get(keys[0]), source.get(keys[1]), source.get(keys[2]))); } } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-cloud\src\main\java\org\springframework\geode\cloud\bindings\MapMapper.java
1
请在Spring Boot框架中完成以下Java代码
public Result<List<AppInfo>> queryAppInfos(HttpServletRequest request) { List<AppInfo> list = new ArrayList<>(appManagement.getBriefApps()); Collections.sort(list, Comparator.comparing(AppInfo::getApp)); return Result.ofSuccess(list); } @GetMapping(value = "/{app}/machines.json") public Result<List<MachineInfoVo>> getMachinesByApp(@PathVariable("app") String app) { AppInfo appInfo = appManagement.getDetailApp(app); if (appInfo == null) { return Result.ofSuccess(null); } List<MachineInfo> list = new ArrayList<>(appInfo.getMachines()); Collections.sort(list, Comparator.comparing(MachineInfo::getApp).thenComparing(MachineInfo::getIp).thenComparingInt(MachineInfo::getPort)); return Result.ofSuccess(MachineInfoVo.fromMachineInfoList(list)); }
@RequestMapping(value = "/{app}/machine/remove.json") public Result<String> removeMachineById( @PathVariable("app") String app, @RequestParam(name = "ip") String ip, @RequestParam(name = "port") int port) { AppInfo appInfo = appManagement.getDetailApp(app); if (appInfo == null) { return Result.ofSuccess(null); } if (appManagement.removeMachine(app, ip, port)) { return Result.ofSuccessMsg("success"); } else { return Result.ofFail(1, "remove failed"); } } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\AppController.java
2
请完成以下Java代码
public boolean checkEligibleAndLog( @NonNull final OLCand cand, @Nullable final AsyncBatchId asyncBatchId) { final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG); if (cand.isProcessed()) { loggable.addLog("Skipping processed C_OLCand: {}", cand); return false; } if (cand.isError()) { loggable.addLog("Skipping C_OLCand with errors: {}", cand); return false; } if (cand.getOrderLineGroup() != null && cand.getOrderLineGroup().isGroupingError()) { loggable.addLog("Skipping C_OLCand with grouping errors: {}", cand); return false; } final InputDataSourceId candDataDestinationId = InputDataSourceId.ofRepoIdOrNull(cand.getAD_DataDestination_ID()); if (!Objects.equals(candDataDestinationId, processorDataDestinationId)) { loggable.addLog("Skipping C_OLCand with AD_DataDestination_ID={} but {} was expected: {}", candDataDestinationId, processorDataDestinationId, cand); return false; } if (asyncBatchId != null && !cand.isAssignToBatch(asyncBatchId)) {
loggable.addLog("Skipping C_OLCand due to missing batch assignment: targetBatchId: {}, candidate: {}", asyncBatchId.getRepoId(), cand); return false; } return true; } @NonNull private Iterator<I_C_OLCand> getOrderedOLCandIterator(@NonNull final PInstanceId selection) { return queryBL.createQueryBuilder(I_C_OLCand.class) .setOnlySelection(selection) .orderBy(I_C_OLCand.COLUMNNAME_HeaderAggregationKey) .create() .iterate(I_C_OLCand.class); } @NonNull private static OLCand prepareOLCandBeforeProcessing(@NonNull final OLCand candidate, @NonNull final LocalDate defaultDateDoc) { if (candidate.getDateOrdered() == null) { candidate.setDateOrdered(defaultDateDoc); } return candidate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\source\OLCandProcessingHelper.java
1
请完成以下Java代码
public void removeAssignedServiceIdsByShipmentScheduleIds(@NonNull final Collection<ShipmentScheduleId> shipmentScheduleIds) { queryBL.createQueryBuilder(I_M_ShipmentSchedule_Carrier_Service.class) .addInArrayFilter(I_M_ShipmentSchedule_Carrier_Service.COLUMNNAME_M_ShipmentSchedule_ID, shipmentScheduleIds) .create() .delete(); } public ImmutableSetMultimap<ShipmentScheduleId, CarrierServiceId> getAssignedServiceIdsMapByShipmentScheduleIds(@NonNull final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) { return ImmutableSetMultimap.of(); } return queryBL.createQueryBuilder(I_M_ShipmentSchedule_Carrier_Service.class) .addInArrayFilter(I_M_ShipmentSchedule_Carrier_Service.COLUMNNAME_M_ShipmentSchedule_ID, shipmentScheduleIds) .create() .stream() .collect(ImmutableSetMultimap.toImmutableSetMultimap( s -> ShipmentScheduleId.ofRepoId(s.getM_ShipmentSchedule_ID()), s -> CarrierServiceId.ofRepoId(s.getCarrier_Service_ID()))); } public void assignServicesToShipmentSchedule(@NonNull final ShipmentScheduleId shipmentScheduleId, final @NonNull Set<CarrierServiceId> serviceIds) {
queryBL.createQueryBuilder(I_M_ShipmentSchedule_Carrier_Service.class) .addEqualsFilter(I_M_ShipmentSchedule_Carrier_Service.COLUMNNAME_M_ShipmentSchedule_ID, shipmentScheduleId) .create() .delete(); final ImmutableSet<I_M_ShipmentSchedule_Carrier_Service> assignedCarrierServices = serviceIds.stream() .map(serviceId -> { final I_M_ShipmentSchedule_Carrier_Service po = InterfaceWrapperHelper.newInstance(I_M_ShipmentSchedule_Carrier_Service.class); po.setM_ShipmentSchedule_ID(ShipmentScheduleId.toRepoId(shipmentScheduleId)); po.setCarrier_Service_ID(CarrierServiceId.toRepoId(serviceId)); return po; }) .collect(ImmutableSet.toImmutableSet()); InterfaceWrapperHelper.saveAll(assignedCarrierServices); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\ShipmentScheduleCarrierServiceRepository.java
1
请完成以下Java代码
protected IntegerStringExpression createSingleParamaterExpression(final ExpressionContext context, final String expressionStr, final CtxName parameter) { return new SingleParameterExpression(context, this, expressionStr, parameter); } @Override protected IntegerStringExpression createGeneralExpression(final ExpressionContext context, final String expressionStr, final List<Object> expressionChunks) { return new GeneralExpression(context, this, expressionStr, expressionChunks); } }); } private static final class IntegerValueConverter implements ValueConverter<Integer, IntegerStringExpression> { @Override public Integer convertFrom(final Object valueObj, final ExpressionContext context) { if (valueObj == null) { return null; } else if (valueObj instanceof Integer) { return (Integer)valueObj; } else { String valueStr = valueObj.toString(); if (valueStr == null) { return null; // shall not happen } valueStr = valueStr.trim(); return new Integer(valueStr); } } } private static final class NullExpression extends NullExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression { public NullExpression(final Compiler<Integer, IntegerStringExpression> compiler) { super(compiler); } }
private static final class ConstantExpression extends ConstantExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression { public ConstantExpression(final Compiler<Integer, IntegerStringExpression> compiler, final String expressionStr, final Integer constantValue) { super(ExpressionContext.EMPTY, compiler, expressionStr, constantValue); } } private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression { public SingleParameterExpression(final ExpressionContext context, final Compiler<Integer, IntegerStringExpression> compiler, final String expressionStr, final CtxName parameter) { super(context, compiler, expressionStr, parameter); } @Override protected Integer extractParameterValue(final Evaluatee ctx) { return parameter.getValueAsInteger(ctx); } } private static final class GeneralExpression extends GeneralExpressionTemplate<Integer, IntegerStringExpression>implements IntegerStringExpression { public GeneralExpression(final ExpressionContext context, final Compiler<Integer, IntegerStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks) { super(context, compiler, expressionStr, expressionChunks); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\IntegerStringExpressionSupport.java
1
请在Spring Boot框架中完成以下Java代码
class ConverterConfiguration { @Bean public CassandraCustomConversions customConversions() { List<Converter<?, ?>> converters = new ArrayList<>(); converters.add(new PersonWriteConverter()); converters.add(new PersonReadConverter()); converters.add(new CustomAddressbookReadConverter()); converters.add(CurrencyToStringConverter.INSTANCE); converters.add(StringToCurrencyConverter.INSTANCE); return new CassandraCustomConversions(converters); } /** * Write a {@link Contact} into its {@link String} representation. */ static class PersonWriteConverter implements Converter<Contact, String> { public String convert(Contact source) { try { return new ObjectMapper().writeValueAsString(source); } catch (IOException e) { throw new IllegalStateException(e); } } } /** * Read a {@link Contact} from its {@link String} representation. */ static class PersonReadConverter implements Converter<String, Contact> { public Contact convert(String source) { if (StringUtils.hasText(source)) { try { return new ObjectMapper().readValue(source, Contact.class);
} catch (IOException e) { throw new IllegalStateException(e); } } return null; } } /** * Perform custom mapping by reading a {@link Row} into a custom class. */ static class CustomAddressbookReadConverter implements Converter<Row, CustomAddressbook> { public CustomAddressbook convert(Row source) { return new CustomAddressbook(source.getString("id"), source.getString("me")); } } enum StringToCurrencyConverter implements Converter<String, Currency> { INSTANCE; @Override public Currency convert(String source) { return Currency.getInstance(source); } } enum CurrencyToStringConverter implements Converter<Currency, String> { INSTANCE; @Override public String convert(Currency source) { return source.getCurrencyCode(); } } }
repos\spring-data-examples-main\cassandra\example\src\main\java\example\springdata\cassandra\convert\ConverterConfiguration.java
2
请完成以下Java代码
public static void installAuthMplus(QueryWrapper<?> queryWrapper,Class<?> clazz) { //权限查询 Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap(); PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(clazz); for (String c : ruleMap.keySet()) { if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){ queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue()))); } } String name, column; for (int i = 0; i < origDescriptors.length; i++) { name = origDescriptors[i].getName(); if (judgedIsUselessField(name)) { continue; } column = ReflectHelper.getTableFieldName(clazz, name); if(column==null){ continue; } if(ruleMap.containsKey(name)) { addRuleToQueryWrapper(ruleMap.get(name), column, origDescriptors[i].getPropertyType(), queryWrapper); } } } /** * 转换sql中的系统变量 * @param sql * @return */ public static String convertSystemVariables(String sql){ return getSqlRuleValue(sql); } /**
* 获取系统数据库类型 */ private static String getDbType(){ return CommonUtils.getDatabaseType(); } /** * mysql 模糊查询之特殊字符下划线 (_、\) * * @param value: * @Return: java.lang.String */ private static String specialStrConvert(String value) { if (DataBaseConstant.DB_TYPE_MYSQL.equals(getDbType()) || DataBaseConstant.DB_TYPE_MARIADB.equals(getDbType())) { String[] specialStr = QueryGenerator.LIKE_MYSQL_SPECIAL_STRS.split(","); for (String str : specialStr) { if (value.indexOf(str) !=-1) { value = value.replace(str, "\\" + str); } } } return value; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\query\QueryGenerator.java
1
请在Spring Boot框架中完成以下Java代码
public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * The MIME type of the attachment. E.g., 'application/pdf' for PDF attachments. * * @return * possible object is * {@link String } * */ public String getMimeType() { return mimeType; } /** * Sets the value of the mimeType property. * * @param value * allowed object is * {@link String } * */ public void setMimeType(String value) { this.mimeType = value; } /** * The actual attachment data as base64-encoded String.
* * @return * possible object is * byte[] */ public byte[] getAttachmentData() { return attachmentData; } /** * Sets the value of the attachmentData property. * * @param value * allowed object is * byte[] */ public void setAttachmentData(byte[] value) { this.attachmentData = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\AttachmentType.java
2
请完成以下Java代码
public void setRating (int Rating) { set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating)); } /** Get Rating. @return Classification or Importance */ public int getRating () { Integer ii = (Integer)get_Value(COLUMNNAME_Rating); if (ii == null) return 0; return ii.intValue(); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message
*/ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Entry.java
1
请完成以下Java代码
public boolean hasTaskDueDateChanged() { return hasDateFieldChanged(TaskInfo::getDueDate); } public boolean hasTaskDescriptionChanged() { return hasStringFieldChanged(TaskInfo::getDescription); } public boolean hasTaskOwnerChanged() { return hasStringFieldChanged(TaskInfo::getOwner); } public boolean hasTaskPriorityChanged() { return hasIntegerFieldChanged(TaskInfo::getPriority); } public boolean hasTaskCategoryChanged() { return hasStringFieldChanged(TaskInfo::getCategory); } public boolean hasTaskFormKeyChanged() { return hasStringFieldChanged(TaskInfo::getFormKey); } public boolean hasTaskParentIdChanged() { return hasStringFieldChanged(TaskInfo::getParentTaskId); } private boolean hasStringFieldChanged(Function<TaskInfo, String> comparableTaskGetter) { if (originalTask != null && updatedTask != null) { return !StringUtils.equals( comparableTaskGetter.apply(originalTask), comparableTaskGetter.apply(updatedTask) ); } return false; } private boolean hasIntegerFieldChanged(Function<TaskInfo, Integer> comparableTaskGetter) { if (originalTask != null && updatedTask != null) { return !Objects.equals(comparableTaskGetter.apply(originalTask), comparableTaskGetter.apply(updatedTask)); } return false; } private boolean hasDateFieldChanged(Function<TaskInfo, Date> comparableTaskGetter) { if (originalTask != null && updatedTask != null) { Date originalDate = comparableTaskGetter.apply(originalTask); Date newDate = comparableTaskGetter.apply(updatedTask); return ( (originalDate == null && newDate != null) ||
(originalDate != null && newDate == null) || (originalDate != null && !originalDate.equals(newDate)) ); } return false; } private TaskInfo copyInformationFromTaskInfo(TaskInfo task) { if (task != null) { TaskEntityImpl duplicatedTask = new TaskEntityImpl(); duplicatedTask.setName(task.getName()); duplicatedTask.setDueDate(task.getDueDate()); duplicatedTask.setDescription(task.getDescription()); duplicatedTask.setId(task.getId()); duplicatedTask.setOwner(task.getOwner()); duplicatedTask.setPriority(task.getPriority()); duplicatedTask.setCategory(task.getCategory()); duplicatedTask.setFormKey(task.getFormKey()); duplicatedTask.setAssignee(task.getAssignee()); duplicatedTask.setTaskDefinitionKey(task.getTaskDefinitionKey()); duplicatedTask.setParentTaskId(task.getParentTaskId()); return duplicatedTask; } throw new IllegalArgumentException("task must be non-null"); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\task\TaskComparatorImpl.java
1
请完成以下Java代码
public void setDetails(byte[] details) { this.details = details; } public byte[] getDetails() { return this.details; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("IdentityLinkEntity[id=").append(id); sb.append(", type=").append(type); if (userId != null) { sb.append(", userId=").append(userId); } if (groupId != null) {
sb.append(", groupId=").append(groupId); } if (taskId != null) { sb.append(", taskId=").append(taskId); } if (processInstanceId != null) { sb.append(", processInstanceId=").append(processInstanceId); } if (processDefId != null) { sb.append(", processDefId=").append(processDefId); } if (details != null) { sb.append(", details=").append(new String(details)); } sb.append("]"); return sb.toString(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\IdentityLinkEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setTargetUnit(UnitType value) { this.targetUnit = value; } /** * Gets the value of the factor property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getFactor() { return factor; } /** * Sets the value of the factor property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setFactor(BigDecimal value) { this.factor = value; } /** * Gets the value of the baseUnitArticleNumber 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 baseUnitArticleNumber property. * * <p>
* For example, to add a new item, do as follows: * <pre> * getBaseUnitArticleNumber().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ArticleNumberExtType } * * */ public List<ArticleNumberExtType> getBaseUnitArticleNumber() { if (baseUnitArticleNumber == null) { baseUnitArticleNumber = new ArrayList<ArticleNumberExtType>(); } return this.baseUnitArticleNumber; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\UnitConversionType.java
2
请在Spring Boot框架中完成以下Java代码
public class X_MobileUI_MFG_Config extends org.compiere.model.PO implements I_MobileUI_MFG_Config, org.compiere.model.I_Persistent { private static final long serialVersionUID = 896845343L; /** Standard Constructor */ public X_MobileUI_MFG_Config (final Properties ctx, final int MobileUI_MFG_Config_ID, @Nullable final String trxName) { super (ctx, MobileUI_MFG_Config_ID, trxName); } /** Load Constructor */ public X_MobileUI_MFG_Config (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 setIsAllowIssuingAnyHU (final boolean IsAllowIssuingAnyHU) { set_Value (COLUMNNAME_IsAllowIssuingAnyHU, IsAllowIssuingAnyHU); } @Override public boolean isAllowIssuingAnyHU() { return get_ValueAsBoolean(COLUMNNAME_IsAllowIssuingAnyHU); } @Override public void setIsScanResourceRequired (final boolean IsScanResourceRequired) {
set_Value (COLUMNNAME_IsScanResourceRequired, IsScanResourceRequired); } @Override public boolean isScanResourceRequired() { return get_ValueAsBoolean(COLUMNNAME_IsScanResourceRequired); } @Override public void setMobileUI_MFG_Config_ID (final int MobileUI_MFG_Config_ID) { if (MobileUI_MFG_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_MFG_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_MFG_Config_ID, MobileUI_MFG_Config_ID); } @Override public int getMobileUI_MFG_Config_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_MFG_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_MFG_Config.java
2
请完成以下Java代码
public class Article { private String title; private String author; private String words; private String date; public Article(String title, String author, String words, String date) { super(); this.title = title; this.author = author; this.words = words; this.date = date; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; }
public String getWords() { return words; } public void setWords(String words) { this.words = words; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
repos\tutorials-master\web-modules\java-lite\src\main\java\app\models\Article.java
1
请完成以下Java代码
private void setDescription(String description) { fieldDescription.setText(description); } public java.awt.Component getComponent(int type) { if (type == PANELTYPE_Stock) return (java.awt.Component)warehouseTbl; else if (type == PANELTYPE_Description) return fieldDescription; else throw new IllegalArgumentException("Unknown panel type " + type); }
public int getM_Warehouse_ID() { if (warehouseTbl.getRowCount() <= 0) return -1; Integer id = warehouseTbl.getSelectedRowKey(); return id == null ? -1 : id; } @Override public void refresh(final int M_Product_ID, final int M_Warehouse_ID, final int M_AttributeSetInstance_ID, final int M_PriceList_Version_ID) { refresh(M_Product_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductStock.java
1
请完成以下Java代码
public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(this.daemon); // If there is no specified name for thread, it will auto detect using the invoker classname instead. // Notice that auto detect may cause some performance overhead String prefix = this.name; if (StringUtils.isBlank(prefix)) { prefix = getInvoker(2); } thread.setName(prefix + "-" + getSequence(prefix)); // no specified uncaughtExceptionHandler, just do logging. if (this.uncaughtExceptionHandler != null) { thread.setUncaughtExceptionHandler(this.uncaughtExceptionHandler); } else { thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { LOGGER.error("unhandled exception in thread: " + t.getId() + ":" + t.getName(), e); } }); } return thread; } /** * Get the method invoker's class name * * @param depth * @return */ private String getInvoker(int depth) { Exception e = new Exception(); StackTraceElement[] stes = e.getStackTrace(); if (stes.length > depth) { return ClassUtils.getShortClassName(stes[depth].getClassName()); } return getClass().getSimpleName(); } /** * Get sequence for different naming prefix * * @param invoker * @return
*/ private long getSequence(String invoker) { AtomicLong r = this.sequences.get(invoker); if (r == null) { r = new AtomicLong(0); AtomicLong previous = this.sequences.putIfAbsent(invoker, r); if (previous != null) { r = previous; } } return r.incrementAndGet(); } /** * Getters & Setters */ public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isDaemon() { return daemon; } public void setDaemon(boolean daemon) { this.daemon = daemon; } public UncaughtExceptionHandler getUncaughtExceptionHandler() { return uncaughtExceptionHandler; } public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) { this.uncaughtExceptionHandler = handler; } }
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\utils\NamingThreadFactory.java
1
请完成以下Java代码
protected final GenericPO newInstance() { return new GenericPO(tableName, getCtx(), ID_NewInstanceNoInit); } @Override public final PO copy() { final GenericPO po = (GenericPO)super.copy(); po.tableName = this.tableName; po.tableID = this.tableID; return po; } } // GenericPO /** * Wrapper class to workaround the limit of PO constructor that doesn't take a tableName or * tableID parameter. Note that in the generated class scenario ( X_ ), tableName and tableId * is generated as a static field. * * @author Low Heng Sin * */
final class PropertiesWrapper extends Properties { /** * */ private static final long serialVersionUID = 8887531951501323594L; protected Properties source; protected String tableName; PropertiesWrapper(Properties source, String tableName) { this.source = source; this.tableName = tableName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\GenericPO.java
1
请完成以下Java代码
public static String getValue(@NonNull final GetValueRequest request) { final COL col = extractCOL(request); if (col == null) { return null; } if (col.getData() == null) { return null; } return col.getData().getValue(); } @Nullable private static COL extractCOL(final @NonNull GetValueRequest request) { final ROW row = request.getRow(); final Map<String, Integer> fieldName2Index = request.getFieldName2Index(); final Integer index = fieldName2Index.get(request.getFieldName()); if (index == null || row.getCols() == null || row.getCols().isEmpty()) { return null; } return row.getCols().get(index); } public static ROW setValue(@NonNull final GetValueRequest request, @Nullable final String newValue) { final COL col = extractCOL(request); if (col == null)
{ throw new RuntimeException("Unable to find COL for request=" + request); } final Map<String, Integer> fieldName2Index = request.getFieldName2Index(); final Integer index = fieldName2Index.get(request.getFieldName()); final ROW rowToModify = request.getRow(); final ArrayList<COL> cols = new ArrayList<>(rowToModify.getCols()); cols.set(index, COL.of(newValue)); return rowToModify.toBuilder().clearCols().cols(cols).build(); } @Builder @Getter public static class GetValueRequest { @NonNull private final ROW row; @NonNull private final Map<String, Integer> fieldName2Index; @NonNull private final String fieldName; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-filemaker\src\main\java\de\metas\common\filemaker\FileMakerDataHelper.java
1
请完成以下Java代码
private void syncCollectedBPartnersIfRequired(@NonNull final Collection<BPartnerId> bPartnerIdList) { if (bPartnerIdList.isEmpty()) { Loggables.withLogger(logger, Level.DEBUG).addLog("BPartnerId list to sync empty! No action is performed!"); return; } if (!externalSystemConfigRepo.isAnyConfigActive(getExternalSystemType())) { Loggables.withLogger(logger, Level.DEBUG).addLog("No active config found for external system type: {}! No action is performed!", getExternalSystemType()); return; // nothing to do } for (final BPartnerId bPartnerId : bPartnerIdList) { final TableRecordReference bPartnerToExportRecordRef = TableRecordReference.of(I_C_BPartner.Table_Name, bPartnerId); exportToExternalSystemIfRequired(bPartnerToExportRecordRef, () -> getAdditionalExternalSystemConfigIds(bPartnerId)); }
} @NonNull protected Optional<Set<IExternalSystemChildConfigId>> getAdditionalExternalSystemConfigIds(@NonNull final BPartnerId bpartnerId) { return Optional.empty(); } @Override protected void runPreExportHook(final TableRecordReference recordReferenceToExport) {} protected abstract Map<String, String> buildParameters(@NonNull final IExternalSystemChildConfig childConfig, @NonNull final BPartnerId bPartnerId); protected abstract boolean isSyncBPartnerEnabled(@NonNull final IExternalSystemChildConfig childConfig); protected abstract String getExternalCommand(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\export\bpartner\ExportBPartnerToExternalSystem.java
1
请完成以下Java代码
public void setBinaryData (byte[] BinaryData) { set_ValueNoCheck (COLUMNNAME_BinaryData, BinaryData); } /** Get Binärwert. @return Binärer Wert */ @Override public byte[] getBinaryData () { return (byte[])get_Value(COLUMNNAME_BinaryData); } /** Set Content type. @param ContentType Content type */ @Override public void setContentType (java.lang.String ContentType) { set_Value (COLUMNNAME_ContentType, ContentType); } /** Get Content type. @return Content type */ @Override public java.lang.String getContentType () { return (java.lang.String)get_Value(COLUMNNAME_ContentType); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set File Name. @param FileName Name of the local file or URL */ @Override public void setFileName (java.lang.String FileName) { set_Value (COLUMNNAME_FileName, FileName); } /** Get File Name. @return Name of the local file or URL */ @Override public java.lang.String getFileName () { return (java.lang.String)get_Value(COLUMNNAME_FileName); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** * Type AD_Reference_ID=540751 * Reference name: AD_AttachmentEntry_Type */ public static final int TYPE_AD_Reference_ID=540751; /** Data = D */ public static final String TYPE_Data = "D"; /** URL = U */ public static final String TYPE_URL = "U"; /** Set Art. @param Type Art */ @Override public void setType (java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ @Override public void setURL (java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ @Override public java.lang.String getURL () { return (java.lang.String)get_Value(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AttachmentEntry_ReferencedRecord_v.java
1
请完成以下Java代码
private boolean createPaymentLine (int C_Payment_ID, int C_Currency_ID, BigDecimal PayAmt, BigDecimal OpenAmt, int C_BPartner_ID, int c_DunningLevel_ID) { MDunningRunEntry entry = null; try { entry = m_run.getEntry (C_BPartner_ID, p_C_Currency_ID, p_SalesRep_ID, c_DunningLevel_ID); } catch (BPartnerNoAddressException e) { MPayment payment = new MPayment(getCtx(), C_Payment_ID, null); String msg = "@Skip@ @C_Payment_ID@ " + payment.getDocumentInfo() + ", @C_BPartner_ID@ " + Services.get(IBPartnerBL.class).getBPartnerName(BPartnerId.ofRepoIdOrNull(C_BPartner_ID)) + " @No@ @IsActive@ @C_BPartner_Location_ID@"; final ProcessExecutionResult processResult = getResult(); processResult.addLog(processResult.getPinstanceId(), null, null, msg); return false; } if (entry.get_ID() == 0) if (!entry.save()) throw new IllegalStateException("Cannot save MDunningRunEntry"); // MDunningRunLine line = new MDunningRunLine (entry); line.setPayment(C_Payment_ID, C_Currency_ID, PayAmt, OpenAmt); if (!line.save())
throw new IllegalStateException("Cannot save MDunningRunLine"); return true; } // createPaymentLine private void addFees(MDunningLevel level) { MDunningRunEntry [] entries = m_run.getEntries (true); if (entries!=null && entries.length>0) { for (int i=0;i<entries.length;i++) { MDunningRunLine line = new MDunningRunLine (entries[i]); line.setFee (p_C_Currency_ID, level.getFeeAmt()); if (!line.save()) throw new IllegalStateException("Cannot save MDunningRunLine"); entries[i].setQty (entries[i].getQty ().subtract (new BigDecimal(1))); } } } } // DunningRunCreate
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\DunningRunCreate.java
1
请在Spring Boot框架中完成以下Java代码
public void setCurrentReplicationTrx(@NonNull final String currentTrxName) { this.currentReplicationTrxName = currentTrxName; } public void setCurrentReplicationTrxStatus(@NonNull final EcosioOrdersRouteContext.TrxImportStatus currentTrxStatus) { importedTrxName2TrxStatus.put(currentReplicationTrxName, currentTrxStatus); } @NonNull public Optional<NotifyReplicationTrxRequest> getStatusRequestFor(@NonNull final String trxName) { final Collection<TrxImportStatus> progress = importedTrxName2TrxStatus.get(trxName); if (Check.isEmpty(progress)) { return Optional.empty(); } final boolean allNotOk = progress.stream().noneMatch(EcosioOrdersRouteContext.TrxImportStatus::isOk); if (allNotOk) { //dev-note: no update is required when there is no C_OLCand imported in this replication trx return Optional.empty(); } final boolean allOk = progress.stream().allMatch(EcosioOrdersRouteContext.TrxImportStatus::isOk); if (allOk) { final NotifyReplicationTrxRequest finishedRequest = NotifyReplicationTrxRequest.finished() .clientValue(clientValue) .trxName(trxName) .build(); return Optional.ofNullable(finishedRequest); } return Optional.of(NotifyReplicationTrxRequest.error(getErrorMessage(progress)) .clientValue(clientValue) .trxName(trxName) .build()); } @NonNull
private static String getErrorMessage(@NonNull final Collection<TrxImportStatus> progress) { return progress.stream() .map(TrxImportStatus::getErrorMessage) .filter(Check::isNotBlank) .collect(Collectors.joining("\n")); } @Value @Builder public static class TrxImportStatus { boolean ok; @Nullable String errorMessage; @NonNull public static EcosioOrdersRouteContext.TrxImportStatus ok() { return TrxImportStatus.builder() .ok(true) .build(); } @NonNull public static EcosioOrdersRouteContext.TrxImportStatus error(@NonNull final String errorMessage) { return TrxImportStatus.builder() .ok(false) .errorMessage(errorMessage) .build(); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\ecosio\EcosioOrdersRouteContext.java
2
请完成以下Java代码
public Field<Integer> field1() { return Article.ARTICLE.ID; } @Override public Field<String> field2() { return Article.ARTICLE.TITLE; } @Override public Field<String> field3() { return Article.ARTICLE.DESCRIPTION; } @Override public Field<Integer> field4() { return Article.ARTICLE.AUTHOR_ID; } @Override public Integer component1() { return getId(); } @Override public String component2() { return getTitle(); } @Override public String component3() { return getDescription(); } @Override public Integer component4() { return getAuthorId(); } @Override public Integer value1() { return getId(); } @Override public String value2() { return getTitle(); } @Override public String value3() { return getDescription(); } @Override public Integer value4() { return getAuthorId(); } @Override public ArticleRecord value1(Integer value) { setId(value); return this; } @Override public ArticleRecord value2(String value) { setTitle(value); return this; } @Override public ArticleRecord value3(String value) { setDescription(value); return this; } @Override public ArticleRecord value4(Integer value) { setAuthorId(value);
return this; } @Override public ArticleRecord values(Integer value1, String value2, String value3, Integer value4) { value1(value1); value2(value2); value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached ArticleRecord */ public ArticleRecord() { super(Article.ARTICLE); } /** * Create a detached, initialised ArticleRecord */ public ArticleRecord(Integer id, String title, String description, Integer authorId) { super(Article.ARTICLE); set(0, id); set(1, title); set(2, description); set(3, authorId); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\ArticleRecord.java
1
请在Spring Boot框架中完成以下Java代码
public static class AddStepRequest { boolean isGeneratedOnFly; @NonNull PickingJobStepId newStepId; @NonNull PickingJobLineId lineId; @NonNull Quantity qtyToPick; @NonNull LocatorInfo pickFromLocator; @NonNull HUInfo pickFromHU; @NonNull PackToSpec packToSpec; } public PickingJob withNewStep(@NonNull final AddStepRequest request) { return withChangedLine(request.getLineId(), line -> line.withNewStep(request)); } @NonNull public ImmutableSet<ProductId> getProductIds() { return streamLines() .map(PickingJobLine::getProductId) .collect(ImmutableSet.toImmutableSet()); } @NonNull public ITranslatableString getSingleProductNameOrEmpty() { ProductId productId = null; ITranslatableString productName = TranslatableStrings.empty(); for (final PickingJobLine line : lines) { if (productId == null) { productId = line.getProductId(); } else if (!ProductId.equals(productId, line.getProductId())) { // found different products return TranslatableStrings.empty(); } productName = line.getProductName(); } return productName; } @Nullable public Quantity getSingleQtyToPickOrNull() { return extractQtyToPickOrNull(lines, PickingJobLine::getProductId, PickingJobLine::getQtyToPick); } @Nullable private static <T> Quantity extractQtyToPickOrNull( @NonNull final Collection<T> lines, @NonNull final Function<T, ProductId> extractProductId, @NonNull final Function<T, Quantity> extractQtyToPick) { ProductId productId = null; Quantity qtyToPick = null; for (final T line : lines) { final ProductId lineProductId = extractProductId.apply(line); if (productId == null) { productId = lineProductId; } else if (!ProductId.equals(productId, lineProductId)) { // found different products return null; } final Quantity lineQtyToPick = extractQtyToPick.apply(line); if (qtyToPick == null) { qtyToPick = lineQtyToPick; } else if (UomId.equals(qtyToPick.getUomId(), lineQtyToPick.getUomId()))
{ qtyToPick = qtyToPick.add(lineQtyToPick); } else { // found different UOMs return null; } } return qtyToPick; } @NonNull public ImmutableSet<HuId> getPickedHuIds(@Nullable final PickingJobLineId lineId) { return lineId != null ? getLineById(lineId).getPickedHUIds() : getAllPickedHuIds(); } public ImmutableSet<HuId> getAllPickedHuIds() { return streamLines() .map(PickingJobLine::getPickedHUIds) .flatMap(Set::stream) .collect(ImmutableSet.toImmutableSet()); } public ImmutableSet<PPOrderId> getManufacturingOrderIds() { return streamLines() .map(PickingJobLine::getPickFromManufacturingOrderId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJob.java
2
请在Spring Boot框架中完成以下Java代码
public class MainController { // The Environment object will be used to read parameters from the // application.properties configuration file @Autowired private Environment env; /** * Show the index page containing the form for uploading a file. */ @RequestMapping("/") public String index() { return "index.html"; } /** * POST /uploadFile -> receive and locally save a file. * * @param uploadfile The uploaded file as Multipart file parameter in the * HTTP request. The RequestParam name must be the same of the attribute * "name" in the input tag with type file. * * @return An http OK status in case of success, an http 4xx status in case * of errors. */ @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody public ResponseEntity<?> uploadFile( @RequestParam("uploadfile") MultipartFile uploadfile) { try { // Get the filename and build the local file path String filename = uploadfile.getOriginalFilename(); String directory = env.getProperty("netgloo.paths.uploadedFiles"); String filepath = Paths.get(directory, filename).toString(); // Save the file locally BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filepath))); stream.write(uploadfile.getBytes()); stream.close(); } catch (Exception e) { System.out.println(e.getMessage()); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(HttpStatus.OK); } // method uploadFile } // class MainController
repos\spring-boot-samples-master\spring-boot-file-upload-with-ajax\src\main\java\netgloo\controllers\MainController.java
2
请在Spring Boot框架中完成以下Java代码
public List<PmsMenu> getMenuByNameAndIsLeaf(Map<String, Object> map) { return pmsMenuDao.getMenuByNameAndIsLeaf(map); } /** * 根据菜单ID获取菜单. * * @param pid * @return */ public PmsMenu getById(Long pid) { return pmsMenuDao.getById(pid); } /** * 更新菜单. * * @param menu */ public void update(PmsMenu menu) { pmsMenuDao.update(menu);
} /** * 根据角色查找角色对应的菜单ID集 * * @param roleId * @return */ public String getMenuIdsByRoleId(Long roleId) { List<PmsMenuRole> menuList = pmsMenuRoleDao.listByRoleId(roleId); StringBuffer menuIds = new StringBuffer(""); if (menuList != null && !menuList.isEmpty()) { for (PmsMenuRole rm : menuList) { menuIds.append(rm.getMenuId()).append(","); } } return menuIds.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsMenuServiceImpl.java
2
请完成以下Java代码
public String getF_AUDITER() { return F_AUDITER; } public void setF_AUDITER(String f_AUDITER) { F_AUDITER = f_AUDITER; } public String getF_AUDITTIME() { return F_AUDITTIME; } public void setF_AUDITTIME(String f_AUDITTIME) { F_AUDITTIME = f_AUDITTIME; } public String getF_ISAUDIT() { return F_ISAUDIT; } public void setF_ISAUDIT(String f_ISAUDIT) { F_ISAUDIT = f_ISAUDIT; } public Timestamp getF_EDITTIME() { return F_EDITTIME; } public void setF_EDITTIME(Timestamp f_EDITTIME) { F_EDITTIME = f_EDITTIME; }
public Integer getF_PLATFORM_ID() { return F_PLATFORM_ID; } public void setF_PLATFORM_ID(Integer f_PLATFORM_ID) { F_PLATFORM_ID = f_PLATFORM_ID; } public String getF_ISPRINTBILL() { return F_ISPRINTBILL; } public void setF_ISPRINTBILL(String f_ISPRINTBILL) { F_ISPRINTBILL = f_ISPRINTBILL; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscExeOffice.java
1
请在Spring Boot框架中完成以下Java代码
public class RpUserBankAccount extends BaseEntity { /** 银行卡开户所在省 **/ private String province; /** 银行卡开户所在城市 **/ private String city; /** 银行卡开户所在区 **/ private String areas; /** 银行卡开户具体地址 **/ private String street; /** 银行卡开户名eg:张三 **/ private String bankAccountName; /** 银行卡卡号 **/ private String bankAccountNo; /** 银行卡类型 **/ private String bankAccountType; /** 证件类型 **/ private String cardType; /** 证件号码 **/ private String cardNo; /** 手机号码 **/ private String mobileNo; /** 银行名称 **/ private String bankName; /** 银行编号eg:ICBC **/ private String bankCode; /** 用户编号 **/ private String userNo; /** 是否默认 **/ private String isDefault; /** 银行卡开户所在省 **/ public String getProvince() { return province; } /** 银行卡开户所在省 **/ public void setProvince(String province) { this.province = province; } /** 银行卡开户所在城市 **/ public String getCity() { return city; } /** 银行卡开户所在城市 **/ public void setCity(String city) { this.city = city; } /** 银行卡开户所在区 **/ public String getAreas() { return areas; } /** 银行卡开户所在区 **/ public void setAreas(String areas) { this.areas = areas; } /** 银行卡开户具体地址 **/ public String getStreet() { return street; } /** 银行卡开户具体地址 **/ public void setStreet(String street) { this.street = street; } /** 银行卡开户名eg:张三 **/ public String getBankAccountName() { return bankAccountName; } /** 银行卡开户名eg:张三 **/ public void setBankAccountName(String bankAccountName) { this.bankAccountName = bankAccountName; } /** 银行卡卡号 **/ public String getBankAccountNo() { return bankAccountNo; } /** 银行卡卡号 **/ public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } /** 银行编号eg:ICBC **/ public String getBankCode() { return bankCode; } /** 银行编号eg:ICBC **/ public void setBankCode(String bankCode) {
this.bankCode = bankCode; } /** 银行卡类型 **/ public String getBankAccountType() { return bankAccountType; } /** 银行卡类型 **/ public void setBankAccountType(String bankAccountType) { this.bankAccountType = bankAccountType; } /** 证件类型 **/ public String getCardType() { return cardType; } /** 证件类型 **/ public void setCardType(String cardType) { this.cardType = cardType; } /** 证件号码 **/ public String getCardNo() { return cardNo; } /** 证件号码 **/ public void setCardNo(String cardNo) { this.cardNo = cardNo; } /** 手机号码 **/ public String getMobileNo() { return mobileNo; } /** 手机号码 **/ public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } /** 银行名称 **/ public String getBankName() { return bankName; } /** 银行名称 **/ public void setBankName(String bankName) { this.bankName = bankName; } /** 用户编号 **/ public String getUserNo() { return userNo; } /** 用户编号 **/ public void setUserNo(String userNo) { this.userNo = userNo; } /** 是否默认 **/ public String getIsDefault() { return isDefault; } /** 是否默认 **/ public void setIsDefault(String isDefault) { this.isDefault = isDefault; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserBankAccount.java
2
请完成以下Java代码
static byte[] convertLongToByteArrayUsingCommonsLang(long value) { byte[] bytes = new byte[Long.BYTES]; Conversion.longToByteArray(value, 0, bytes, 0, bytes.length); ArrayUtils.reverse(bytes); return bytes; } static float convertByteArrayToFloatUsingCommonsLang(byte[] bytes) { byte[] copyBytes = Arrays.copyOf(bytes, bytes.length); ArrayUtils.reverse(copyBytes); int intValue = Conversion.byteArrayToInt(copyBytes, 0, 0, 0, copyBytes.length); return Float.intBitsToFloat(intValue); } static byte[] convertFloatToByteArrayUsingCommonsLang(float value) { int intValue = Float.floatToIntBits(value); byte[] bytes = new byte[Float.BYTES]; Conversion.intToByteArray(intValue, 0, bytes, 0, bytes.length); ArrayUtils.reverse(bytes); return bytes;
} static double convertByteArrayToDoubleUsingCommonsLang(byte[] bytes) { byte[] copyBytes = Arrays.copyOf(bytes, bytes.length); ArrayUtils.reverse(copyBytes); long longValue = Conversion.byteArrayToLong(copyBytes, 0, 0, 0, copyBytes.length); return Double.longBitsToDouble(longValue); } static byte[] convertDoubleToByteArrayUsingCommonsLang(double value) { long longValue = Double.doubleToLongBits(value); byte[] bytes = new byte[Long.BYTES]; Conversion.longToByteArray(longValue, 0, bytes, 0, bytes.length); ArrayUtils.reverse(bytes); return bytes; } }
repos\tutorials-master\core-java-modules\core-java-arrays-convert\src\main\java\com\baeldung\array\conversions\ByteArrayToNumericRepresentation.java
1
请完成以下Java代码
public static final class ProjectDetails { private final @Nullable String group; private final @Nullable String artifact; private final @Nullable String name; private final @Nullable String version; private final @Nullable Instant time; private final @Nullable Map<String, String> additionalProperties; public ProjectDetails(@Nullable String group, @Nullable String artifact, @Nullable String version, @Nullable String name, @Nullable Instant time, @Nullable Map<String, String> additionalProperties) { this.group = group; this.artifact = artifact; this.name = name; this.version = version; this.time = time; validateAdditionalProperties(additionalProperties); this.additionalProperties = additionalProperties; } private static void validateAdditionalProperties(@Nullable Map<String, String> additionalProperties) { if (additionalProperties != null) { additionalProperties.forEach((name, value) -> { if (value == null) { throw new NullAdditionalPropertyValueException(name); } }); } } public @Nullable String getGroup() { return this.group; }
public @Nullable String getArtifact() { return this.artifact; } public @Nullable String getName() { return this.name; } public @Nullable String getVersion() { return this.version; } public @Nullable Instant getTime() { return this.time; } public @Nullable Map<String, String> getAdditionalProperties() { return this.additionalProperties; } } /** * Exception thrown when an additional property with a null value is encountered. */ public static class NullAdditionalPropertyValueException extends IllegalArgumentException { public NullAdditionalPropertyValueException(String name) { super("Additional property '" + name + "' is illegal as its value is null"); } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\BuildPropertiesWriter.java
1
请完成以下Java代码
public void setCtxColumnName(final String ctxColumnName) { assertNotBuilt(); this.ctxColumnName = ctxColumnName; } public void setDisplayType(final int displayType) { assertNotBuilt(); this.displayType = displayType; } public void addFilter(@NonNull final Collection<IValidationRule> validationRules, @Nullable LookupDescriptorProvider.LookupScope scope) { for (final IValidationRule valRule : CompositeValidationRule.unbox(validationRules)) { addFilter(SqlLookupFilter.of(valRule, scope)); }
} public void addFilter(@Nullable final IValidationRule validationRule, @Nullable LookupDescriptorProvider.LookupScope scope) { for (final IValidationRule valRule : CompositeValidationRule.unbox(validationRule)) { addFilter(SqlLookupFilter.of(valRule, scope)); } } private void addFilter(@NonNull final SqlLookupFilter filter) { assertNotBuilt(); filters.add(filter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\CompositeSqlLookupFilterBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class BatchConfiguration { @Value("${file.input}") private String fileInput; @Bean public VirtualThreadTaskExecutor taskExecutor() { return new VirtualThreadTaskExecutor("virtual-thread-executor"); } @Bean public FlatFileItemReader<Coffee> reader() { return new FlatFileItemReaderBuilder<Coffee>().name("coffeeItemReader") .resource(new ClassPathResource(fileInput)) .delimited() .names(new String[] { "brand", "origin", "characteristics" }) .fieldSetMapper(new BeanWrapperFieldSetMapper<Coffee>() {{ setTargetType(Coffee.class); }}) .build(); } @Bean public CoffeeItemProcessor processor() { return new CoffeeItemProcessor(); } @Bean public JdbcBatchItemWriter<Coffee> writer(DataSource dataSource) { return new JdbcBatchItemWriterBuilder<Coffee>().itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>()) .sql("INSERT INTO coffee (brand, origin, characteristics) VALUES (:brand, :origin, :characteristics)") .dataSource(dataSource) .build();
} @Bean public Job importUserJob(JobRepository jobRepository, JobCompletionNotificationListener listener, Step step1) { return new JobBuilder("importUserJob", jobRepository) .incrementer(new RunIdIncrementer()) .listener(listener) .flow(step1) .end() .build(); } @Bean public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, JdbcBatchItemWriter<Coffee> writer, VirtualThreadTaskExecutor taskExecutor) { return new StepBuilder("step1", jobRepository) .<Coffee, Coffee> chunk(10, transactionManager) .reader(reader()) .processor(processor()) .writer(writer) .taskExecutor(taskExecutor) .build(); } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\bootbatch\BatchConfiguration.java
2
请完成以下Java代码
public <T extends TypedValue> T getVariableTyped(String variableName, boolean deserializeObjectValues) { TypedValue typedValue = null; VariableValue variableValue = receivedVariableMap.get(variableName); if (variableValue != null) { typedValue = variableValue.getTypedValue(deserializeObjectValues); } return (T) typedValue; } public Map<String, String> getExtensionProperties() { return extensionProperties == null ? Collections.emptyMap() : extensionProperties; } public void setExtensionProperties(Map<String, String> extensionProperties) { this.extensionProperties = extensionProperties; } @JsonIgnore @Override public String getExtensionProperty(String propertyKey) { if(extensionProperties != null) { return extensionProperties.get(propertyKey); } return null; } @Override public String toString() { return "ExternalTaskImpl [" + "activityId=" + activityId + ", " + "activityInstanceId=" + activityInstanceId + ", "
+ "businessKey=" + businessKey + ", " + "errorDetails=" + errorDetails + ", " + "errorMessage=" + errorMessage + ", " + "executionId=" + executionId + ", " + "id=" + id + ", " + formatTimeField("lockExpirationTime", lockExpirationTime) + ", " + formatTimeField("createTime", createTime) + ", " + "priority=" + priority + ", " + "processDefinitionId=" + processDefinitionId + ", " + "processDefinitionKey=" + processDefinitionKey + ", " + "processDefinitionVersionTag=" + processDefinitionVersionTag + ", " + "processInstanceId=" + processInstanceId + ", " + "receivedVariableMap=" + receivedVariableMap + ", " + "retries=" + retries + ", " + "tenantId=" + tenantId + ", " + "topicName=" + topicName + ", " + "variables=" + variables + ", " + "workerId=" + workerId + "]"; } protected String formatTimeField(String timeField, Date time) { return timeField + "=" + (time == null ? null : DateFormat.getDateTimeInstance().format(time)); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\impl\ExternalTaskImpl.java
1
请完成以下Java代码
public static ILoggable nop() { return NullLoggable.instance; } public static boolean isNull(@Nullable final ILoggable loggable) { return NullLoggable.isNull(loggable); } /** * Create a new {@link ILoggable} instance that delegates {@link #addLog(String, Object...)} invocations to the thread-local instance and in addition logs to the given logger. */ public static ILoggable withLogger(@NonNull final Logger logger, @NonNull final Level level) { return new LoggableWithLogger(get(), logger, level); } @NonNull public static ILoggable withFallbackToLogger(@NonNull final Logger logger, @NonNull final Level level) { final ILoggable threadLocalLoggable = get(); if (NullLoggable.isNull(threadLocalLoggable)) { return new LoggableWithLogger(NullLoggable.instance, logger, level); } else { return threadLocalLoggable;
} } public static ILoggable withLogger(@NonNull final ILoggable loggable, @NonNull final Logger logger, @NonNull final Level level) { return new LoggableWithLogger(loggable, logger, level); } public static ILoggable withWarnLoggerToo(@NonNull final Logger logger) { return withLogger(logger, Level.WARN); } public static PlainStringLoggable newPlainStringLoggable() { return new PlainStringLoggable(); } public static ILoggable addLog(final String msg, final Object... msgParameters) { return get().addLog(msg, msgParameters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Loggables.java
1
请完成以下Java代码
public class SignalIconType extends IconType { @Override public String getFillValue() { return "none"; } @Override public String getStrokeValue() { return "#585858"; } @Override public String getDValue() { return " M7.7124971 20.247342 L22.333334 20.247342 L15.022915000000001 7.575951200000001 L7.7124971 20.247342 z"; } public void drawIcon( final int imageX, final int imageY, final int iconPadding, final ProcessDiagramSVGGraphics2D svgGenerator ) { Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG); gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 7) + "," + (imageY - 7) + ")"); Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG); pathTag.setAttributeNS(null, "d", this.getDValue()); pathTag.setAttributeNS(null, "style", this.getStyleValue()); pathTag.setAttributeNS(null, "fill", this.getFillValue()); pathTag.setAttributeNS(null, "stroke", this.getStrokeValue()); gTag.appendChild(pathTag); svgGenerator.getExtendDOMGroupManager().addElement(gTag); } @Override public String getAnchorValue() { return null; }
@Override public String getStyleValue() { return "fill:none;stroke-width:1.4;stroke-miterlimit:4;stroke-dasharray:none"; } @Override public Integer getWidth() { return 17; } @Override public Integer getHeight() { return 15; } @Override public String getStrokeWidth() { return null; } }
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\SignalIconType.java
1
请完成以下Java代码
public String getImei() { return imei; } public void setImei(String imei) { this.imei = imei; } public String getSn() { return sn; } public void setSn(String sn) { this.sn = sn; } public String getSeries() { return series; } public void setSeries(String series) { this.series = series; } public String getAndroidVersion() { return androidVersion; } public void setAndroidVersion(String androidVersion) { this.androidVersion = androidVersion; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; }
public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getTips() { return tips; } public void setTips(String tips) { this.tips = tips; } public String getApplicationId() { return applicationId; } public void setApplicationId(String applicationId) { this.applicationId = applicationId; } }
repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\model\PosParam.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_Activity_ID (final int C_Activity_ID) { if (C_Activity_ID < 1) set_Value (COLUMNNAME_C_Activity_ID, null); else set_Value (COLUMNNAME_C_Activity_ID, C_Activity_ID); } @Override public int getC_Activity_ID() { return get_ValueAsInt(COLUMNNAME_C_Activity_ID); } @Override public void setC_CompensationGroup_Schema_ID (final int C_CompensationGroup_Schema_ID) { if (C_CompensationGroup_Schema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CompensationGroup_Schema_ID, C_CompensationGroup_Schema_ID); } @Override public int getC_CompensationGroup_Schema_ID()
{ return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_Schema_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\de\metas\order\model\X_C_CompensationGroup_Schema.java
1
请在Spring Boot框架中完成以下Java代码
public String getGroupId() { return groupId; } @Override public void setGroupId(String groupId) { if (this.userId != null && groupId != null) { throw new FlowableException("Cannot assign a groupId to a task assignment that already has a userId"); } this.groupId = groupId; } @Override public String getTaskId() { return taskId; } @Override public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getScopeId() { return this.scopeId; } @Override public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public String getSubScopeId() { return subScopeId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public String getScopeType() { return this.scopeType; } @Override public void setScopeType(String scopeType) {
this.scopeType = scopeType; } @Override public String getScopeDefinitionId() { return this.scopeDefinitionId; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("IdentityLinkEntity[id=").append(id); sb.append(", type=").append(type); if (userId != null) { sb.append(", userId=").append(userId); } if (groupId != null) { sb.append(", groupId=").append(groupId); } if (taskId != null) { sb.append(", taskId=").append(taskId); } if (processInstanceId != null) { sb.append(", processInstanceId=").append(processInstanceId); } if (scopeId != null) { sb.append(", scopeId=").append(scopeId); } if (scopeType != null) { sb.append(", scopeType=").append(scopeType); } if (scopeDefinitionId != null) { sb.append(", scopeDefinitionId=").append(scopeDefinitionId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\HistoricIdentityLinkEntityImpl.java
2
请在Spring Boot框架中完成以下Java代码
public CacheControl toCacheControl() { if (Boolean.TRUE.equals(this.noStore)) { return CacheControl.noStore(); } if (Boolean.TRUE.equals(this.noCache)) { return CacheControl.noCache(); } if (this.maxAge != null) { return CacheControl.maxAge(this.maxAge.getSeconds(), TimeUnit.SECONDS); } return CacheControl.empty(); } } @Data public static class UiTheme { private Boolean backgroundEnabled = true; private Palette palette = new Palette(); private String color = "#14615A"; } /** * Color shades are based on Tailwind's color palettes: * <a href="https://tailwindcss.com/docs/customizing-colors">tailwindcss.com</a> * <p> * name shade number mainColorLighter 50 mainColorLight 300 mainColor 500 * mainColorDark 700 mainColorDarker 800 */ @Getter public static class Palette { private String shade50 = "#EEFCFA"; private String shade100 = "#D9F7F4"; private String shade200 = "#B7F0EA"; private String shade300 = "#91E8E0"; private String shade400 = "#6BE0D5"; private String shade500 = "#47D9CB"; private String shade600 = "#27BEAF"; private String shade700 = "#1E9084"; private String shade800 = "#14615A";
private String shade900 = "#0A2F2B"; public void set50(String shade50) { this.shade50 = shade50; } public void set100(String shade100) { this.shade100 = shade100; } public void set200(String shade200) { this.shade200 = shade200; } public void set300(String shade300) { this.shade300 = shade300; } public void set400(String shade400) { this.shade400 = shade400; } public void set500(String shade500) { this.shade500 = shade500; } public void set600(String shade600) { this.shade600 = shade600; } public void set700(String shade700) { this.shade700 = shade700; } public void set800(String shade800) { this.shade800 = shade800; } public void set900(String shade900) { this.shade900 = shade900; } } }
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\config\AdminServerUiProperties.java
2
请完成以下Java代码
private SecurityContext getContext() { ApplicationContext appContext = SecurityWebApplicationContextUtils .findRequiredWebApplicationContext(getServletContext()); String[] names = appContext.getBeanNamesForType(SecurityContextHolderStrategy.class); if (names.length == 1) { SecurityContextHolderStrategy strategy = appContext.getBean(SecurityContextHolderStrategy.class); return strategy.getContext(); } return SecurityContextHolder.getContext(); } @SuppressWarnings({ "unchecked", "rawtypes" }) private SecurityExpressionHandler<FilterInvocation> getExpressionHandler() throws IOException { ApplicationContext appContext = SecurityWebApplicationContextUtils .findRequiredWebApplicationContext(getServletContext()); Map<String, SecurityExpressionHandler> handlers = appContext.getBeansOfType(SecurityExpressionHandler.class); for (SecurityExpressionHandler handler : handlers.values()) { if (FilterInvocation.class .equals(GenericTypeResolver.resolveTypeArgument(handler.getClass(), SecurityExpressionHandler.class))) { return handler; } } throw new IOException("No visible WebSecurityExpressionHandler instance could be found in the application " + "context. There must be at least one in order to support expressions in JSP 'authorize' tags."); } private WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() throws IOException { WebInvocationPrivilegeEvaluator privEvaluatorFromRequest = (WebInvocationPrivilegeEvaluator) getRequest()
.getAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE); if (privEvaluatorFromRequest != null) { return privEvaluatorFromRequest; } ApplicationContext ctx = SecurityWebApplicationContextUtils .findRequiredWebApplicationContext(getServletContext()); Map<String, WebInvocationPrivilegeEvaluator> wipes = ctx.getBeansOfType(WebInvocationPrivilegeEvaluator.class); if (wipes.isEmpty()) { throw new IOException( "No visible WebInvocationPrivilegeEvaluator instance could be found in the application " + "context. There must be at least one in order to support the use of URL access checks in 'authorize' tags."); } return (WebInvocationPrivilegeEvaluator) wipes.values().toArray()[0]; } }
repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTag.java
1
请完成以下Java代码
public void voidReports(@NonNull final I_C_Order order) { final List<I_C_Order_MFGWarehouse_Report> reports = orderCheckupDAO.retrieveAllReports(order); for (final I_C_Order_MFGWarehouse_Report report : reports) { report.setIsActive(false); InterfaceWrapperHelper.save(report); } } @Override public int getNumberOfCopies(@NonNull final I_C_Printing_Queue queueItem, @NonNull final I_AD_Archive printOut) { final I_C_Order_MFGWarehouse_Report report = getReportOrNull(printOut); if (report != null && report.getDocumentType().equals(X_C_Order_MFGWarehouse_Report.DOCUMENTTYPE_Warehouse)) { return Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_ORDERCHECKUP_BARCOE_COPIES, 1, queueItem.getAD_Client_ID(), queueItem.getAD_Org_ID()); } return Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_ORDERCHECKUP_COPIES, 1, queueItem.getAD_Client_ID(), queueItem.getAD_Org_ID()); } @Override
public final I_C_Order_MFGWarehouse_Report getReportOrNull(@NonNull final I_AD_Archive printOut) { if (!tableDAO.isTableId(I_C_Order_MFGWarehouse_Report.Table_Name, printOut.getAD_Table_ID())) { return null; } final I_C_Order_MFGWarehouse_Report report = archiveDAO.retrieveReferencedModel(printOut, I_C_Order_MFGWarehouse_Report.class); if (report == null) { //noinspection ThrowableNotThrown new AdempiereException("No report was found for " + printOut) .throwIfDeveloperModeOrLogWarningElse(logger); } return report; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\ordercheckup\impl\OrderCheckupBL.java
1
请在Spring Boot框架中完成以下Java代码
public Saml2MetadataConfigurer<H> metadataResponseResolver(Saml2MetadataResponseResolver metadataResponseResolver) { Assert.notNull(metadataResponseResolver, "metadataResponseResolver cannot be null"); this.metadataResponseResolver = (registrations) -> metadataResponseResolver; return this; } public H and() { return getBuilder(); } @Override public void configure(H http) { Saml2MetadataResponseResolver metadataResponseResolver = createMetadataResponseResolver(http); http.addFilterBefore(new Saml2MetadataFilter(metadataResponseResolver), BasicAuthenticationFilter.class); } private Saml2MetadataResponseResolver createMetadataResponseResolver(H http) { if (this.metadataResponseResolver != null) { RelyingPartyRegistrationRepository registrations = getRelyingPartyRegistrationRepository(http); return this.metadataResponseResolver.apply(registrations); } Saml2MetadataResponseResolver metadataResponseResolver = getBeanOrNull(Saml2MetadataResponseResolver.class); if (metadataResponseResolver != null) { return metadataResponseResolver; } RelyingPartyRegistrationRepository registrations = getRelyingPartyRegistrationRepository(http); if (USE_OPENSAML_5) { return new RequestMatcherMetadataResponseResolver(registrations, new OpenSaml5MetadataResolver()); } throw new IllegalArgumentException(
"Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5"); } private RelyingPartyRegistrationRepository getRelyingPartyRegistrationRepository(H http) { Saml2LoginConfigurer<H> login = http.getConfigurer(Saml2LoginConfigurer.class); if (login != null) { return login.relyingPartyRegistrationRepository(http); } else { return getBeanOrNull(RelyingPartyRegistrationRepository.class); } } private <C> C getBeanOrNull(Class<C> clazz) { if (this.context == null) { return null; } return this.context.getBeanProvider(clazz).getIfAvailable(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\saml2\Saml2MetadataConfigurer.java
2
请完成以下Java代码
public void exportLog(HttpServletResponse response, SysLogQueryCriteria criteria) throws IOException { criteria.setLogType("INFO"); sysLogService.download(sysLogService.queryAll(criteria), response); } @Log("导出错误数据") @ApiOperation("导出错误数据") @GetMapping(value = "/error/download") @PreAuthorize("@el.check()") public void exportErrorLog(HttpServletResponse response, SysLogQueryCriteria criteria) throws IOException { criteria.setLogType("ERROR"); sysLogService.download(sysLogService.queryAll(criteria), response); } @GetMapping @ApiOperation("日志查询") @PreAuthorize("@el.check()") public ResponseEntity<Object> queryLog(SysLogQueryCriteria criteria, Pageable pageable){ criteria.setLogType("INFO"); return new ResponseEntity<>(sysLogService.queryAll(criteria,pageable), HttpStatus.OK); } @GetMapping(value = "/user") @ApiOperation("用户日志查询") public ResponseEntity<PageResult<SysLogSmallDto>> queryUserLog(SysLogQueryCriteria criteria, Pageable pageable){ criteria.setLogType("INFO"); criteria.setUsername(SecurityUtils.getCurrentUsername()); return new ResponseEntity<>(sysLogService.queryAllByUser(criteria,pageable), HttpStatus.OK); } @GetMapping(value = "/error") @ApiOperation("错误日志查询") @PreAuthorize("@el.check()") public ResponseEntity<Object> queryErrorLog(SysLogQueryCriteria criteria, Pageable pageable){ criteria.setLogType("ERROR"); return new ResponseEntity<>(sysLogService.queryAll(criteria,pageable), HttpStatus.OK); } @GetMapping(value = "/error/{id}") @ApiOperation("日志异常详情查询") @PreAuthorize("@el.check()") public ResponseEntity<Object> queryErrorLogDetail(@PathVariable Long id){ return new ResponseEntity<>(sysLogService.findByErrDetail(id), HttpStatus.OK);
} @DeleteMapping(value = "/del/error") @Log("删除所有ERROR日志") @ApiOperation("删除所有ERROR日志") @PreAuthorize("@el.check()") public ResponseEntity<Object> delAllErrorLog(){ sysLogService.delAllByError(); return new ResponseEntity<>(HttpStatus.OK); } @DeleteMapping(value = "/del/info") @Log("删除所有INFO日志") @ApiOperation("删除所有INFO日志") @PreAuthorize("@el.check()") public ResponseEntity<Object> delAllInfoLog(){ sysLogService.delAllByInfo(); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-logging\src\main\java\me\zhengjie\rest\SysLogController.java
1
请完成以下Java代码
public ProcessDefinitionBuilder initial() { processDefinition.setInitial(getActivity()); return this; } public ProcessDefinitionBuilder startTransition(String destinationActivityId) { return startTransition(destinationActivityId, null); } public ProcessDefinitionBuilder startTransition(String destinationActivityId, String transitionId) { if (destinationActivityId==null) { throw new PvmException("destinationActivityId is null"); } ActivityImpl activity = getActivity(); transition = activity.createOutgoingTransition(transitionId); unresolvedTransitions.add(new Object[]{transition, destinationActivityId}); processElement = transition; return this; } public ProcessDefinitionBuilder endTransition() { processElement = scopeStack.peek(); transition = null; return this; } public ProcessDefinitionBuilder transition(String destinationActivityId) { return transition(destinationActivityId, null); } public ProcessDefinitionBuilder transition(String destinationActivityId, String transitionId) { startTransition(destinationActivityId, transitionId); endTransition(); return this; } public ProcessDefinitionBuilder behavior(ActivityBehavior activityBehaviour) { getActivity().setActivityBehavior(activityBehaviour); return this; } public ProcessDefinitionBuilder property(String name, Object value) { processElement.setProperty(name, value); return this; } public PvmProcessDefinition buildProcessDefinition() { for (Object[] unresolvedTransition: unresolvedTransitions) { TransitionImpl transition = (TransitionImpl) unresolvedTransition[0]; String destinationActivityName = (String) unresolvedTransition[1]; ActivityImpl destination = processDefinition.findActivity(destinationActivityName); if (destination == null) { throw new RuntimeException("destination '"+destinationActivityName+"' not found. (referenced from transition in '"+transition.getSource().getId()+"')"); } transition.setDestination(destination); } return processDefinition;
} protected ActivityImpl getActivity() { return (ActivityImpl) scopeStack.peek(); } public ProcessDefinitionBuilder scope() { getActivity().setScope(true); return this; } public ProcessDefinitionBuilder executionListener(ExecutionListener executionListener) { if (transition!=null) { transition.addExecutionListener(executionListener); } else { throw new PvmException("not in a transition scope"); } return this; } public ProcessDefinitionBuilder executionListener(String eventName, ExecutionListener executionListener) { if (transition==null) { scopeStack.peek().addExecutionListener(eventName, executionListener); } else { transition.addExecutionListener(executionListener); } return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\ProcessDefinitionBuilder.java
1
请完成以下Java代码
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; } @Override public org.compiere.model.I_M_MovementLine getReversalLine() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_MovementLine.class); } @Override public void setReversalLine(org.compiere.model.I_M_MovementLine ReversalLine) { set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_MovementLine.class, ReversalLine); } /** Set Reversal Line. @param ReversalLine_ID Use to keep the reversal line ID for reversing costing purpose */ @Override public void setReversalLine_ID (int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID)); } /** Get Reversal Line. @return Use to keep the reversal line ID for reversing costing purpose */ @Override public int getReversalLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verworfene Menge. @param ScrappedQty The Quantity scrapped due to QA issues */ @Override public void setScrappedQty (java.math.BigDecimal ScrappedQty) { set_Value (COLUMNNAME_ScrappedQty, ScrappedQty); } /** Get Verworfene Menge. @return The Quantity scrapped due to QA issues */ @Override public java.math.BigDecimal getScrappedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty); if (bd == null) return Env.ZERO; return bd; } /** Set Zielmenge.
@param TargetQty Target Movement Quantity */ @Override public void setTargetQty (java.math.BigDecimal TargetQty) { set_Value (COLUMNNAME_TargetQty, TargetQty); } /** Get Zielmenge. @return Target Movement Quantity */ @Override public java.math.BigDecimal getTargetQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty); if (bd == null) return Env.ZERO; return bd; } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { throw new IllegalArgumentException ("Value is virtual column"); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementLine.java
1
请完成以下Java代码
public java.math.BigDecimal getOverUnderAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OverUnderAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Abschreibung Betrag. @param PaymentWriteOffAmt Abschreibung Betrag */ @Override public void setPaymentWriteOffAmt (java.math.BigDecimal PaymentWriteOffAmt) { set_Value (COLUMNNAME_PaymentWriteOffAmt, PaymentWriteOffAmt); } /** Get Abschreibung Betrag. @return Abschreibung Betrag */ @Override public java.math.BigDecimal getPaymentWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PaymentWriteOffAmt); if (bd == null) return BigDecimal.ZERO; return bd; } @Override public org.compiere.model.I_C_AllocationLine getReversalLine() { return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class); } @Override public void setReversalLine(org.compiere.model.I_C_AllocationLine ReversalLine) { set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class, ReversalLine); } /** Set Storno-Zeile. @param ReversalLine_ID Storno-Zeile */ @Override public void setReversalLine_ID (int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID)); } /** Get Storno-Zeile.
@return Storno-Zeile */ @Override public int getReversalLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Abschreiben. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) { set_ValueNoCheck (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Abschreiben. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AllocationLine.java
1
请完成以下Java代码
public int compare(VocabWord o1, VocabWord o2) { return o2.cn - o1.cn; } } void initUnigramTable(Corpus corpus) { final int vocabSize = corpus.getVocabSize(); final VocabWord[] vocab = corpus.getVocab(); long trainWordsPow = 0; double d1, power = 0.75; table = new int[TABLE_SIZE]; for (int i = 0; i < vocabSize; i++) { trainWordsPow += Math.pow(vocab[i].cn, power); } int i = 0; d1 = Math.pow(vocab[i].cn, power) / (double) trainWordsPow; for (int j = 0; j < TABLE_SIZE; j++) { table[j] = i; if ((double) j / (double) TABLE_SIZE > d1) { i++; d1 += Math.pow(vocab[i].cn, power) / (double) trainWordsPow; } if (i >= vocabSize) i = vocabSize - 1; } } void initNet(Corpus corpus) { final int layer1Size = config.getLayer1Size(); final int vocabSize = corpus.getVocabSize(); syn0 = posixMemAlign128(vocabSize * layer1Size); if (config.useHierarchicalSoftmax()) { syn1 = posixMemAlign128(vocabSize * layer1Size); for (int i = 0; i < vocabSize; i++) { for (int j = 0; j < layer1Size; j++) { syn1[i * layer1Size + j] = 0; } } } if (config.getNegative() > 0) { syn1neg = posixMemAlign128(vocabSize * layer1Size);
for (int i = 0; i < vocabSize; i++) { for (int j = 0; j < layer1Size; j++) { syn1neg[i * layer1Size + j] = 0; } } } long nextRandom = 1; for (int i = 0; i < vocabSize; i++) { for (int j = 0; j < layer1Size; j++) { nextRandom = nextRandom(nextRandom); syn0[i * layer1Size + j] = (((nextRandom & 0xFFFF) / (double) 65536) - 0.5) / layer1Size; } } corpus.createBinaryTree(); } static double[] posixMemAlign128(int size) { final int surplus = size % 128; if (surplus > 0) { int div = size / 128; return new double[(div + 1) * 128]; } return new double[size]; } static long nextRandom(long nextRandom) { return nextRandom * 25214903917L + 11; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Word2VecTraining.java
1
请完成以下Java代码
default Map<String, ?> asMap() { final Builder<String, Object> result = ImmutableMap.builder(); if (getCheck_NetAmtToInvoice() != null) { result.put(InvoicingParams.PARA_Check_NetAmtToInvoice, getCheck_NetAmtToInvoice()); // during enqueuing this result might be overwritten by a specific value } if (getDateAcct() != null) { result.put(InvoicingParams.PARA_DateAcct, getDateAcct()); } if (getDateInvoiced() != null) { result.put(InvoicingParams.PARA_DateInvoiced, getDateInvoiced());
} if (getPOReference() != null) { result.put(InvoicingParams.PARA_POReference, getPOReference()); } result.put(InvoicingParams.PARA_IgnoreInvoiceSchedule, isIgnoreInvoiceSchedule()); result.put(InvoicingParams.PARA_IsConsolidateApprovedICs, isConsolidateApprovedICs()); result.put(InvoicingParams.PARA_IsUpdateLocationAndContactForInvoice, isUpdateLocationAndContactForInvoice()); result.put(InvoicingParams.PARA_OnlyApprovedForInvoicing, isOnlyApprovedForInvoicing()); result.put(InvoicingParams.PARA_IsCompleteInvoices, isCompleteInvoices()); return result.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\IInvoicingParams.java
1
请完成以下Java代码
public class City { /** * 城市编号 */ private Long id; /** * 省份年龄 */ private Integer age; /** * 城市名称 */ private String cityName; public Long getId() { return id; } public void setId(Long id) {
this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } }
repos\springboot-learning-example-master\springboot-hbase\src\main\java\org\spring\springboot\domain\City.java
1
请在Spring Boot框架中完成以下Java代码
public ChannelInterceptor securityContextPropagationInterceptor() { return new SecurityContextPropagationChannelInterceptor(); } @Bean public ThreadPoolTaskExecutor executor() { ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); pool.setCorePoolSize(10); pool.setMaxPoolSize(10); pool.setWaitForTasksToCompleteOnShutdown(true); return pool; } public String getRoles() { SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(",")); } public String getUsername() { SecurityContext securityContext = SecurityContextHolder.getContext(); return securityContext.getAuthentication().getName(); } public Message<String> buildNewMessage(String content, Message<?> message) { DefaultMessageBuilderFactory builderFactory = new DefaultMessageBuilderFactory(); MessageBuilder<String> messageBuilder = builderFactory.withPayload(content); messageBuilder.copyHeaders(message.getHeaders()); return messageBuilder.build(); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\si\security\SecurityPubSubChannel.java
2
请完成以下Java代码
public String getList(UserParam userParam) { StringBuffer sql = new StringBuffer("select id, userName, passWord, user_sex as userSex, nick_name as nickName"); sql.append(" from users where 1=1 "); if (userParam != null) { if (StringUtils.isNotBlank(userParam.getUserName())) { sql.append(" and userName = #{userName}"); } if (StringUtils.isNotBlank(userParam.getUserSex())) { sql.append(" and user_sex = #{userSex}"); } } sql.append(" order by id desc"); sql.append(" limit " + userParam.getBeginLine() + "," + userParam.getPageSize()); log.info("getList sql is :" +sql.toString()); return sql.toString(); } public String getCount(UserParam userParam) {
String sql= new SQL(){{ SELECT("count(1)"); FROM("users"); if (StringUtils.isNotBlank(userParam.getUserName())) { WHERE("userName = #{userName}"); } if (StringUtils.isNotBlank(userParam.getUserSex())) { WHERE("user_sex = #{userSex}"); } //从这个toString可以看出,其内部使用高效的StringBuilder实现SQL拼接 }}.toString(); log.info("getCount sql is :" +sql); return sql; } }
repos\spring-boot-leaning-master\1.x\第07课:Spring Boot 集成 MyBatis\spring-boot-mybatis-annotation\src\main\java\com\neo\mapper\UserSql.java
1
请完成以下Java代码
private boolean isSubscriptionInvoiceCandidate(final I_C_Invoice_Candidate invoiceCandidate) { final int tableId = invoiceCandidate.getAD_Table_ID(); return getTableId(I_C_Flatrate_Term.class) == tableId; } public LocalDate retrieveContractEndDateForInvoiceIdOrNull(@NonNull final InvoiceId invoiceId) { final I_C_Invoice invoice = invoiceDAO.getByIdInTrx(invoiceId); final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(invoice.getAD_Org_ID())); final List<I_C_InvoiceLine> invoiceLines = invoiceDAO.retrieveLines(invoice); final List<I_C_Invoice_Candidate> allInvoiceCands = new ArrayList<>(); for (final I_C_InvoiceLine invoiceLine : invoiceLines) { final List<I_C_Invoice_Candidate> cands = invoiceCandDAO.retrieveIcForIl(invoiceLine); allInvoiceCands.addAll(cands); } final Optional<I_C_Flatrate_Term> latestTerm = allInvoiceCands.stream() .filter(this::isSubscriptionInvoiceCandidate) .map(I_C_Invoice_Candidate::getRecord_ID) .map(flatrateDAO::getById) .sorted((contract1, contract2) -> { final Timestamp contractEndDate1 = CoalesceUtil.coalesce(contract1.getMasterEndDate(), contract1.getEndDate()); final Timestamp contractEndDate2 = CoalesceUtil.coalesce(contract2.getMasterEndDate(), contract2.getEndDate()); if (contractEndDate1.after(contractEndDate2)) { return -1; }
return 1; }) .findFirst(); if (latestTerm == null) { return null; } return TimeUtil.asLocalDate( CoalesceUtil.coalesce(latestTerm.get().getMasterEndDate(), latestTerm.get().getEndDate()), timeZone); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\invoice\ContractInvoiceService.java
1
请完成以下Java代码
public int apply(int a, int b) { return a + b; } }, MULTIPLY { @Override public int apply(int a, int b) { return a * b; } }, SUBTRACT { @Override public int apply(int a, int b) { return a - b; } },
DIVIDE { @Override public int apply(int a, int b) { return a / b; } }, MODULO { @Override public int apply(int a, int b) { return a % b; } }; public abstract int apply(int a, int b); }
repos\tutorials-master\patterns-modules\design-patterns-creational\src\main\java\com\baeldung\reducingIfElse\Operator.java
1
请完成以下Java代码
public WindowManager getWindowManager() { return windowManager; } class InfoUpdater implements Runnable { boolean stop = false; @Override public void run() { final int sleep = Services.get(ISysConfigBL.class).getIntValue("MENU_INFOUPDATER_SLEEP_MS", 60000, Env.getAD_Client_ID(Env.getCtx())); while (stop == false) { updateInfo(); try { synchronized (this) { this.wait(sleep); } } catch (InterruptedException ire) { } } } } private static AdTreeId retrieveMenuTreeId(final Properties ctx) { final IUserRolePermissions userRolePermissions = Env.getUserRolePermissions(ctx); if (!userRolePermissions.hasPermission(IUserRolePermissions.PERMISSION_MenuAvailable)) { return null; } return userRolePermissions.getMenuInfo().getAdTreeId(); } public FormFrame startForm(final int AD_Form_ID) { // metas: tsa: begin: US831: Open one window per session per user (2010101810000044) final Properties ctx = Env.getCtx(); final I_AD_Form form = InterfaceWrapperHelper.create(ctx, AD_Form_ID, I_AD_Form.class, ITrx.TRXNAME_None); if (form == null) { ADialog.warn(0, null, "Error", msgBL.parseTranslation(ctx, "@NotFound@ @AD_Form_ID@")); return null; }
final WindowManager windowManager = getWindowManager(); // metas: tsa: end: US831: Open one window per session per user (2010101810000044) if (Ini.isPropertyBool(Ini.P_SINGLE_INSTANCE_PER_WINDOW) || form.isOneInstanceOnly()) // metas: tsa: us831 { final FormFrame ffExisting = windowManager.findForm(AD_Form_ID); if (ffExisting != null) { AEnv.showWindow(ffExisting); // metas: tsa: use this method because toFront() is not working when window is minimized // ff.toFront(); // metas: tsa: commented original code return ffExisting; } } final FormFrame ff = new FormFrame(); final boolean ok = ff.openForm(form); // metas: tsa: us831 if (!ok) { ff.dispose(); return null; } windowManager.add(ff); // Center the window ff.showFormWindow(); return ff; } // startForm } // AMenu
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AMenu.java
1
请完成以下Java代码
public class HandOverLocationAdapter implements IDocumentHandOverLocationAdapter, RecordBasedLocationAdapter<HandOverLocationAdapter> { private final I_C_OLCand delegate; @Getter @Setter private String handOverAddress; HandOverLocationAdapter(@NonNull final I_C_OLCand delegate) { this.delegate = delegate; } @Override public boolean isUseHandOver_Location() { return BPartnerLocationId.ofRepoIdOrNull(getHandOver_Partner_ID(), getHandOver_Location_ID()) != null; } @Override public int getHandOver_Partner_ID() { return delegate.getHandOver_Partner_ID(); } @Override public void setHandOver_Partner_ID(final int HandOver_Partner_ID) { delegate.setHandOver_Partner_ID(HandOver_Partner_ID); } @Override public int getHandOver_Location_ID() { return delegate.getHandOver_Location_ID(); } @Override public void setHandOver_Location_ID(final int HandOver_Location_ID) { delegate.setHandOver_Location_ID(HandOver_Location_ID); } @Override public int getHandOver_Location_Value_ID() { return delegate.getHandOver_Location_Value_ID(); } @Override public void setHandOver_Location_Value_ID(final int HandOver_Location_Value_ID) { delegate.setHandOver_Location_Value_ID(HandOver_Location_Value_ID); } @Override public int getHandOver_User_ID() { return delegate.getHandOver_User_ID(); } @Override public void setHandOver_User_ID(final int HandOver_User_ID) {
delegate.setHandOver_User_ID(HandOver_User_ID); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentHandOverLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentHandOverLocationAdapter.super.setRenderedAddress(from); } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public HandOverLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new HandOverLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_OLCand.class)); } @Override public I_C_OLCand getWrappedRecord() { return delegate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\HandOverLocationAdapter.java
1
请完成以下Java代码
protected List<EntityImpl> getListFromCache(CachedEntityMatcher<EntityImpl> entityMatcher, Object parameter) { Collection<CachedEntity> cachedObjects = getEntityCache().findInCacheAsCachedObjects(getManagedEntityClass()); DbSqlSession dbSqlSession = getDbSqlSession(); List<EntityImpl> result = new ArrayList<EntityImpl>(cachedObjects.size()); if (cachedObjects != null && entityMatcher != null) { for (CachedEntity cachedObject : cachedObjects) { EntityImpl cachedEntity = (EntityImpl) cachedObject.getEntity(); if ( entityMatcher.isRetained(null, cachedObjects, cachedEntity, parameter) && !dbSqlSession.isEntityToBeDeleted(cachedEntity) ) { result.add(cachedEntity); } } } if (getManagedEntitySubClasses() != null && entityMatcher != null) { for (Class<? extends EntityImpl> entitySubClass : getManagedEntitySubClasses()) { Collection<CachedEntity> subclassCachedObjects = getEntityCache().findInCacheAsCachedObjects( entitySubClass ); if (subclassCachedObjects != null) { for (CachedEntity subclassCachedObject : subclassCachedObjects) {
EntityImpl cachedSubclassEntity = (EntityImpl) subclassCachedObject.getEntity(); if ( entityMatcher.isRetained(null, cachedObjects, cachedSubclassEntity, parameter) && !dbSqlSession.isEntityToBeDeleted(cachedSubclassEntity) ) { result.add(cachedSubclassEntity); } } } } } return result; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\AbstractDataManager.java
1