Java Code Examples for java.util.TreeMap

The following are top voted examples for showing how to use java.util.TreeMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: ArubaSyslog   File: Utils.java View source code Vote up 7 votes
public static String formattrans(String date_string){
    //Prepare for the month name for date changing
    TreeMap<String, String> month_tmap = new TreeMap<String, String>();
    month_tmap.put("Jan", "01");
    month_tmap.put("Feb", "02");
    month_tmap.put("Mar", "03");
    month_tmap.put("Apr", "04");
    month_tmap.put("May", "05");
    month_tmap.put("Jun", "06");
    month_tmap.put("Jul", "07");
    month_tmap.put("Aug", "08");
    month_tmap.put("Sep", "09");
    month_tmap.put("Oct", "10");
    month_tmap.put("Nov", "11");
    month_tmap.put("Dec", "12");
    //change the date from "May 4" to "2013-05-04"
    String date_reg = "(?<month>\\w+)\\s+(?<day>\\d+)\\s+(?<time>(\\d{1,2}:){2}\\d{1,2})\\s+(?<year>\\d{4})";
    Pattern date_pattern = Pattern.compile(date_reg);
    Matcher date_matcher = date_pattern.matcher(date_string);
    if(! date_matcher.find()) return null;
    
    String year_string=date_matcher.group("year");
    //change the month format
    String month_string = date_matcher.group("month");
    if(month_tmap.containsKey(month_string)){
    	month_string = month_tmap.get(month_string);
    }else{
        System.out.println("Can not find the month!!!");
    }
    //change the day format
    String day_string = date_matcher.group("day");
    int day_int = Integer.parseInt(day_string);
    if(day_int < 10){
    	day_string = "0" + Integer.toString(day_int);
    }else{
    	day_string = Integer.toString(day_int);
    }
    String time_string = date_matcher.group("time");
    return String.format("%s-%s-%s %s", year_string, month_string, day_string, time_string);
}
 
Example 2
Project: mgwt   File: PermutationMapLinker.java View source code Vote up 7 votes
protected Map<String, Set<BindingProperty>> buildPermutationMap(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException {

    HashMap<String, Set<BindingProperty>> map = new HashMap<String, Set<BindingProperty>>();

    for (SelectionInformation result : artifacts.find(SelectionInformation.class)) {
      Set<BindingProperty> list = new HashSet<BindingProperty>();
      map.put(result.getStrongName(), list);

      TreeMap<String, String> propMap = result.getPropMap();
      Set<Entry<String, String>> set = propMap.entrySet();

      for (Entry<String, String> entry : set) {
        BindingProperty bindingProperty = new BindingProperty(entry.getKey(), entry.getValue());
        list.add(bindingProperty);
      }

    }
    return map;
  }
 
Example 3
Project: AIDR   File: FairScheduler.java View source code Vote up 6 votes
public FairScheduler(TreeMap<String, Double> channelLambdaList) {
	interval = new double[channelLambdaList.size() + 1];
	this.channelLambdaList = new TreeMap<String, Double>();

	this.channelLambdaList.putAll(channelLambdaList);
	transform();
	buildIntervalList();
}
 
Example 4
Project: iswc2012metadata   File: DataKeyKeyValue.java View source code Vote up 6 votes
public List<String> report(boolean bUseSubKey){
	List<String> ret = new ArrayList<String>();
	for (KEY key: data.keySet()){
		String line = key.toString()+":\t";
		TreeMap<SUBKEY, VALUE> map = data.get(key);
		for (SUBKEY subkey: map.keySet()){
			if (bUseSubKey)
				line += String.format("%s=%s\t", subkey, map.get(subkey));
			else
				line += String.format("%s\t",  map.get(subkey));
		}
		ret.add(line);
	}
	return ret;
}
 
Example 5
Project: aipo   File: PortletFilter.java View source code Vote up 6 votes
/**
 * Builds a list of all portlet categories
 * 
 * @param List portlets portlets to scan for categories
 * @return List of categories
 */
public static List buildCategoryList(List portlets)
{
    TreeMap catMap = new TreeMap();
    Iterator pItr = portlets.iterator();
    while (pItr.hasNext())
    {
        PortletEntry entry = (PortletEntry) pItr.next();

        Iterator cItr = entry.listCategories();
        while (cItr.hasNext())
        {
            BaseCategory cat = (BaseCategory) cItr.next();
            catMap.put(cat.getName(), cat);
        }
    }

    return new ArrayList(catMap.values());
}
 
Example 6
Project: hadoop_ekg   File: JobInitializationPoller.java View source code Vote up 6 votes
/**
 * This method returns the first job in the queue and removes the same.
 * 
 * @param queue
 *          queue name
 * @return First job in the queue and removes it.
 */
private JobInProgress getFirstJobInQueue(String queue) {
  TreeMap<JobSchedulingInfo, JobInProgress> jobsList = jobsPerQueue
      .get(queue);
  synchronized (jobsList) {
    if (jobsList.isEmpty()) {
      return null;
    }
    Iterator<JobInProgress> jobIterator = jobsList.values().iterator();
    JobInProgress job = jobIterator.next();
    jobIterator.remove();
    currentJobCount.getAndDecrement();
    return job;
  }
}
 
Example 7
Project: Hphoto   File: TableServer.java View source code Vote up 6 votes
private Object[] scanTable(HTable table,Text row, Text[] column,RowFilterInterface rf,Class valueClass) throws IOException{
	ArrayList<Writable> list = new ArrayList<Writable>();
	HScannerInterface s = table.obtainScanner(column,row,rf);
	Writable writeClass = WritableFactories.newInstance(valueClass);
    try{
    	 HStoreKey curKey = new HStoreKey();
         TreeMap<Text, byte[]> curVals = new TreeMap<Text, byte[]>();
         boolean next = s.next(curKey, curVals);
         while(next) {
        	 for(Iterator<Text> it = curVals.keySet().iterator(); it.hasNext(); ) {	
        		 writeClass = WritableFactories.newInstance(valueClass);	  
        		 byte[] bytes =  curVals.get(it.next());
        		 DataInputBuffer inbuf = new DataInputBuffer();
        		 inbuf.reset(bytes, bytes.length);
        		 writeClass.readFields(inbuf);
        		 inbuf.close(); 	        		
            	 list.add(writeClass);
             }
             curVals.clear();
             next = s.next(curKey, curVals);
         }
    }finally {
        s.close();
    }

    
   Object[] result = (Object[]) Array.newInstance(valueClass, list.size());
   for (int i = 0; i < list.size(); i++) {
      Array.set(result, i, list.get(i));
   }	  
   
   //if can comparable,sort it;
   if(WritableComparable.class.isAssignableFrom(valueClass)){
		Arrays.sort(result);
	}
	
   return result;

}
 
Example 8
Project: TAberystwyth   File: Allocator.java View source code Vote up 6 votes
private TreeMap<Integer, ArrayList<String>> getLeveledPools()
                throws SQLException {
    TreeMap<Integer, ArrayList<String>> pools = getPools();
    
    /*
     * For each pool, starting at the top (highest ranked pool) and working
     * down...
     */
    for (int i = pools.lastKey(); i > 0; --i) {
        /*
         * if the pool exists...
         */
        if (pools.containsKey(i)) {
            /*
             * and the pools size is not a multiple of 4...
             */
            while (!((pools.get(i).size() % 4) == 0)) {
                /*
                 * then pull up (randomly) a member from the pool directly
                 * below this one
                 */
                for (int j = (i - 1); j > 0; --j) {
                    if (pools.containsKey(j)) {
                        ArrayList<String> lowerPool = pools.get(j);
                        int randomElementIndex = randomGenerator
                                        .nextInt(lowerPool.size());
                        pools.get(i)
                                        .add(pools.get(j)
                                                        .remove(randomElementIndex));
                        
                        /*
                         * If the arraylist is empty then delete it
                         */
                        if (lowerPool.size() == 0) {
                            pools.remove(j);
                        }
                        break;
                    }
                }
            }
        }
    }
    
    return pools;
}
 
Example 9
Project: SPINdle   File: LiteralDataStore.java View source code Vote up 6 votes
private TreeMap<Temporal, ConclusionType> getConclusionsStored(Literal literal, ProvabilityLevel provability,
		Map<ProvabilityLevel, Map<Literal, TreeMap<Temporal, ConclusionType>>> conclusionsSet) {
	TreeMap<Temporal, ConclusionType> conclusionStored = getConclusionSet(literal, provability, conclusionsSet, false);
	if (AppFeatureConst.printDataStoreMessage) System.out.println("* * * conclusionStored=" + conclusionStored);
	if (null == conclusionStored || conclusionStored.size() == 0) {
		if (AppFeatureConst.printDataStoreMessage) System.out.println("* * no conclusions have been derived.");
		return null;
	}

	Temporal literalTemporal = literal.getTemporal();
	if (null == literalTemporal) literalTemporal = PERSISTENT_TEMPORAL;

	Temporal startTemporal = literalTemporal.getStartTimeAsInstance();
	Temporal endTemporal = literalTemporal.getEndTimeAsInstance();

	TreeMap<Temporal, ConclusionType> conclusionExtracted = new TreeMap<Temporal, ConclusionType>();

	Entry<Temporal, ConclusionType> lowerEntry = conclusionStored.lowerEntry(startTemporal);
	if (AppFeatureConst.printDataStoreMessage) System.out.println("-- conclusionStored.lowerEntry=" + lowerEntry);
	if (null != lowerEntry && lowerEntry.getKey().overlap(literalTemporal))
		conclusionExtracted.put(lowerEntry.getKey(), lowerEntry.getValue());
	SortedMap<Temporal, ConclusionType> conclusionSubset = conclusionStored.subMap(startTemporal, true, endTemporal, false);
	if (AppFeatureConst.printDataStoreMessage) System.out.println("-- conclusionStored.conclusionSubset=" + conclusionSubset);
	if (null != conclusionSubset) conclusionExtracted.putAll(conclusionSubset);
	if (AppFeatureConst.printDataStoreMessage) System.out.println("-- -> conclusionStored.conclusionExtracted=" + conclusionExtracted);

	return conclusionExtracted;
}
 
Example 10
Project: io   File: LinkDocHandler.java View source code Vote up 6 votes
/**
 * ???????.
 * @param srcHandler OEntityDocHandler
 * @param tgtHandler OEntityDocHandler
 */
public LinkDocHandler(final EntitySetDocHandler srcHandler, final EntitySetDocHandler tgtHandler) {
    this.cellId = srcHandler.getCellId();
    this.boxId = srcHandler.getBoxId();
    this.nodeId = srcHandler.getNodeId();
    String srcType = srcHandler.getType();
    String srcId = srcHandler.getId();
    String tgtType = tgtHandler.getType();
    String tgtId = tgtHandler.getId();

    // ES ??????????
    TreeMap<String, String> tm = new TreeMap<String, String>();
    tm.put(srcType, srcId);
    tm.put(tgtType, tgtId);

    this.ent1Type = tm.firstKey();
    this.ent2Type = tm.lastKey();
    this.ent1Key = tm.get(ent1Type);
    this.ent2Key = tm.get(ent2Type);
    this.id = this.createLinkId();
    long dateTime = new Date().getTime();
    this.published = dateTime;
    this.updated = dateTime;
}
 
Example 11
Project: js-invulnerable   File: DisambiguatePropertiesTest.java View source code Vote up 6 votes
/** Sorts the map and converts to a string for comparision purposes. */
private <T> String mapToString(Multimap<String, Collection<T>> map) {
  TreeMap<String, String> retMap = Maps.newTreeMap();
  for (String key : map.keySet()) {
    TreeSet<String> treeSet = Sets.newTreeSet();
    for (Collection<T> collection : map.get(key)) {
      Set<String> subSet = Sets.newTreeSet();
      for (T type : collection) {
        subSet.add(type.toString());
      }
      treeSet.add(subSet.toString());
    }
    retMap.put(key, treeSet.toString());
  }
  return retMap.toString();
}
 
Example 12
Project: HDP-2.2-Patched   File: AMRMClientImpl.java View source code Vote up 6 votes
@Override
public synchronized List<? extends Collection<T>> getMatchingRequests(
                                        Priority priority, 
                                        String resourceName, 
                                        Resource capability) {
  Preconditions.checkArgument(capability != null,
      "The Resource to be requested should not be null ");
  Preconditions.checkArgument(priority != null,
      "The priority at which to request containers should not be null ");
  List<LinkedHashSet<T>> list = new LinkedList<LinkedHashSet<T>>();
  Map<String, TreeMap<Resource, ResourceRequestInfo>> remoteRequests = 
      this.remoteRequestsTable.get(priority);
  if (remoteRequests == null) {
    return list;
  }
  TreeMap<Resource, ResourceRequestInfo> reqMap = remoteRequests
      .get(resourceName);
  if (reqMap == null) {
    return list;
  }

  ResourceRequestInfo resourceRequestInfo = reqMap.get(capability);
  if (resourceRequestInfo != null &&
      !resourceRequestInfo.containerRequests.isEmpty()) {
    list.add(resourceRequestInfo.containerRequests);
    return list;
  }
  
  // no exact match. Container may be larger than what was requested.
  // get all resources <= capability. map is reverse sorted. 
  SortedMap<Resource, ResourceRequestInfo> tailMap = 
                                                reqMap.tailMap(capability);
  for(Map.Entry<Resource, ResourceRequestInfo> entry : tailMap.entrySet()) {
    if (canFit(entry.getKey(), capability) &&
        !entry.getValue().containerRequests.isEmpty()) {
      // match found that fits in the larger resource
      list.add(entry.getValue().containerRequests);
    }
  }
  
  // no match found
  return list;          
}
 
Example 13
Project: cloudtm-data-platform   File: InnerNode.java View source code Vote up 6 votes
private void rotateRightToLeft(Map.Entry<Comparable,InnerNode> leftEntry, Map.Entry<Comparable,InnerNode> rightEntry) {
	InnerNode leftSubNode = leftEntry.getValue();
	InnerNode rightSubNode = rightEntry.getValue();

	TreeMap<Comparable,AbstractNode> newLeftSubNodeSubNodes = leftSubNode.duplicateMap();
	TreeMap<Comparable,AbstractNode> newRightSubNodeSubNodes = rightSubNode.duplicateMap();

	// re-index the left highest value under the split-key, which is moved down
	AbstractNode leftHighestValue = newLeftSubNodeSubNodes.get(BPlusTree.LAST_KEY);
	newLeftSubNodeSubNodes.put(leftEntry.getKey(), leftHighestValue);

	// remove right's lowest entry
	Map.Entry<Comparable,AbstractNode> rightLowestEntry = newRightSubNodeSubNodes.pollFirstEntry();
	
	// set its value on the left
	AbstractNode rightLowestValue = rightLowestEntry.getValue();
	newLeftSubNodeSubNodes.put(BPlusTree.LAST_KEY, rightLowestValue);
	rightLowestValue.setParent(leftSubNode);

    leftSubNode.setSubNodes(newLeftSubNodeSubNodes);
    rightSubNode.setSubNodes(newRightSubNodeSubNodes);

	// update the split-key to be the key we just removed from the right
	TreeMap<Comparable,AbstractNode> newMap = duplicateMap();
	newMap.remove(leftEntry.getKey());
	newMap.put(rightLowestEntry.getKey(), leftSubNode);
    setSubNodes(newMap);
}
 
Example 14
Project: hadoop-on-lustre2   File: ElasticByteBufferPool.java View source code Vote up 6 votes
@Override
public synchronized ByteBuffer getBuffer(boolean direct, int length) {
  TreeMap<Key, ByteBuffer> tree = getBufferTree(direct);
  Map.Entry<Key, ByteBuffer> entry =
      tree.ceilingEntry(new Key(length, 0));
  if (entry == null) {
    return direct ? ByteBuffer.allocateDirect(length) :
                    ByteBuffer.allocate(length);
  }
  tree.remove(entry.getKey());
  return entry.getValue();
}
 
Example 15
Project: cloudtm-data-platform   File: InnerNode.java View source code Vote up 6 votes
private void rotateLeftToRight(Map.Entry<Comparable,InnerNode> leftEntry, Map.Entry<Comparable,InnerNode> rightEntry) {
	InnerNode leftSubNode = leftEntry.getValue();
	InnerNode rightSubNode = rightEntry.getValue();

	TreeMap<Comparable,AbstractNode> newLeftSubNodeSubNodes = leftSubNode.duplicateMap();
	TreeMap<Comparable,AbstractNode> newRightSubNodeSubNodes = rightSubNode.duplicateMap();
	
	Comparable leftHighestKey = newLeftSubNodeSubNodes.lowerKey(BPlusTree.LAST_KEY);
	AbstractNode leftHighestValue = newLeftSubNodeSubNodes.get(BPlusTree.LAST_KEY);

	// move the highest value from the left to the right.  Use the split-key as the index.
	newRightSubNodeSubNodes.put(leftEntry.getKey(), leftHighestValue);
	leftHighestValue.setParent(rightSubNode);
	
	// shift a new child to the last entry on the left
	leftHighestValue = newLeftSubNodeSubNodes.remove(leftHighestKey);
	newLeftSubNodeSubNodes.put(BPlusTree.LAST_KEY, leftHighestValue);

    leftSubNode.setSubNodes(newLeftSubNodeSubNodes);
    rightSubNode.setSubNodes(newRightSubNodeSubNodes);

	// update the split-key to be the key we just removed from the left
	TreeMap<Comparable,AbstractNode> newMap = duplicateMap();
	newMap.remove(leftEntry.getKey());
	newMap.put(leftHighestKey, leftSubNode);
    setSubNodes(newMap);
}
 
Example 16
Project: jadira   File: TreeMapImplementor.java View source code Vote up 6 votes
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public <T> T clone(T obj, CloneDriver parentContext, IdentityHashMap<Object, Object> referencesToReuse, long stackDepth) {
    
	stackDepth++;
	
    final TreeMap<Object, Object> source = (TreeMap)obj;
    
    final TreeMap copy = new TreeMap(source.comparator());
    
    for (final Map.Entry e : source.entrySet()) {
        final Object key = parentContext.clone(e.getKey(), parentContext, referencesToReuse, stackDepth);
        final Object value = parentContext.clone(e.getValue(), parentContext, referencesToReuse, stackDepth);
        
        copy.put(key, value);
    }
    return (T) copy;
}
 
Example 17
Project: java_binding_v1   File: OAuthCredential.java View source code Vote up 6 votes
@SuppressWarnings("unchecked")
private SortedMap<String, String> generateOAuthParameters(String url, SortedMap<String, String> params)
    throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException
{
    TreeMap<String, String> oauthParameters = new TreeMap<String, String>();
    oauthParameters.put("oauth_consumer_key", consumerKey);
    oauthParameters.put("oauth_nonce", generateNonce());
    oauthParameters.put("oauth_timestamp", generateTimestamp());
    oauthParameters.put("oauth_signature_method", OAUTH_SIGNATURE_METHOD);
    oauthParameters.put("oauth_version", OAUTH_VERSION);
    
    if (userKey != null) {
        oauthParameters.put("oauth_token", userKey);
    }
    
    if (requestorId != null) {
        oauthParameters.put("xoauth_requestor_id", requestorId);
    }
    
    SortedMap<String, String> oauthParametersForBaseString = (SortedMap<String, String>)oauthParameters.clone();
    if (params != null) {
        for (Map.Entry<String, String> param : params.entrySet()) {
            oauthParametersForBaseString.put(param.getKey(), param.getValue());
        }
    }
    
    oauthParameters.put("oauth_signature", generateSignature(url, oauthParametersForBaseString));
    
    return oauthParameters;
}
 
Example 18
Project: nibiru   File: TokenRouter.java View source code Vote up 6 votes
@Override
public List<Destination> routesTo(ServerId local, Keyspace requestKeyspace,
        ClusterMembership clusterMembership, Token token) {
  //TODO this is not efficient we should cache this or refactor
  Map<String, String> tokenMap1 = (Map<String, String>) requestKeyspace
          .getKeyspaceMetaData().getProperties().get(TOKEN_MAP_KEY);
  TreeMap<String,String> tokenMap = new TreeMap<String,String>(tokenMap1); 
  Integer replicationFactor = (Integer) requestKeyspace
          .getKeyspaceMetaData().getProperties().get(REPLICATION_FACTOR);
  int rf = 1;
  if (replicationFactor != null){
    rf = replicationFactor;
  }
  if (rf > tokenMap.size()) {
    throw new IllegalArgumentException(
            "Replication factor specified was larger than token map size");
  }
  List<Destination> destinations = new ArrayList<Destination>();
  
  Map.Entry<String,String> ceilingEntry;
  ceilingEntry = tokenMap.ceilingEntry(token.getToken());
  if (ceilingEntry == null){
    ceilingEntry = tokenMap.firstEntry();
  }
  destinations.add(new Destination(ceilingEntry.getValue()));
  for (int i = 1; i < rf; i++) {
    ceilingEntry = tokenMap.higherEntry(ceilingEntry.getKey());
    if (ceilingEntry == null) {
      ceilingEntry = tokenMap.firstEntry();
    }
    destinations.add(new Destination(ceilingEntry.getValue()));
  }
  return destinations;
}
 
Example 19
Project: NucleusFramework   File: NucleusFriendsProvider.java View source code Vote up 6 votes
@Nullable
public <T extends IFriendLevel> T getClosestBelowLevel(Class<T> clazz, int rawLevel) {
    PreCon.notNull(clazz);

    TreeMap<Integer, IFriendLevel> map = _levels.get(clazz);
    if (map == null)
        return null;

    Entry<Integer, IFriendLevel> entry = map.floorEntry(rawLevel);
    if (entry == null)
        return null;

    @SuppressWarnings("unchecked")
    T result = (T)entry.getValue();

    return result;
}
 
Example 20
Project: cloudtm-data-platform   File: InnerNode.java View source code Vote up 6 votes
private TreeMap<Comparable,AbstractNode> justInsert(Comparable middleKey, AbstractNode subLeftNode, AbstractNode subRightNode) {
	TreeMap<Comparable,AbstractNode> newMap = duplicateMap();

	// find smallest key greater than middleKey
	Comparable keyJustAfterMiddleKey = newMap.higherKey(middleKey);
	newMap.put(keyJustAfterMiddleKey, subRightNode); // this replaces the previous mapping
	newMap.put(middleKey, subLeftNode); // this adds the new split
    setSubNodes(newMap);
	return newMap;
}
 
Example 21
Project: airlift   File: Bootstrap.java View source code Vote up 5 votes
public Injector initialize()
        throws Exception
{
    Preconditions.checkState(!initialized, "Already initialized");
    initialized = true;

    Logging logging = null;
    if (initializeLogging) {
        logging = Logging.initialize();
    }

    Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> log.error(throwable, "Uncaught exception in thread %s", thread.getName()));

    Map<String, String> requiredProperties;
    ConfigurationFactory configurationFactory;
    if (requiredConfigurationProperties == null) {
        // initialize configuration
        log.info("Loading configuration");
        ConfigurationLoader loader = new ConfigurationLoader();

        requiredProperties = Collections.emptyMap();
        String configFile = System.getProperty("config");
        if (configFile != null) {
            requiredProperties = loader.loadPropertiesFrom(configFile);
        }
    }
    else {
        requiredProperties = requiredConfigurationProperties;
    }
    SortedMap<String, String> properties = Maps.newTreeMap();
    if (optionalConfigurationProperties != null) {
        properties.putAll(optionalConfigurationProperties);
    }
    properties.putAll(requiredProperties);
    properties.putAll(fromProperties(System.getProperties()));
    properties = ImmutableSortedMap.copyOf(properties);

    configurationFactory = new ConfigurationFactory(properties);


    if (logging != null) {
        // initialize logging
        log.info("Initializing logging");
        LoggingConfiguration configuration = configurationFactory.build(LoggingConfiguration.class);
        logging.configure(configuration);
    }

    // Validate configuration
    List<Message> messages = processConfiguration(configurationFactory, log::warn, modules);

    // at this point all config file properties should be used
    // so we can calculate the unused properties
    TreeMap<String, String> unusedProperties = new TreeMap<>();
    unusedProperties.putAll(requiredProperties);
    unusedProperties.keySet().removeAll(configurationFactory.getUsedProperties());

    // Log effective configuration
    if (!quiet) {
        logConfiguration(configurationFactory, unusedProperties);
    }

    // system modules
    Builder<Module> moduleList = ImmutableList.builder();
    moduleList.add(new LifeCycleModule());
    moduleList.add(new ConfigurationModule(configurationFactory));
    if (!messages.isEmpty()) {
        moduleList.add(new ValidationErrorModule(messages));
    }
    moduleList.add(binder -> binder.bind(WarningsMonitor.class).toInstance(log::warn));

    // disable broken Guice "features"
    moduleList.add(Binder::disableCircularProxies);
    if (requireExplicitBindings) {
        moduleList.add(Binder::requireExplicitBindings);
    }

    // todo this should be part of the ValidationErrorModule
    if (strictConfig) {
        moduleList.add(binder -> {
            for (Entry<String, String> unusedProperty : unusedProperties.entrySet()) {
                binder.addError("Configuration property '%s=%s' was not used", unusedProperty.getKey(), unusedProperty.getValue());
            }
        });
    }
    moduleList.addAll(modules);

    // create the injector
    Injector injector = Guice.createInjector(Stage.PRODUCTION, moduleList.build());

    // Create the life-cycle manager
    LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class);

    // Start services
    if (lifeCycleManager.size() > 0) {
        lifeCycleManager.start();
    }

    return injector;
}
 
Example 22
Project: ArubaSyslog   File: SessionExtraction.java View source code Vote up 5 votes
private static List<String> extractRoughSessions(List<String> allLines) throws ParseException {
    List<String> roughSessions = new LinkedList<String>();
    //prepare to store the "Auth" log, K: ap name , V: date_string
    TreeMap<String, String> ap_auth_tmap = new TreeMap<String, String>();                   
    //start exacting the movement session
    String previous_ap = "";
    String previous_action = "";
    for ( String line : allLines ){
    	String[] parts = line.split("\\t");
    	if ( parts.length < 4 )
    		continue;
    	String mac = parts[0];
    	String date_string = parts[1];
    	String action = parts[2];
    	String ap = parts[3];
    	
        if(action.equals(ACTION_SESSION_START)){    //auth request log
            if(ap_auth_tmap.containsKey(ap)){
                //the treemap already has the ap name
                if(ap.equals(previous_ap) && action.equals(previous_action)){
                    //discard
                    if (Utils.debug){
                    	System.out.println("repeating auth log!");
                    }
                    continue;
                } else{
                    // replace the previous one
                	// currently, we do not end an auth (without deauth) with another auth.
                    ap_auth_tmap.put(ap, date_string);
                }
            }
            else{
                //a new ap name
                ap_auth_tmap.put(ap, date_string);
            }
        } else if (action.equals(ACTION_SESSION_END)){    //"Deauth log"
            if(ap_auth_tmap.containsKey(ap)){
                //movement exact
                String start_time_string = ap_auth_tmap.get(ap);
                String end_time_string = date_string;
                DateFormat df = new SimpleDateFormat(DATE_TIME_FORMAT);
                Date start_time = df.parse(start_time_string);
                Date end_time = df.parse(end_time_string);
                long duration = (end_time.getTime() - start_time.getTime())/1000;
                /*
                 * Write into the output file in the format of
                 * USER_MAC, START_TIME, END_TIME, DURATION, AP_NAME
                 */
                roughSessions.add(mac + "\t" + start_time_string + "\t" + end_time_string + "\t" + duration + "\t" + ap);
                //remove the auth time with this ap in the ap_auth_tmap
                ap_auth_tmap.remove(ap);
            } else{    
                //discard
                if (Utils.debug) {
                	System.out.println("Can not find the ap! discard!!!");
                }
                continue;
            }
        } else {
        	/*
        	 * Add other lines as what they are for future usage. 
        	 */
        	roughSessions.add(line);
        }
        previous_ap = ap;
        previous_action = action;
    }

    return roughSessions;
}
 
Example 23
Project: SPINdle   File: TdlReasoningEngine2.java View source code Vote up 5 votes
private Temporal getProvableTemporalSegment(Literal literal, ProvabilityLevel provability,Collection<Literal>conflictLiterals) throws LiteralDataStoreException {
	//	Set<Literal> conflictLiterals = getConflictLiterals(literal);
logMessage(Level.FINEST,3,"getProvableTemporalSegment",literal,provability,conflictLiterals);
		Temporal literalTemporal = literal.getTemporal();
		if (null == literalTemporal) literalTemporal = PERSISTENT_TEMPORAL;

		long startTime = literalTemporal.getStartTime();
		long endTime = literalTemporal.getEndTime();

		for (Literal conflictHeadLiteral : conflictLiterals) {
			// check the temporal information of preceding literals
			if (hasUnprovedRelatedPrecedingLiterals(literalTemporal,conflictHeadLiteral,provability)){
				System.out.println("    getProvableTemporalSegment => null temporal segment: has preceding conflict literals unproved");
				logMessage(Level.FINEST,4,"getProvableTemporalSegment =>null temporal segment","has preceding conflict literals unproved");
				return null;
			}
//			TreeMap<Temporal, Literal> unprovedPrecedingConflictHeadLiterals = literalDataStore.getUnprovedPrecedingHeadLiterals(
//					conflictHeadLiteral, provability);
//			if (null != unprovedPrecedingConflictHeadLiterals) {
//				for (Temporal precedingTemporal : unprovedPrecedingConflictHeadLiterals.keySet()) {
//					// check to prevent conclusion being defeated due to modal operator in the later process
//					if (literalTemporal.overlap(precedingTemporal) ){// && startTime < precedingTemporal.getEndTime()) {
//						System.out.println("    getProvableTemporalSegment => null temporal segment: has preceding conflict literals unproved");
//						return null;
//					}
//				}
//			}

			TreeMap<Temporal, Map<ConclusionType, Set<String>>> ambiguousConclusionsSet = getAmbiguousConclusions(conflictHeadLiteral,
					provability);
			if (null != ambiguousConclusionsSet) { // check the temporal information of ambiguous conclusions
				SortedMap<Temporal, Map<ConclusionType, Set<String>>> extractedConclusions = ambiguousConclusionsSet.headMap(Temporal
						.getTemporalInstance(endTime));
				if (null != extractedConclusions) {
					for (Entry<Temporal, Map<ConclusionType, Set<String>>> extractedEntry : extractedConclusions.entrySet()) {
						Temporal acTemporal = extractedEntry.getKey();
						if (literalTemporal.overlap(acTemporal)) {
							long acStart = acTemporal.getStartTime();
							// check to prevent conclusion being defeated due to modal operator in the later process
							if (literalTemporal.getStartTime() >= acStart) {
								System.out.println("    getProvableTemporalSegment => null temporal segment: has preceding ambiguous conclusion unresolved");
								logMessage(Level.FINEST,4,"getProvableTemporalSegment => null temporal segment:","has preceding ambiguous conclusion unresolved");
								return null;
							} else {
								if (endTime > acStart) endTime = acStart;
							}
						}
					}
				}
			}

			// check the temporal information of succeeding literals
			TreeMap<Temporal, Literal> unprovedSucceedingConflictHeadLiterals = literalDataStore.getUnprovedSucceedingHeadLiterals(
					conflictHeadLiteral, provability);
			if (null == unprovedSucceedingConflictHeadLiterals) continue;
			for (Temporal succeedingTemporal : unprovedSucceedingConflictHeadLiterals.keySet()) {
				if (literalTemporal.overlap(succeedingTemporal) && endTime > succeedingTemporal.getStartTime())
					endTime = succeedingTemporal.getStartTime();
			}
		}
		
		if (endTime == literalTemporal.getEndTime()) {
			return literalTemporal;
		} else {
			if (endTime == literalTemporal.getStartTime() && AppFeatureConst.isIntervalBasedTemporal) return null;
			return new Temporal(literalTemporal.getStartTime(), endTime);
		}
		// return endTime == headTemporal.getEndTime() ? headTemporal : new Temporal(headTemporal.getStartTime(), endTime);
	}
 
Example 24
Project: REST-OCD-Services   File: WeightedLinkCommunitiesAlgorithm.java View source code Vote up 5 votes
private List<Pair<Integer, Integer>> determineMostSimilarCommunityPairs(Matrix similarities) throws InterruptedException {
	double maxSimilarity = Double.NEGATIVE_INFINITY;
	double currentSimilarity;
	TreeMap<Integer, Integer> mergedCommunities = new TreeMap<Integer, Integer>();
	Set<Integer> updatedCommunities = new HashSet<Integer>();
	int oldCommunity;
	int newCommunity;
	for(int j=0; j<similarities.columns() - 1; j++) {
		for(int i=j+1; i<similarities.rows(); i++) {
			if(Thread.interrupted()) {
				throw new InterruptedException();
			}
			currentSimilarity = similarities.get(i, j);
			if(currentSimilarity >= maxSimilarity) {
				if(currentSimilarity > maxSimilarity) {
					mergedCommunities.clear();
					maxSimilarity = currentSimilarity;
				}
				newCommunity = j;
				if(mergedCommunities.containsKey(j)) {
					oldCommunity = mergedCommunities.get(j);
					if(oldCommunity <= newCommunity) {
						newCommunity = oldCommunity;
					}
					else {
						updatedCommunities.add(oldCommunity);
					}
				}
				if(mergedCommunities.containsKey(i)) {
					oldCommunity = mergedCommunities.get(i);
					if(oldCommunity <= newCommunity) {
						newCommunity = oldCommunity;
					}
					else {
						updatedCommunities.add(oldCommunity);
					}
				}
				if(updatedCommunities.size() > 0) {
					for(Entry<Integer, Integer> entry : mergedCommunities.entrySet()) {
						if(updatedCommunities.contains(entry.getValue())) {
							entry.setValue(newCommunity);
						}
					}
				}
				mergedCommunities.put(j, newCommunity);
				mergedCommunities.put(i, newCommunity);
			}
		}
	}
	List<Pair<Integer, Integer>> mostSimilarPairs = new ArrayList<Pair<Integer, Integer>>();
	Entry<Integer, Integer> lastPair;
	while(mergedCommunities.size() > 0) {
		if(Thread.interrupted()) {
			throw new InterruptedException();
		}
		lastPair = mergedCommunities.lastEntry();
		if(lastPair.getKey() != lastPair.getValue()) {
			mostSimilarPairs.add(new Pair<Integer, Integer>(lastPair.getValue(), lastPair.getKey()));
		}
		mergedCommunities.remove(lastPair.getKey());
	}
	return mostSimilarPairs;
}