javax.annotation.PostConstruct Java Examples

The following examples show how to use javax.annotation.PostConstruct. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Jexl3ConfigEnvironmentPreprocessor.java    From spring-cloud-formula with Apache License 2.0 7 votes vote down vote up
@PostConstruct
public void init() {
    jexlEngine = new JexlBuilder().create();
    // 支持的参数
    // 1. 启动参数
    // 2. 测试配置变量
    // 3. 系统属性
    PropertySource<?> ps = environment.getPropertySources().get("systemProperties");
    Map<Object, Object> source = (Map<Object, Object>) ps.getSource();
    source.forEach((key, value) -> {
        if (!jc.has(keyed((String) key))) {
            jc.set(keyed((String) key), value);
        }
    });

    // 4. 环境变量
    ps = environment.getPropertySources().get("systemEnvironment");
    source = (Map<Object, Object>) ps.getSource();
    source.forEach((key, value) -> {
        if (!jc.has(keyed((String) key))) {
            jc.set(keyed((String) key), value);
        }
    });
}
 
Example #2
Source File: MqCacheRebuildService.java    From pmq with Apache License 2.0 6 votes vote down vote up
@PostConstruct
private void init() {
	cacheCount = soaConfig.getCacheRebuild();
	soaConfig.registerChanged(new Runnable() {
		@Override
		public void run() {
			if (cacheCount != soaConfig.getCacheRebuild()) {
				cacheCount = soaConfig.getCacheRebuild();
				 Map<String, CacheUpdateService> cacheUpdateServices = SpringUtil.getBeans(CacheUpdateService.class);
		            if (cacheUpdateServices != null) {
		                cacheUpdateServices.values().forEach(t1 -> {
		                    t1.forceUpdateCache();
		                });
		            }
			}

		}
	});

}
 
Example #3
Source File: CachePushConfigVersionServiceImpl.java    From qconfig with MIT License 6 votes vote down vote up
@PostConstruct
public void init() {
    freshPushVersionCache();

    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            Thread.currentThread().setName("fresh-push-version-thread");
            try {
                freshPushVersionCache();
            } catch (Throwable e) {
                logger.error("fresh push version error", e);
            }
        }
    }, 3, 3, TimeUnit.MINUTES);
}
 
Example #4
Source File: RelatedProductsImpl.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
@PostConstruct
private void initModel() {
    if (!isConfigured()) {
        return;
    }

    magentoGraphqlClient = MagentoGraphqlClient.create(resource);
    productPage = SiteNavigation.getProductPage(currentPage);
    if (productPage == null) {
        productPage = currentPage;
    }

    locale = productPage.getLanguage(false);

    if (magentoGraphqlClient == null) {
        LOGGER.error("Cannot get a GraphqlClient using the resource at {}", resource.getPath());
    } else {
        configureProductsRetriever();
    }
}
 
Example #5
Source File: SearchResultsImpl.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
@PostConstruct
protected void initModel() {
    searchTerm = request.getParameter(SearchOptionsImpl.SEARCH_QUERY_PARAMETER_ID);

    // make sure the current page from the query string is reasonable i.e. numeric and over 0
    Integer currentPageIndex = calculateCurrentPageCursor(request.getParameter(SearchOptionsImpl.CURRENT_PAGE_PARAMETER_ID));

    Map<String, String> searchFilters = createFilterMap(request.getParameterMap());

    LOGGER.debug("Detected search parameter {}", searchTerm);

    searchOptions = new SearchOptionsImpl();
    searchOptions.setCurrentPage(currentPageIndex);
    searchOptions.setPageSize(navPageSize);
    searchOptions.setAttributeFilters(searchFilters);
    searchOptions.setSearchQuery(searchTerm);

    // configure sorting
    searchOptions.addSorterKey("relevance", "Relevance", Sorter.Order.DESC);
    searchOptions.addSorterKey("price", "Price", Sorter.Order.ASC);
    searchOptions.addSorterKey("name", "Product Name", Sorter.Order.ASC);
}
 
Example #6
Source File: MqRestStatController.java    From pmq with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void report() {
	// MetricSingleton.getMetricRegistry().register(MetricRegistry.name("app.Count"),
	// new Gauge<Long>() {
	// @Override
	// public Long getValue() {
	// return appService.getCount();
	// }
	// });
	// MetricSingleton.getMetricRegistry().register(MetricRegistry.name("app.ClusterCount"),
	// new Gauge<Long>() {
	// @Override
	// public Long getValue() {
	// return appClusterService.getClusterCount();
	// }
	// });
	// MetricSingleton.getMetricRegistry().register(MetricRegistry.name("app.InstanceCount"),
	// new Gauge<Long>() {
	// @Override
	// public Long getValue() {
	// return instanceService.getCount();
	// }
	// });
}
 
Example #7
Source File: ConfigPrinter.java    From Qualitis with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void printConfig() throws UnSupportConfigFileSuffixException {
    LOGGER.info("Start to print config");
    addPropertiesFile();
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    LOGGER.info("Prepared to print config in file: {}", propertiesFiles);

    for (String fileName : propertiesFiles) {
        LOGGER.info("======================== Config in {} ========================", fileName);
        PropertySourceLoader propertySourceLoader = getPropertySourceLoader(fileName);
        Resource resource = resourceLoader.getResource(fileName);
        try {
            List<PropertySource<?>> propertySources = propertySourceLoader.load(fileName, resource);
            for (PropertySource p : propertySources) {
                Map<String, Object> map = (Map<String, Object>) p.getSource();
                for (String key : map.keySet()) {
                    LOGGER.info("Name: [{}]=[{}]", key, map.get(key));
                }
            }
        } catch (IOException e) {
            LOGGER.info("Failed to open file: {}, caused by: {}, it does not matter", fileName, e.getMessage());
        }
        LOGGER.info("=======================================================================================\n");
    }
    LOGGER.info("Succeed to print all configs");
}
 
Example #8
Source File: OpendapServlet.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@PostConstruct
public void init() throws javax.servlet.ServletException {
  // super.init();

  logServerStartup.info(getClass().getName() + " initialization start");

  this.ascLimit = ThreddsConfig.getInt("Opendap.ascLimit", ascLimit); // LOOK how the hell can OpendapServlet call
                                                                      // something in the tds module ??
  this.binLimit = ThreddsConfig.getInt("Opendap.binLimit", binLimit);

  this.odapVersionString = ThreddsConfig.get("Opendap.serverVersion", odapVersionString);
  logServerStartup.info(getClass().getName() + " version= " + odapVersionString + " ascLimit = " + ascLimit
      + " binLimit = " + binLimit);

  if (tdsContext != null) // LOOK not set in mock testing enviro ?
  {
    setRootpath(tdsContext.getServletRootDirectory().getPath());
  }

  logServerStartup.info(getClass().getName() + " initialization done");
}
 
Example #9
Source File: TestProducer.java    From staccato with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    Map<String, Object> props = new HashMap<>();
    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, configProps.getBootstrapServers());
    props.put(ProducerConfig.ACKS_CONFIG, "all");
    props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
    props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    SenderOptions<Integer, String> senderOptions = SenderOptions.create(props);

    sender = KafkaSender.create(senderOptions);
}
 
Example #10
Source File: FileStorageService.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
@PostConstruct
public void start()
{
    deleteStagingFilesAsync();
    createParents(new File(baseStagingDir, "."));
    createParents(new File(baseStorageDir, "."));
    createParents(new File(baseQuarantineDir, "."));
}
 
Example #11
Source File: DeviceOTAFirmwareResolver.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
   LOGGER.info("Loading device firmware file - {}", deviceOTAFirmwareUpdatePath);
   firmwareFileResource = Resources.getResource(deviceOTAFirmwareUpdatePath);
   if (firmwareFileResource.isWatchable()){
      firmwareFileResource.addWatch(() -> {
         firmwareFileUpdated();
      });
   }
   firmwareIndex.set(loadFirmwareFile());
}
 
Example #12
Source File: CommonAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@PostConstruct
protected void init2() {
	if (this.testBean3 == null || this.testBean4 == null) {
		throw new IllegalStateException("Resources not injected");
	}
	super.init2();
}
 
Example #13
Source File: InternalCommunicationIgnite.java    From ext-opensource-netty with Mozilla Public License 2.0 5 votes vote down vote up
@PostConstruct
private void internalListen() {
	igniteMessaging.localListen(internalTopic, (nodeId, msg) -> {
		///InternalMessage internalMessage = (InternalMessage) msg;
		return true;
	});
}
 
Example #14
Source File: CityController.java    From azure-spring-cloud-training with MIT License 5 votes vote down vote up
@PostConstruct
public void init() {
    container = new CosmosClientBuilder()
            .endpoint(cosmosDbUrl)
            .key(cosmosDbKey)
            .buildAsyncClient()
            .getDatabase(cosmosDbDatabase)
            .getContainer("City");
}
 
Example #15
Source File: IntegrateTxleController.java    From txle with Apache License 2.0 5 votes vote down vote up
@PostConstruct
void init() {
    ManagedChannel channel = ManagedChannelBuilder.forTarget(txleGrpcServerAddress).usePlaintext()/*.maxInboundMessageSize(10 * 1024 * 1024)*/.build();
    this.stubService = TxleTransactionServiceGrpc.newStub(channel);
    this.stubBlockingService = TxleTransactionServiceGrpc.newBlockingStub(channel);
    this.serverStreamObserver = new TxleGrpcServerStreamObserver(this);
    // 正式环境请设置正确的服务名称、IP和类别
    TxleClientConfig clientConfig = TxleClientConfig.newBuilder().setServiceName("actiontech-dble").setServiceIP("0.0.0.0").setServiceCategory("").build();
    stubService.onInitialize(clientConfig, new TxleServerConfigStreamObserver(this));

    this.onInitialize();
    this.initDBSchema();
    new Thread(() -> this.onSynDatabaseFullDose()).start();
}
 
Example #16
Source File: JuejinHotProcessor.java    From hot-crawler with MIT License 5 votes vote down vote up
@Override
@PostConstruct
protected void initialize(){
    RequestMethod requestMethod = RequestMethod.POST;
    setFieldsByProperties(siteProperties, requestMethod, generateHeader(),generateRequestBody());
    injectBeansByContext(context);
    setLog(LoggerFactory.getLogger(getClass()));
    setTitleJsonPaths(Arrays.asList("$.data.articleFeed.items.edges.[*].node.title"));
    setUrlJsonPaths(Arrays.asList("$.data.articleFeed.items.edges.[*].node.originalUrl"));
}
 
Example #17
Source File: ReleaseInfoServiceImpl.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
public void init() {
    DynamicConfig<LocalDynamicConfig> dynamicConfig = DynamicConfigLoader.load("releaseInfo_config.properties", false);
    dynamicConfig.addListener(aDynamicConfig -> {
        defaultReleaseInfoPath = aDynamicConfig.getString(DEFAULT, DEFAULT_RELEASE_INFO_PATH);
    });
}
 
Example #18
Source File: cachePolicies.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
@PostConstruct
public void initialize() {
    Collection<FidoPolicies> fpCol = getFidoPolicies.getAllActive();
    for(FidoPolicies fp: fpCol){
        FidoPoliciesPK fpPK = fp.getFidoPoliciesPK();
        try{
            FidoPolicyObject fidoPolicyObject = FidoPolicyObject.parse(
                    fp.getPolicy(),
                    fp.getVersion(),
                    (long) fpPK.getDid(),
                    (long) fpPK.getSid(),
                    (long) fpPK.getPid(),
                    fp.getStartDate(),
                    fp.getEndDate());

            MDSClient mds = null;
            if(fidoPolicyObject.getMdsOptions() != null){
                mds = new MDS(fidoPolicyObject.getMdsOptions().getEndpoints());
            }

            String mapkey = fpPK.getSid() + "-" + fpPK.getDid() + "-" + fpPK.getPid();
            skceMaps.getMapObj().put(skfsConstants.MAP_FIDO_POLICIES, mapkey, new FidoPolicyMDSObject(fidoPolicyObject, mds));
        }
        catch(SKFEException ex){
            skfsLogger.log(skfsConstants.SKFE_LOGGER, Level.SEVERE, "SKCE-ERR-1000", "Unable to cache policy: " + ex);
        }
    }

}
 
Example #19
Source File: AdminTriggerController.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@PostConstruct
public void afterPropertiesSet() {

  DebugCommands.Category debugHandler = debugCommands.findCategory("Catalogs");
  DebugCommands.Action act;

  act = new DebugCommands.Action("reportStats", "Make Catalog Report") {
    public void doAction(DebugCommands.Event e) {
      // look want background thread ?
      e.pw.printf("%n%s%n", makeReport());
    }
  };
  debugHandler.addAction(act);

  act = new DebugCommands.Action("reinit", "Read all catalogs") {
    public void doAction(DebugCommands.Event e) {
      // look want background thread ?
      boolean ok = catInit.reread(ConfigCatalogInitialization.ReadMode.always, false);
      e.pw.printf("<p/>Reading all catalogs%n");
      if (ok)
        e.pw.printf("reinit ok%n");
      else
        e.pw.printf("reinit failed%n");
    }
  };
  debugHandler.addAction(act);

  act = new DebugCommands.Action("recheck", "Read changed catalogs") {
    public void doAction(DebugCommands.Event e) {
      // look want background thread ?
      boolean ok = catInit.reread(ConfigCatalogInitialization.ReadMode.check, false);
      e.pw.printf("<p/>Reading changed catalogs%n");
      if (ok)
        e.pw.printf("reinit ok%n");
    }
  };
  debugHandler.addAction(act);
}
 
Example #20
Source File: MovieService.java    From jstarcraft-example with Apache License 2.0 5 votes vote down vote up
@PostConstruct
void postConstruct() {
    userDimension = dataModule.getQualityInner("user");
    itemDimension = dataModule.getQualityInner("item");
    scoreDimension = dataModule.getQuantityInner("score");
    qualityOrder = dataModule.getQualityOrder();
    quantityOrder = dataModule.getQuantityOrder();

    // 启动之后每间隔5分钟执行一次
    executor.scheduleAtFixedRate(this::refreshModel, 5, 5, TimeUnit.MINUTES);
}
 
Example #21
Source File: JobCenterAutoConfiguration.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    this.initDefaultParm();
    ScheduledExecutorService scheduleReport = Executors.newScheduledThreadPool(1, new NamedThreadFactory());
    scheduleReport.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            try {
                XxlJobExecutor xxlJobExecutor = applicationContext.getBean(XxlJobExecutor.class);
                String adminAddresses = discoveryAdminAddress();
                if (StringUtils.isEmpty(adminAddresses)) {
                    return;
                }
                if (adminAddresses.equals(xxlJobExecutor.getAdminAddresses())) {
                    LOGGER.info("AdminAddresses has no changes.");
                    return;
                }
                if (xxlJobExecutor.getAdminAddresses() == null) {
                    LOGGER.info("Old adminAddresses is NULL");
                } else {
                    LOGGER.info("Remove old node {}", xxlJobExecutor.getAdminAddresses());
                    XxlJobExecutor.getAdminBizList().clear();
                }

                LOGGER.info("Find all adminAddresses:" + adminAddresses + " from eureka");
                xxlJobExecutor.setAdminAddresses(adminAddresses);
                xxlJobExecutor.reInitAdminBizList();
            } catch (Throwable e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
    }, 0, 30, TimeUnit.SECONDS);
}
 
Example #22
Source File: QueueExpansionAlarmService.java    From pmq with Apache License 2.0 5 votes vote down vote up
@PostConstruct
private void init() {
	super.init(Constants.QUEUE_EXPANSION, soaConfig.getQueueExpansionCheckInterval(), soaConfig);
	soaConfig.registerChanged(new Runnable() {
		private volatile int interval = soaConfig.getQueueExpansionCheckInterval();
		@Override
		public void run() {
			if (soaConfig.getQueueExpansionCheckInterval() != interval) {
				interval = soaConfig.getQueueExpansionCheckInterval();
				updateInterval(interval);
			}
		}
	});
}
 
Example #23
Source File: ReadhubHotProcessor.java    From hot-crawler with MIT License 5 votes vote down vote up
@Override
@PostConstruct
protected void initialize(){
    RequestMethod requestMethod = RequestMethod.GET;
    setFieldsByProperties(siteProperties, requestMethod, generateHeader(),generateRequestBody());
    injectBeansByContext(context);
    setLog(LoggerFactory.getLogger(getClass()));
}
 
Example #24
Source File: CommonAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@PostConstruct
protected void init2() {
	if (this.testBean3 == null || this.testBean4 == null) {
		throw new IllegalStateException("Resources not injected");
	}
	super.init2();
}
 
Example #25
Source File: DirectMessageExecutor.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
   pool = new ThreadPoolBuilder()
         .withNameFormat("hub-directmsg-%d")
         .withMetrics("hub.direct.message")
         .withMaxPoolSize(poolSize)
         .withCorePoolSize(poolSize)
         .withPrestartCoreThreads(true)
         .withDaemon(true)
         .withMaxBacklog(poolQueueSize)
         .build();
}
 
Example #26
Source File: CamelResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@PostConstruct
void postConstruct() throws SQLException {
    try (Connection con = dataSource.getConnection()) {
        try (Statement statement = con.createStatement()) {
            try {
                statement.execute("drop table camels");
            } catch (Exception ignored) {
            }
            statement.execute("create table camels (id int primary key, species varchar(255))");
            statement.execute("insert into camels (id, species) values (1, 'Camelus dromedarius')");
            statement.execute("insert into camels (id, species) values (2, 'Camelus bactrianus')");
            statement.execute("insert into camels (id, species) values (3, 'Camelus ferus')");
        }
    }
}
 
Example #27
Source File: StoredProcedure1.java    From spring-boot with MIT License 5 votes vote down vote up
@PostConstruct
void init() {
    // o_name and O_NAME, same
    jdbcTemplate.setResultsMapCaseInsensitive(true);

    simpleJdbcCall = new SimpleJdbcCall(jdbcTemplate)
            .withProcedureName("get_book_by_id");

}
 
Example #28
Source File: JarDependenciesEndpoint.java    From Moss with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    CompletableFuture.runAsync(() -> {
        try {
            cachedObject = Analyzer.getAllPomInfo();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    });
}
 
Example #29
Source File: QuartzService.java    From springbootquartzs with MIT License 5 votes vote down vote up
@PostConstruct
public void startScheduler() {
    try {
        scheduler.start();
    } catch (SchedulerException e) {
        e.printStackTrace();
    }
}
 
Example #30
Source File: MyWebAppConfiguration.java    From molicode with Apache License 2.0 5 votes vote down vote up
@PostConstruct
 public void initEditableValidation(){
    ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
    if(initializer.getConversionService()!=null){
        GenericConversionService conversionService = (GenericConversionService) initializer.getConversionService();
        conversionService.addConverter(new StringToDateConverter());
    }
}