net.jodah.expiringmap.ExpiringMap Java Examples

The following examples show how to use net.jodah.expiringmap.ExpiringMap. 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: MusicRepository.java    From Melophile with Apache License 2.0 5 votes vote down vote up
@Inject
public MusicRepository(Mapper<Playlist, PlaylistEntity> playlistMapper,
                       Mapper<Track, TrackEntity> trackMapper,
                       Mapper<User, UserEntity> userMapper,
                       Mapper<UserDetails, UserDetailsEntity> detailsMapper,
                       RemoteSource remoteSource, LocalSource localSource,
                       PersonalInfo personalInfo, Context context,
                       BaseSchedulerProvider schedulerProvider) {
  this.playlistMapper = playlistMapper;
  this.trackMapper = trackMapper;
  this.userMapper = userMapper;
  this.detailsMapper = detailsMapper;
  this.remoteSource = remoteSource;
  this.localSource = localSource;
  this.personalInfo = personalInfo;
  this.schedulerProvider = schedulerProvider;
  this.context = context;
  //initialize cache
  playlistCacheStore = new CacheStore<>(ExpiringMap.builder()
          .maxSize(DEFAULT_CACHE_SIZE)
          .expiration(DEFAULT_CACHE_DURATION, TimeUnit.MINUTES)
          .build());

  trackCacheStore = new CacheStore<>(ExpiringMap.builder()
          .maxSize(DEFAULT_CACHE_SIZE)
          .expiration(DEFAULT_CACHE_DURATION, TimeUnit.MINUTES)
          .build());
  userCacheStore = new CacheStore<>(ExpiringMap.builder()
          .maxSize(DEFAULT_CACHE_SIZE)
          .expiration(DEFAULT_CACHE_DURATION, TimeUnit.MINUTES)
          .build());
}
 
Example #2
Source File: InMemorySlidingWindowRequestRateLimiter.java    From ratelimitj with Apache License 2.0 5 votes vote down vote up
InMemorySlidingWindowRequestRateLimiter(ExpiringMap<String, ConcurrentMap<String, Long>> expiringKeyMap, Set<RequestLimitRule> rules, TimeSupplier timeSupplier) {
    requireNonNull(rules, "rules can not be null");
    requireNonNull(rules, "time supplier can not be null");
    if (rules.isEmpty()) {
        throw new IllegalArgumentException("at least one rule must be provided");
    }
    this.expiringKeyMap = expiringKeyMap;
    this.timeSupplier = timeSupplier;
    this.rulesSupplier = new DefaultRequestLimitRulesSupplier(rules);
}
 
Example #3
Source File: PoolStrategyCache.java    From kanela with Apache License 2.0 5 votes vote down vote up
private PoolStrategyCache() {
    super(TypePool.Default.ReaderMode.FAST);
    ExpiringMap.setThreadFactory(NamedThreadFactory.instance("strategy-cache-listener"));
    this.cache = ExpiringMap
            .builder()
            .entryLoader((key) -> TypePool.CacheProvider.Simple.withObjectType())
            .expiration(1, TimeUnit.MINUTES)
            .expirationPolicy(ExpirationPolicy.ACCESSED)
            .asyncExpirationListener(LogExpirationListener())
            .build();
}
 
Example #4
Source File: NotificationPreProcessor.java    From MercuryTrade with MIT License 5 votes vote down vote up
public NotificationPreProcessor() {
    this.currentMessages = new ArrayList<>();
    this.expiresMessages = ExpiringMap.builder()
            .expiration(1, TimeUnit.HOURS)
            .build();
    this.subscribe();
}
 
Example #5
Source File: ExpiringMapPolicy.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public ExpiringMapPolicy(Config config) {
  policyStats = new PolicyStats("product.ExpiringMap");
  ExpiringMapSettings settings = new ExpiringMapSettings(config);
  cache = ExpiringMap.builder()
      .expirationPolicy(settings.policy())
      .maxSize(settings.maximumSize())
      .build();
}
 
Example #6
Source File: ExpirationNotificatorTimer.java    From oxAuth with MIT License 5 votes vote down vote up
public void initTimer() {
    log.debug("Initializing ExpirationNotificatorTimer");
    this.isActive = new AtomicBoolean(false);

    expiringMap = ExpiringMap.builder()
            .expirationPolicy(ExpirationPolicy.CREATED)
            .maxSize(appConfiguration.getExpirationNotificatorMapSizeLimit())
            .variableExpiration()
            .build();
    expiringMap.addExpirationListener(this);

    timerEvent.fire(new TimerEvent(new TimerSchedule(DEFAULT_INTERVAL, DEFAULT_INTERVAL), new ExpirationEvent(), Scheduled.Literal.INSTANCE));

    this.lastFinishedTime = System.currentTimeMillis();
}
 
Example #7
Source File: SS7Firewall.java    From SigFW with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Initialize the SS7 stack
 * 
 * @param ipChannelType TCP or UDP
 */
public void initializeStack(IpChannelType ipChannelType) throws Exception {
    
    // Initialize SigFW Extensions
    try {
        logger.info("Trying to load SigFW extensions from: " + "file://" + System.getProperty("user.dir")  + "/src/main/resources/SigFW_extension-1.0.jar");
        
        // Constructing a URL form the path to JAR
        URL u = new URL("file://" + System.getProperty("user.dir")  + "/src/main/resources/SigFW_extension-1.0.jar");
        
        // Creating an instance of URLClassloader using the above URL and parent classloader 
        ClassLoader loader  = URLClassLoader.newInstance(new URL[]{u}, ExternalFirewallRules.class.getClassLoader());

        // Returns the class object
        Class<?> mainClass = Class.forName("com.p1sec.sigfw.SigFW_extension.rules.ExtendedFirewallRules", true, loader);
        externalFirewallRules = (FirewallRulesInterface) mainClass.getDeclaredConstructor().newInstance();
        
        // Returns the class object
        Class<?> mainClassCrypto = Class.forName("com.p1sec.sigfw.SigFW_extension.crypto.ExtendedCrypto", true, loader);
        crypto = (CryptoInterface) mainClassCrypto.getDeclaredConstructor().newInstance();

        
        logger.info("Sucessfully loaded SigFW extensions ....");
    
    } catch (Exception e) {
        logger.info("Failed to load SigFW extensions: " + e.toString());
    }
    // End of SigFW Extensions
    
    if (SS7FirewallConfig.firewallPolicy == SS7FirewallConfig.FirewallPolicy.DNAT_TO_HONEYPOT) {
        dnat_sessions = ExpiringMap.builder()
                                            .expiration(SS7FirewallConfig.honeypot_dnat_session_expiration_timeout, TimeUnit.SECONDS)
                                            .build();
    }   

    this.initSCTP(ipChannelType);

    // Initialize M3UA first
    this.initM3UA();

    // Initialize SCCP
    this.initSCCP();
    
    // Initialize MAP
    this.initMAP();

    // 7. Start ASP
    serverM3UAMgmt.startAsp("RASP1");
    clientM3UAMgmt.startAsp("ASP1");

    logger.debug("[[[[[[[[[[    Started SctpFirewall       ]]]]]]]]]]");
}
 
Example #8
Source File: InMemorySlidingWindowRequestRateLimiter.java    From ratelimitj with Apache License 2.0 4 votes vote down vote up
public InMemorySlidingWindowRequestRateLimiter(Set<RequestLimitRule> rules, TimeSupplier timeSupplier) {
    this(ExpiringMap.builder().variableExpiration().build(), rules, timeSupplier);
}
 
Example #9
Source File: InMemoryConcurrentRequestRateLimiter.java    From ratelimitj with Apache License 2.0 4 votes vote down vote up
public InMemoryConcurrentRequestRateLimiter(ConcurrentLimitRule rule) {
    this.rule = rule;
    expiringKeyMap = ExpiringMap.builder().expiration(rule.getTimeoutMillis(), MILLISECONDS).expirationPolicy(ACCESSED).build();
}
 
Example #10
Source File: PreInitializeClasses.java    From kanela with Apache License 2.0 4 votes vote down vote up
private static void preExpiryMapKeySetAndKeySetIterator() {
    toPreventDeadCodeElimination = ExpiringMap.builder().build().keySet().iterator();
}
 
Example #11
Source File: ChatScannerFrame.java    From MercuryTrade with MIT License 4 votes vote down vote up
@Override
public void onViewInit() {
    this.scannerService = Configuration.get().scannerConfiguration();
    this.notificationConfig = Configuration.get().notificationConfiguration();
    this.expiresMessages = ExpiringMap.builder()
            .expiration(10, TimeUnit.SECONDS)
            .build();
    this.messageBuilder = new HtmlMessageBuilder();
    this.initHeaderBar();
    JPanel root = componentsFactory.getTransparentPanel(new BorderLayout());
    JPanel setupArea = componentsFactory.getTransparentPanel(new BorderLayout());
    setupArea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));

    JLabel title = componentsFactory.getTextLabel(
            FontStyle.REGULAR,
            AppThemeColor.TEXT_DEFAULT,
            TextAlignment.LEFTOP,
            15f,
            "Show messages containing the following words:");
    title.setBorder(BorderFactory.createEmptyBorder(2, 0, 6, 0));
    JTextArea words = componentsFactory.getSimpleTextArea(this.scannerService.get().getWords());
    words.setEditable(true);
    words.setCaretColor(AppThemeColor.TEXT_DEFAULT);
    words.setBorder(BorderFactory.createLineBorder(AppThemeColor.HEADER));
    words.setBackground(AppThemeColor.SLIDE_BG);

    JPanel navBar = componentsFactory.getJPanel(new FlowLayout(FlowLayout.CENTER), AppThemeColor.FRAME);
    Dimension buttonSize = new Dimension(90, 24);
    JButton save = componentsFactory.getBorderedButton("Save");
    save.addActionListener(action -> {
        this.scannerService.get().setWords(words.getText());
        MercuryStoreCore.saveConfigSubject.onNext(true);

        String[] split = words.getText().split(",");
        this.performNewStrings(split);
        this.hideComponent();
    });
    JButton cancel = componentsFactory.getBorderedButton("Cancel");
    cancel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(AppThemeColor.BORDER),
            BorderFactory.createLineBorder(AppThemeColor.TRANSPARENT, 3)
    ));
    cancel.setBackground(AppThemeColor.FRAME);
    cancel.addActionListener(action -> {
        hideComponent();
    });
    save.setPreferredSize(buttonSize);
    cancel.setPreferredSize(buttonSize);
    navBar.add(cancel);
    navBar.add(save);

    setupArea.add(title, BorderLayout.PAGE_START);
    setupArea.add(words, BorderLayout.CENTER);

    root.add(setupArea, BorderLayout.CENTER);
    root.add(getMemo(), BorderLayout.LINE_END);

    JPanel propertiesPanel = this.componentsFactory.getJPanel(new BorderLayout(), AppThemeColor.FRAME);

    JLabel quickResponseLabel = this.componentsFactory.getIconLabel(HotKeyType.N_QUICK_RESPONSE.getIconPath(), 18);
    quickResponseLabel.setFont(this.componentsFactory.getFont(FontStyle.REGULAR, 16));
    quickResponseLabel.setForeground(AppThemeColor.TEXT_DEFAULT);
    quickResponseLabel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
    quickResponseLabel.setText("Response message:");
    propertiesPanel.add(quickResponseLabel, BorderLayout.LINE_START);
    JTextField quickResponseField = this.componentsFactory.getTextField(this.scannerService.get().getResponseMessage(), FontStyle.BOLD, 15f);
    quickResponseField.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            scannerService.get().setResponseMessage(quickResponseField.getText());
        }
    });
    propertiesPanel.add(this.componentsFactory.wrapToSlide(quickResponseField, AppThemeColor.FRAME, 0, 4, 0, 4), BorderLayout.CENTER);

    root.add(propertiesPanel, BorderLayout.PAGE_END);
    this.add(root, BorderLayout.CENTER);
    this.add(navBar, BorderLayout.PAGE_END);
    this.pack();
}
 
Example #12
Source File: MemoryQueryCache.java    From heroic with Apache License 2.0 4 votes vote down vote up
@Inject
public MemoryQueryCache() {
    this.cache = ExpiringMap.builder().variableExpiration().build();
}
 
Example #13
Source File: ExpiringMapCache.java    From caffeine with Apache License 2.0 4 votes vote down vote up
public ExpiringMapCache(int maximumSize, ExpirationPolicy policy) {
  cache = ExpiringMap.builder()
      .expirationPolicy(policy)
      .maxSize(maximumSize)
      .build();
}
 
Example #14
Source File: KhanHttpSession.java    From khan-session with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Constructor
 *
 * @param sessionId
 * @param sessionStore
 * @param namespace
 * @param timeoutMin
 * @param session
 * @param sessionManager
 * @param clientIp
 */
public KhanHttpSession(String sessionId, SessionStore sessionStore, String namespace, Integer timeoutMin, HttpSession session, KhanSessionManager sessionManager, String clientIp) {
    // Check argument is not null
    StringUtils.isNotNull("khanSessionId", sessionId);
    StringUtils.isNotNull("sessionStore", sessionStore);
    StringUtils.isNotNull("khanNamespace", namespace);
    StringUtils.isNotNull("timeoutMin", timeoutMin);
    StringUtils.isNotNull("session", session);

    System.out.println("======================= KhanHttpSession ===================");

    this.khanSessionId = sessionId;
    this.sessionStore = sessionStore;
    this.khanNamespace = namespace;
    this.session = session;
    this.keyGenerator = new KhanSessionKeyGenerator(sessionId, namespace);
    this.sessionManager = sessionManager;

    if( log.isDebugEnabled() ) {
        log.debug("session.getMaxInactiveInterval()=" + session.getMaxInactiveInterval());
        log.debug("timeoutMinutes=" + timeoutMin);
    }

    // set session timeout seconds
    setMaxInactiveInterval(timeoutMin * 60);

    khanSessionMetadata = sessionStore.get(keyGenerator.generate(METADATA_KEY));
    if (khanSessionMetadata == null) {
        isNewlyCreated = true;
        khanSessionMetadata = new KhanSessionMetadata();
        khanSessionMetadata.setInvalidated(false);
        khanSessionMetadata.setCreationTime(new Date());
        khanSessionMetadata.setClientIp(clientIp);
        sessionStore.put(keyGenerator.generate(METADATA_KEY), khanSessionMetadata, getMaxInactiveInterval());
        sessionStore.put(keyGenerator.generate(ATTRIBUTES_KEY), attributes, getMaxInactiveInterval());
    }

    attributes = sessionStore.get(keyGenerator.generate(ATTRIBUTES_KEY));

    if( log.isDebugEnabled() ) {
        log.debug("keyGenerator.generate(ATTRIBUTES_KEY)=" + keyGenerator.generate(ATTRIBUTES_KEY));
        log.debug("KhanHttpSession.attributes=" + attributes);
    }

    //session.setAttribute("khansid", khanSessionId);
    //KhanSessionManager.getInstance().addSessionId(khanSessionId);
    //sessionManager.addSessionId(khanSessionId);

    config = KhanSessionFilter.getKhanSessionConfig();

    if( localChangedMap == null ) {
        localChangedMap = ExpiringMap.builder()
                .expiration(config.getSessionSaveDelay(), TimeUnit.SECONDS)
                .build();
    }

    if (log.isDebugEnabled()) {
        log.debug("New KhanHttpSession is created. (khanSessionId: " + sessionId + ", attributes: " + attributes + ")");
    }
}