Java Code Examples for java.util.HashMap.keySet()

The following are Jave code examples for showing how to use keySet() of the java.util.HashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: m6ASNP   File: MutationWriter.java   View Source Code Vote up 6 votes
public static void WriteMethylationMutationInBED(HashMap<String, LinkedList<MethylationMutationRecord>> methyMutMap, String savePath, boolean isOutputAll)
{
    try
    {
        FileWriter fw = new FileWriter(savePath);
        for(String sampleID : methyMutMap.keySet())
        {
            LinkedList<MethylationMutationRecord> methyMutRecList = methyMutMap.get(sampleID);
            for(MethylationMutationRecord methyMutRec : methyMutRecList)
            {
                if(!isOutputAll)
                {
                    if( (methyMutRec.getMutationEvent() == MutationEvent.FunctionalGain) || (methyMutRec.getMutationEvent() == MutationEvent.FunctionalLoss) )
                        fw.write(methyMutRec.toBEDString() + "\n");
                }
                else
                    fw.write(methyMutRec.toBEDString() + "\n");
            }
        }
        fw.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
}
 
Example 2
Project: BBSSDK-for-Android   File: ProtocolBase.java   View Source Code Vote up 6 votes
public Object uploadFile(String url, HashMap<String, Object> request, String path) throws Throwable {
	byte[] rawFile = readFile(path);
	ArrayList<KVPair<String>> headers = getHeaders(rawFile);
	MobLog.getInstance().d(">>>  file: " + path + "\nurl = " + url + "\nheader = " + headers.toString());

	NetworkTimeOut timeout = new NetworkTimeOut();
	timeout.readTimout = 30000;
	timeout.connectionTimeout = 5000;
	ArrayList<KVPair<String>> values = new ArrayList<KVPair<String>>();
	for (String key : request.keySet()) {
		values.add(new KVPair<String>(key, String.valueOf(request.get(key))));
	}
	ArrayList<KVPair<String>> files = new ArrayList<KVPair<String>>();
	files.add(new KVPair<String>("file", path));
	StringBuilder sb = new StringBuilder();
	HttpResponseCallback callback = newCallback(sb, null);
	NETWORK.httpPost(url, values, files, headers, callback, timeout);
	String resp = sb.toString().trim();
	MobLog.getInstance().d(">>> response: " + resp);
	return processResponse(HASHON.fromJson(resp));
}
 
Example 3
Project: Protestr   File: LocaleUtils.java   View Source Code Vote up 6 votes
private static LinkedHashMap<String, String> sortHashMapByValues(HashMap<String, String> passedMap) {
    List<String> mapKeys = new ArrayList<>(passedMap.keySet());
    List<String> mapValues = new ArrayList<>(passedMap.values());
    Collections.sort(mapValues);
    Collections.sort(mapKeys);

    LinkedHashMap<String, String> sortedMap = new LinkedHashMap<>();

    for (String val : mapValues) {
        Iterator<String> keyIt = mapKeys.iterator();

        while (keyIt.hasNext()) {
            String key = keyIt.next();
            String comp1 = passedMap.get(key);

            if (comp1.equals(val)) {
                keyIt.remove();
                sortedMap.put(key, val);
                break;
            }
        }
    }
    return sortedMap;
}
 
Example 4
Project: mutaflow   File: FlowExtractor.java   View Source Code Vote up 6 votes
/**
	 * Reports how often a sink occurred and how often it occurred without a source
	 * @param sinks
	 * @param sources
	 */
	private static void occurenceAdderSink(HashMap<String, HashSet<String>> sinks, HashMap<String, HashSet<String>> sources, HashMap<String, Integer> sinksOccurred, HashMap<String, Integer> sinksOccurredNoSource) {
		for (String sink : sinks.keySet()) {
//			System.out.println(sink);
			if (sinksOccurred.containsKey(sink)) {
				sinksOccurred.put(sink, sinksOccurred.get(sink)+1);
			} else {
				sinksOccurred.put(sink, 1);
				sinksOccurredNoSource.put(sink,0);
			}
			
			if (sources.isEmpty()) {
				sinksOccurredNoSource.put(sink, sinksOccurredNoSource.get(sink)+1);
			}
		}
	}
 
Example 5
Project: alfresco-core   File: BridgeTable.java   View Source Code Vote up 6 votes
public HashSet<T> getAncestors(T node, int start, int end)
{
    HashSet<T> answer = new HashSet<T>();
    HashMap<Integer, HashMap<T, Counter>> found = ancestors.get(node);
    if (found != null)
    {
        for (Integer key : found.keySet())
        {
            if ((key.intValue() >= start) && (key.intValue() <= end))
            {
                HashMap<T, Counter> asd = found.get(key);
                answer.addAll(asd.keySet());
            }
        }
    }
    return answer;
}
 
Example 6
Project: OasisLight-ServerManager   File: Main.java   View Source Code Vote up 5 votes
public static void removeServer() {
    String pName = "RemoveServer";
    while (true) {
        Printer.printPrompt(pName, "Enter the server name that you wish to remove:");
        String input = in.next();
        if (input.equalsIgnoreCase("back") || input.equalsIgnoreCase("b")) {
            return;
        }
        boolean removed = false;
        HashMap<String, Server> serverList = Storage.getServerList();
        synchronized (serverList) {
            for (String s : serverList.keySet()) {
                if (s.equals(input)) {
                    serverList.remove(s);

                    removed = true;
                    break;
                }
            }
        }
        if (removed) {

            Printer.printDataChange(pName, "Server \"" + input + "\" has been removed successfully.");
            return;
        } else {
            Printer.printFailedReply(pName, "Server \"" + input + "\" was not found.");
        }
    }
}
 
Example 7
Project: OpenJSharp   File: P11KeyStore.java   View Source Code Vote up 5 votes
/**
 * If the secret key shares a CKA_LABEL with another entry,
 * throw an exception
 */
private void mapSecretKeys(HashMap<String, AliasInfo> sKeyMap)
            throws KeyStoreException {
    for (String label : sKeyMap.keySet()) {
        if (aliasMap.containsKey(label)) {
            throw new KeyStoreException("invalid KeyStore state: " +
                    "found secret key sharing CKA_LABEL [" +
                    label +
                    "] with another token object");
        }
    }
    aliasMap.putAll(sKeyMap);
}
 
Example 8
Project: human-mobility-modeling-utilities   File: DataHelper.java   View Source Code Vote up 5 votes
/**
 * As its name tells, this method returns the given {@code traces} as a
 * hashmap that holds traces per user where the key values hold user ids
 * 
 * @param traces a list that has location traces from multiple users
 * @return location traces organized by user and sorted by date ascending.
 */
public static HashMap<String, List<LocationTrace>> organizeTracesByUserAndSort(
		List<LocationTrace> traces) {
	HashMap<String, List<LocationTrace>> traceMap = new HashMap<String, List<LocationTrace>>();

	// trace organization by user
	for (LocationTrace aTrace : traces) {
		List<LocationTrace> list;
		if (traceMap.containsKey(aTrace.getUserId()) == true) {
			list = traceMap.get(aTrace.getUserId());
		} else {
			list = new ArrayList<LocationTrace>();
			traceMap.put(aTrace.getUserId(), list);
		}
		list.add(aTrace);
	}

	// sorting traces by time ascending

	// comparator object
	Comparator<LocationTrace> comparator = new Comparator<LocationTrace>() {
		public int compare(LocationTrace t1, LocationTrace t2) {
			return (t1.getUTCTime().getMillis() > t2.getUTCTime()
					.getMillis() ? 1 : -1);
		}
	};

	for (String userId : traceMap.keySet()) {
		List<LocationTrace> traceListForUser = traceMap.get(userId);

		Collections.sort(traceListForUser, comparator);
		traceMap.put(userId, traceListForUser);
	}

	return traceMap;
}
 
Example 9
Project: org.openhab.binding.heos   File: HeosPlayer.java   View Source Code Vote up 5 votes
public void updatePlayerInfo(HashMap<String, String> values) {

        playerInfo = values;
        for (String key : values.keySet()) {
            if (key.equals("name")) {
                name = values.get(key);
            }
            if (key.equals("pid")) {
                pid = values.get(key);
            }
            if (key.equals("ip")) {
                ip = values.get(key);
            }
            if (key.equals("model")) {
                model = values.get(key);
            }
            if (key.equals("version")) {
                version = values.get(key);
            }
            if (key.equals("lineout")) {
                lineout = values.get(key);
            }
            if (key.equals("network")) {
                network = values.get(key);
            }
            if (key.equals("gid")) {
                gid = values.get(key);
            }
        }

    }
 
Example 10
Project: athena   File: DefaultRoutingHandler.java   View Source Code Vote up 5 votes
/**
 * Populate ECMP rules for subnets from all switches to destination.
 *
 * @param destSw Device ID of destination switch
 * @param ecmpSPG ECMP shortest path graph
 * @param subnets Subnets to be populated. If empty, populate all configured subnets.
 * @return true if succeed
 */
private boolean populateEcmpRoutingRules(DeviceId destSw,
                                         EcmpShortestPathGraph ecmpSPG,
                                         Set<Ip4Prefix> subnets) {

    HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia = ecmpSPG
            .getAllLearnedSwitchesAndVia();
    for (Integer itrIdx : switchVia.keySet()) {
        HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap = switchVia
                .get(itrIdx);
        for (DeviceId targetSw : swViaMap.keySet()) {
            Set<DeviceId> nextHops = new HashSet<>();
            log.debug("** Iter: {} root: {} target: {}", itrIdx, destSw, targetSw);
            for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
                if (via.isEmpty()) {
                    nextHops.add(destSw);
                } else {
                    nextHops.add(via.get(0));
                }
            }
            if (!populateEcmpRoutingRulePartial(targetSw, destSw, nextHops, subnets)) {
                return false;
            }
        }
    }

    return true;
}
 
Example 11
Project: weex-uikit   File: WXModuleManager.java   View Source Code Vote up 5 votes
public static void onActivityResult(String instanceId,int requestCode, int resultCode, Intent data){

    HashMap<String, WXModule> modules = sInstanceModuleMap.get(instanceId);
    if(modules!=null) {
      for (String key : modules.keySet()) {
        WXModule module = modules.get(key);
        if (module != null) {
          module.onActivityResult(requestCode, resultCode, data);
        } else {
          WXLogUtils.w("onActivityResult can not find the " + key + " module");
        }
      }
    }
  }
 
Example 12
Project: SlidingWindowFilter-evaluator   File: App.java   View Source Code Vote up 5 votes
private static HashMap<String, Distance<TimeSeries<Accel>>> getDistances() {
  HashMap<String, Distance<TimeSeries<Accel>>> hashMap =
      new HashMap<String, Distance<TimeSeries<Accel>>>();
  Complexity<Accel> complexityEstimate = new Complexity<Accel>(new EuclideanDistance());
  HashMap<String, AdjustmentWindowCondition> conditions = getConditions();
  for (String conditionName : conditions.keySet()) {
    AdjustmentWindowCondition condition = conditions.get(conditionName);
    hashMap.put(
        "DTW;" + conditionName,
        new DynamicTimeWarping<Accel>(new EuclideanDistance(), condition)
    );
    hashMap.put(
        "ηDTW;" + conditionName,
        new NormalizedDistance<Accel>(
            new DynamicTimeWarping<Accel>(new EuclideanDistance(), condition),
            new ZeroMean<Accel>(new Add(),  new ScalarMult())
        )
    );
    hashMap.put(
        "η'DTW;" + conditionName,
        new NormalizedDistance<Accel>(
            new DynamicTimeWarping<Accel>(new EuclideanDistance(), condition),
            new ZeroMeanOneVariance<Accel>(
                new EuclideanDistance(),
                new Add(),
                new ScalarMult()
            )
        )
    );
  }
  return hashMap;
}
 
Example 13
Project: alfresco-core   File: BridgeTable.java   View Source Code Vote up 5 votes
/**
 * @param parent T
 * @param child T
 */
private void addAncestors(T parent, T child)
{
    HashMap<Integer, HashMap<T, Counter>> childsAncestors = ancestors.get(child);
    if (childsAncestors == null)
    {
        childsAncestors = new HashMap<Integer, HashMap<T, Counter>>();
        ancestors.put(child, childsAncestors);
    }

    HashMap<Integer, HashMap<T, Counter>> parentAncestorsToAdd = ancestors.get(parent);

    // add all the childs children to the parents descendants

    add(parentAncestorsToAdd, Integer.valueOf(0), childsAncestors, parent);

    // add childs descendants to all parents ancestors at the correct depth

    HashMap<Integer, HashMap<T, Counter>> descenantsToFixUp = descendants.get(child);

    if (descenantsToFixUp != null)
    {
        for (Integer descendantPosition : descenantsToFixUp.keySet())
        {
            HashMap<T, Counter> descenantsToFixUpAtPosition = descenantsToFixUp.get(descendantPosition);
            for (T descenantToFixUpAtPosition : descenantsToFixUpAtPosition.keySet())
            {
                HashMap<Integer, HashMap<T, Counter>> descendatAncestors = ancestors.get(descenantToFixUpAtPosition);
                add(parentAncestorsToAdd, descendantPosition, descendatAncestors, parent);
            }
        }
    }
}
 
Example 14
Project: human-mobility-modeling-utilities   File: DataHelper.java   View Source Code Vote up 5 votes
public static HashMap<String, List<ExtendedLocationTrace>> organizeExtendedTracesByUserAndSort(
		List<ExtendedLocationTrace> traces) {
	HashMap<String, List<ExtendedLocationTrace>> traceMap = new HashMap<String, List<ExtendedLocationTrace>>();

	// trace organization by user
	for (ExtendedLocationTrace aTrace : traces) {
		List<ExtendedLocationTrace> list;
		if (traceMap.containsKey(aTrace.getUserId()) == true) {
			list = traceMap.get(aTrace.getUserId());
		} else {
			list = new ArrayList<ExtendedLocationTrace>();
			traceMap.put(aTrace.getUserId(), list);
		}
		list.add(aTrace);
	}

	// sorting traces by time ascending

	// comparator object
	Comparator<LocationTrace> comparator = new Comparator<LocationTrace>() {
		public int compare(LocationTrace t1, LocationTrace t2) {
			return (t1.getUTCTime().getMillis() > t2.getUTCTime()
					.getMillis() ? 1 : -1);
		}
	};

	for (String userId : traceMap.keySet()) {
		List<ExtendedLocationTrace> traceListForUser = traceMap.get(userId);

		Collections.sort(traceListForUser, comparator);
		traceMap.put(userId, traceListForUser);
	}

	return traceMap;
}
 
Example 15
Project: BaRMIe   File: RMIReplyDataParser.java   View Source Code Vote up 5 votes
/*******************
 * Handle a new object element in the ReplyData stream.
 * 
 * @param obj The RMIObject to populate with class names.
 * @param dataStack The remaining data in the ReplyData packet.
 ******************/
private void handleNewObjectElement(RMIObject obj, LinkedList<Byte> dataStack) throws BaRMIeInvalidReplyDataPacketException {
	LinkedList<HashMap<Byte, ArrayList<Character>>> classDataDesc;
	HashMap<Byte, ArrayList<Character>> classDataDescElement;
	ArrayList<Character> classDataDescFields;
	
	//Reset the field data
	this._classDataDesc.clear();
	
	//Read the class desc
	this.handleClassDesc(obj, dataStack);
	
	//Set the 'recordClasses' flag to false so that no further classes are added to the object description
	this._recordClasses = false;
	
	//Create a fresh copy of the class data description to use in reading the object data
	classDataDesc = new LinkedList<HashMap<Byte, ArrayList<Character>>>();
	for(HashMap<Byte, ArrayList<Character>> el: this._classDataDesc) {
		classDataDescElement = new HashMap<Byte, ArrayList<Character>>();
		for(Byte key: el.keySet()) {
			classDataDescFields = new ArrayList<Character>();
			for(Character typeCode: el.get(key)) {
				classDataDescFields.add(typeCode);
			}
			classDataDescElement.put(key, classDataDescFields);
		}
		classDataDesc.add(classDataDescElement);
	}
	
	//Read in the class data based on the classDataDesc
	this.handleClassData(obj, dataStack, classDataDesc);
}
 
Example 16
Project: Elgin-Plant-Game   File: EntityRenderer.java   View Source Code Vote up 5 votes
/**
 * Renders a model.
 * @param entities - List of entities to render
 */
public void render(HashMap<TexturedModel, List<Entity>> entities) {
    for(TexturedModel model:entities.keySet()) {
        prepareTexturedModel(model);
        List<Entity> batch = entities.get(model);
        for(Entity entity: batch) {
            prepareInstance(entity);
            GL11.glDrawElements(GL11.GL_TRIANGLES, model.getRawModel().getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
        }
        unbindTexturedModel();
    }
}
 
Example 17
Project: ObsidianSuite   File: TabulaMetadataExporter.java   View Source Code Vote up 5 votes
private void addMetadata()
{
    HashMap<String, ArrayList<String>> metaMap = Maps.newHashMap();
    if (converter != null) for (CubeInfo cube : converter.cubes)
    {
        for (String key : cube.metadata)
        {
            addToMeta(key, cube, metaMap);
        }
    }
    String xmlStr = "        <metadata headCap=\"-60,60\" headAxis=\"1\" headAxis2=\"0\" headDir=\"1\"";
    for (String s : metaMap.keySet())
    {
        ArrayList<String> parts = metaMap.get(s);
        String component = s + "=\"";
        for (int i = 0; i < parts.size(); i++)
        {
            component += parts.get(i);
            if (i < parts.size() - 1)
            {
                component += ",";
            }
        }
        component += "\"";
        xmlStr += " " + component;
    }
    xmlStr += "/>";
    lines.add(xmlStr);
}
 
Example 18
Project: SigFW   File: SS7Firewall.java   View Source Code Vote up 4 votes
/**
 * Method to execute firewall policy on target SCCP message.
 * 
 * @param mup M3UA instance in forward direction
 * @param mupReturn M3UA instance in reverse direction, to return UDTS
 * @param opc M3UA OPC
 * @param dpc M3UA DPC
 * @param sls M3UA SLS
 * @param ni M3UA NI
 * @param lmrt LongMessageRuleType
 * @param message Original SCCP message
 * @param reason the reason of discarding the message
 * @param lua_hm the LUA parameters, decoded from the message
 */
private void firewallMessage(Mtp3UserPart mup, Mtp3UserPart mupReturn, int opc, int dpc, int sls, int ni, LongMessageRuleType lmrt, SccpDataMessage message, String reason, HashMap<String, String> lua_hm) {
    String firewallPolicy = "";
    if (SS7FirewallConfig.firewallPolicy == SS7FirewallConfig.FirewallPolicy.DROP_SILENTLY) {
        firewallPolicy = "DROP_SILENTLY";
    } else if (SS7FirewallConfig.firewallPolicy == SS7FirewallConfig.FirewallPolicy.DROP_WITH_SCCP_ERROR) {
        firewallPolicy = "DROP_WITH_SCCP_ERROR";
        sendSccpErrorMessage(mupReturn, dpc, opc, sls, ni, lmrt, message, ReturnCauseValue.NO_TRANSLATION_FOR_ADDRESS);
    } else if (SS7FirewallConfig.firewallPolicy == SS7FirewallConfig.FirewallPolicy.DNAT_TO_HONEYPOT && dnat_sessions != null
            && message.getCallingPartyAddress() != null
            && message.getCallingPartyAddress().getGlobalTitle() != null 
            && message.getCalledPartyAddress() != null
            && message.getCalledPartyAddress().getGlobalTitle() != null
            ) {
        firewallPolicy = "DNAT_TO_HONEYPOT";
        
        GlobalTitle gt = this.sccpProvider.getParameterFactory().createGlobalTitle(SS7FirewallConfig.honeypot_sccp_gt, 0, org.mobicents.protocols.ss7.indicator.NumberingPlan.ISDN_TELEPHONY, null, NatureOfAddress.INTERNATIONAL);
        SccpAddress sa_dnat = this.sccpProvider.getParameterFactory().createSccpAddress(RoutingIndicator.ROUTING_BASED_ON_GLOBAL_TITLE, gt, 0, message.getCalledPartyAddress().getSubsystemNumber());
        SccpAddress sa = message.getCalledPartyAddress();
        String session_key = message.getCallingPartyAddress().getGlobalTitle().getDigits();
        dnat_sessions.put(session_key, message.getCalledPartyAddress().getGlobalTitle().getDigits() + ":" + message.getCalledPartyAddress().getSubsystemNumber());
        message.setCalledPartyAddress(sa_dnat);
        
        sendSccpMessage(mup, opc, dpc, sls, ni, lmrt, message);
    } else if (SS7FirewallConfig.firewallPolicy == SS7FirewallConfig.FirewallPolicy.ALLOW) {
        firewallPolicy = "ALLOW";
        sendSccpMessage(mup, opc, dpc, sls, ni, lmrt, message);
    }
    
    logger.info("Blocked message: Reason [" + reason + "] Policy [" + firewallPolicy + "] " + message.toString());
    
    JSONObject json_alert = new JSONObject();
    logger.debug("============ LUA variables ============");
    // mThreat alerting
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-256");
    
        for (String key : lua_hm.keySet()) {
            logger.debug(key + ": " + lua_hm.get(key));

            String value = lua_hm.get(key);
            // Anonymize MSISDN, IMSI
            if (key.equals("map_imsi") || key.equals("map_msisdn")) {
                // add salt before hashing
                value = SS7FirewallConfig.mthreat_salt + value;
                value = DatatypeConverter.printHexBinary(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
            } 
            json_alert.put(key, value);
        }
        mThreat_alerts.add(json_alert.toJSONString());
    } catch (NoSuchAlgorithmException ex) {
        java.util.logging.Logger.getLogger(SS7Firewall.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 19
Project: boohee_v5.6   File: TinkerDexLoader.java   View Source Code Vote up 4 votes
public static boolean checkComplete(String directory, ShareSecurityCheck securityCheck,
                                    Intent intentResult) {
    String meta = (String) securityCheck.getMetaContentMap().get("assets/dex_meta.txt");
    if (meta == null) {
        return true;
    }
    dexList.clear();
    ShareDexDiffPatchInfo.parseDexDiffPatchInfo(meta, dexList);
    if (dexList.isEmpty()) {
        return true;
    }
    HashMap<String, String> dexes = new HashMap();
    Iterator it = dexList.iterator();
    while (it.hasNext()) {
        ShareDexDiffPatchInfo info = (ShareDexDiffPatchInfo) it.next();
        if (!isJustArtSupportDex(info)) {
            if (ShareDexDiffPatchInfo.checkDexDiffPatchInfo(info)) {
                dexes.put(info.realName, info.destMd5InDvm);
            } else {
                intentResult.putExtra(ShareIntentUtil.INTENT_PATCH_PACKAGE_PATCH_CHECK, -3);
                ShareIntentUtil.setIntentReturnCode(intentResult, -9);
                return false;
            }
        }
    }
    String dexDirectory = directory + "/" + "dex" + "/";
    File dexDir = new File(dexDirectory);
    if (dexDir.exists() && dexDir.isDirectory()) {
        File optimizeDexDirectoryFile = new File(directory + "/" + "odex" + "/");
        for (String name : dexes.keySet()) {
            File dexFile = new File(dexDirectory + name);
            if (dexFile.exists()) {
                File dexOptFile = new File(SharePatchFileUtil.optimizedPathFor(dexFile,
                        optimizeDexDirectoryFile));
                if (!dexOptFile.exists()) {
                    intentResult.putExtra(ShareIntentUtil.INTENT_PATCH_MISSING_DEX_PATH,
                            dexOptFile.getAbsolutePath());
                    ShareIntentUtil.setIntentReturnCode(intentResult, -12);
                    return false;
                }
            }
            intentResult.putExtra(ShareIntentUtil.INTENT_PATCH_MISSING_DEX_PATH, dexFile
                    .getAbsolutePath());
            ShareIntentUtil.setIntentReturnCode(intentResult, -11);
            return false;
        }
        intentResult.putExtra(ShareIntentUtil.INTENT_PATCH_DEXES_PATH, dexes);
        return true;
    }
    ShareIntentUtil.setIntentReturnCode(intentResult, -10);
    return false;
}
 
Example 20
Project: unitimes   File: SessionRollForward.java   View Source Code Vote up 4 votes
protected void rollForwardBuildingPrefs(PreferenceGroup fromPrefGroup, PreferenceGroup toPrefGroup, Session toSession) throws Exception{
	Set locations = null;
	boolean isExamPref = false;
	if (fromPrefGroup instanceof Exam) {
		isExamPref = true;
	}
	if (fromPrefGroup.getBuildingPreferences() != null 
			&& !fromPrefGroup.getBuildingPreferences().isEmpty() 
			&& (!(fromPrefGroup instanceof Class_) || isClassRollForward())
			&& (!(fromPrefGroup instanceof SchedulingSubpart) || isSubpartLocationRollForward())){
		locations = getLocationsFor(fromPrefGroup, toPrefGroup, toSession);
		if (!isExamPref && locations == null){
			return;
		}
		for (Iterator it = fromPrefGroup.getBuildingPreferences().iterator(); it.hasNext(); ){
			createToBuildingPref((BuildingPref) it.next(), fromPrefGroup, toPrefGroup, toSession, locations, isExamPref);
		}
	}		
	if (fromPrefGroup instanceof SchedulingSubpart && isClassPrefsPushUp() && (toPrefGroup.getBuildingPreferences() == null || toPrefGroup.getBuildingPreferences().isEmpty())) {
		SchedulingSubpart ss = (SchedulingSubpart) fromPrefGroup;
		if (locations == null){
			locations = getLocationsFor(fromPrefGroup, toPrefGroup, toSession);
		}
		if (locations != null && locations.size() >0  && ss.getClasses() != null && !ss.getClasses().isEmpty()){
			HashMap<String, BuildingPref> prefMap = new HashMap<String, BuildingPref>();
			HashMap<String, Integer> prefCount = new HashMap<String, Integer>();
			String key;
			int clsCnt = 0;
			for (Iterator cIt = ss.getClasses().iterator(); cIt.hasNext();){
				Class_ c = (Class_)cIt.next();
				if (CancelledClassAction.SKIP == getCancelledClassAction() && c.isCancelled()) continue;
				clsCnt ++;
				if (c.getBuildingPreferences() != null && !c.getBuildingPreferences().isEmpty()){
					for (Iterator rfpIt = c.getBuildingPreferences().iterator(); rfpIt.hasNext();){
						BuildingPref rfp = (BuildingPref) rfpIt.next();
						key = rfp.getPrefLevel().getPrefName() + rfp.getBuilding().getUniqueId().toString();
						prefMap.put(key, rfp);
						int cnt = 0;
						if (prefCount.containsKey(key)){
							cnt = prefCount.get(key).intValue();
						}
						cnt++;
						prefCount.put(key, new Integer(cnt));
					}
				}
			}
			for (String pref : prefCount.keySet()){
				if (prefCount.get(pref).intValue() == clsCnt){
					createToBuildingPref(prefMap.get(pref), fromPrefGroup, toPrefGroup, toSession, locations, isExamPref);
				}
			}
		}				
	}
}