List of usage examples for java.util ArrayList clone
public Object clone()
From source file:com.nononsenseapps.notepad.sync.SyncAdapter.java
@SuppressWarnings("unchecked") @Override/*from w w w .j a v a 2 s . co m*/ public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext); // Only sync if it has been enabled by the user, and account is selected // Issue on reinstall where account approval is remembered by system if (settings.getBoolean(SyncPrefs.KEY_SYNC_ENABLE, false) && !settings.getString(SyncPrefs.KEY_ACCOUNT, "").isEmpty() && account.name.equals(settings.getString(SyncPrefs.KEY_ACCOUNT, ""))) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "onPerformSync"); Intent i = new Intent(SYNC_STARTED); mContext.sendBroadcast(i); // For later Intent doneIntent = new Intent(SYNC_FINISHED); doneIntent.putExtra(SYNC_RESULT, ERROR); // Initialize necessary stuff GoogleDBTalker dbTalker = new GoogleDBTalker(account.name, provider); GoogleAPITalker apiTalker = new GoogleAPITalker(); try { boolean connected = apiTalker.initialize(accountManager, account, AUTH_TOKEN_TYPE, NOTIFY_AUTH_FAILURE); if (connected) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "We got an authToken atleast"); try { // FIrst of all, we need the latest updated time later. // So // save // that for now. // This is the latest time we synced String lastUpdate = dbTalker.getLastUpdated(account.name); //String lastUpdate = settings.getString(PREFS_LAST_SYNC_DATE, null); // Get the latest hash value we saw on the server String localEtag = settings.getString(PREFS_LAST_SYNC_ETAG, ""); // Prepare lists for items ArrayList<GoogleTaskList> listsToSaveToDB = new ArrayList<GoogleTaskList>(); HashMap<GoogleTaskList, ArrayList<GoogleTask>> tasksInListToSaveToDB = new HashMap<GoogleTaskList, ArrayList<GoogleTask>>(); HashMap<Long, ArrayList<GoogleTask>> tasksInListToUpload = new HashMap<Long, ArrayList<GoogleTask>>(); HashMap<Long, ArrayList<GoogleTask>> allTasksInList = new HashMap<Long, ArrayList<GoogleTask>>(); // gets all tasks in one query ArrayList<GoogleTask> allTasks = dbTalker.getAllTasks(allTasksInList, tasksInListToUpload); ArrayList<GoogleTaskList> listsToUpload = new ArrayList<GoogleTaskList>(); ArrayList<GoogleTaskList> allLocalLists = new ArrayList<GoogleTaskList>(); // gets all lists in one query dbTalker.getAllLists(allLocalLists, listsToUpload); // Get the current hash value on the server and all // remote // lists if upload is not true String serverEtag = apiTalker.getModifiedLists(localEtag, allLocalLists, listsToSaveToDB); // IF the tags match, then nothing has changed on // server. if (localEtag.equals(serverEtag)) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Etags match, nothing to download"); } else { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Etags dont match, downloading new tasks"); // Download tasks which have been updated since last // time for (GoogleTaskList list : listsToSaveToDB) { if (list.id != null && !list.id.isEmpty()) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Saving remote modified tasks for: " + list.id); tasksInListToSaveToDB.put(list, list.downloadModifiedTasks(apiTalker, allTasks, lastUpdate)); } } } if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Getting stuff we want to upload"); // Get stuff we would like to upload to server // In case of lists, locally modified versions always // wins // in // conflict, so nothing more to do for (GoogleTaskList list : allLocalLists) { ArrayList<GoogleTask> moddedTasks = tasksInListToUpload.get(list.dbId); if (moddedTasks != null && !moddedTasks.isEmpty()) { // There are some tasks here which we want to // upload if (SYNC_DEBUG_PRINTS) Log.d(TAG, "List id " + list.dbId + ", Locally modified tasks found: " + moddedTasks.size()); // Now we need to handle possible conflicts in // the // tasks. But this has already been sorted when // we // downloaded them // For any task which exists in stuffToSaveToDB, // we // should not upload it // Iterate over a clone to avoid concurrency // problems since we will be modifying // the list during iteration for (GoogleTask moddedTask : (ArrayList<GoogleTask>) moddedTasks.clone()) { ArrayList<GoogleTask> tasksToBeSaved = tasksInListToSaveToDB.get(list); if (tasksToBeSaved != null && tasksToBeSaved.contains(moddedTask)) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "This modified task was newer on server, removing from upload list: " + moddedTask.title); moddedTasks.remove(moddedTask); } // In the case that a task has been deleted // before it was synced the first time // We should definitely not sync it. Only // delete // it later if (moddedTask.deleted == 1 && (moddedTask.id == null || moddedTask.id.isEmpty())) { moddedTasks.remove(moddedTask); } } } } if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Uploading lists"); // First thing we want to do is upload stuff, because // some // values are updated then boolean uploadedStuff = false; // Start with lists for (GoogleTaskList list : listsToUpload) { GoogleTaskList result = apiTalker.uploadList(list); uploadedStuff = true; if (result != null) { // Make sure that local version is the same as // server's for (GoogleTaskList localList : allLocalLists) { if (result.equals(localList)) { localList.title = result.title; localList.id = result.id; result.dbId = localList.dbId; break; } } listsToSaveToDB.add(result); } } if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Uploading tasks"); // Right, now upload tasks for (GoogleTaskList list : allLocalLists) { ArrayList<GoogleTask> tasksToUpload = tasksInListToUpload.get(list.dbId); if (tasksToUpload != null) { for (GoogleTask task : tasksToUpload) { GoogleTask result = apiTalker.uploadTask(task, list); uploadedStuff = true; // Task now has relevant fields set. Add to // DB-list if (tasksInListToSaveToDB.get(list) == null) tasksInListToSaveToDB.put(list, new ArrayList<GoogleTask>()); tasksInListToSaveToDB.get(list).add(result); } } } // Finally, get the updated etag from the server and // save. // Only worth doing if we actually uploaded anything // Also, only do this if we are doing a full sync String currentEtag = serverEtag; if (uploadedStuff) { currentEtag = apiTalker.getEtag(); //lastUpdate = dbTalker.getLastUpdated(account.name); } settings.edit().putString(PREFS_LAST_SYNC_ETAG, currentEtag) //.putString(PREFS_LAST_SYNC_DATE, lastUpdate) .commit(); // Now, set sorting values. for (GoogleTaskList list : tasksInListToSaveToDB.keySet()) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Setting position values in: " + list.id); ArrayList<GoogleTask> tasks = tasksInListToSaveToDB.get(list); if (tasks != null) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Setting position values for #tasks: " + tasks.size()); ArrayList<GoogleTask> allListTasks = allTasksInList.get(list.dbId); list.setSortingValues(tasks, allListTasks); } } // Save to database in a single transaction if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Save stuff to DB"); dbTalker.SaveToDatabase(listsToSaveToDB, tasksInListToSaveToDB); // Commit it ContentProviderResult[] result = dbTalker.apply(); if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Sync Complete!"); doneIntent.putExtra(SYNC_RESULT, SUCCESS); } catch (ClientProtocolException e) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "ClientProtocolException: " + e.getLocalizedMessage()); } catch (JSONException e) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "JSONException: " + e.getLocalizedMessage()); } catch (IOException e) { syncResult.stats.numIoExceptions++; if (SYNC_DEBUG_PRINTS) Log.d(TAG, "IOException: " + e.getLocalizedMessage()); } catch (RemoteException e) { if (SYNC_DEBUG_PRINTS) Log.d(TAG, "RemoteException: " + e.getLocalizedMessage()); } catch (OperationApplicationException e) { Log.d(TAG, "Joined operation failed: " + e.getLocalizedMessage()); } catch (ClassCastException e) { // GetListofLists will cast this if it returns a string. It should not return a string // but it did... Log.d(TAG, "ClassCastException: " + e.getLocalizedMessage()); } } else { // return real failure if (SYNC_DEBUG_PRINTS) Log.d(TAG, "Could not get authToken. Reporting authException"); syncResult.stats.numAuthExceptions++; doneIntent.putExtra(SYNC_RESULT, LOGIN_FAIL); } } finally { // This must always be called or we will leak resources if (apiTalker != null) { apiTalker.closeClient(); } mContext.sendBroadcast(doneIntent); if (SYNC_DEBUG_PRINTS) Log.d(TAG, "SyncResult: " + syncResult.toDebugString()); } } }
From source file:com.supremainc.biostar2.user.UserModifyFragment.java
@Override protected void registerBroadcast() { if (mReceiver == null) { mReceiver = new BroadcastReceiver() { @Override// w w w . j a v a 2 s.c om public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (mIsDestroy) { return; } if (action.equals(Setting.BROADCAST_UPDATE_FINGER)) { ArrayList<ListFingerprintTemplate> fingerTemplate = getExtraData( Setting.BROADCAST_UPDATE_FINGER, intent); if (fingerTemplate == null) { return; } if (mUserInfo != null) { mUserInfo.fingerprint_templates = fingerTemplate; mUserInfo.fingerprint_count = fingerTemplate.size(); } setFingerCount(); return; } if (action.equals(Setting.BROADCAST_UPDATE_CARD)) { ArrayList<ListCard> Cards = getExtraData(Setting.BROADCAST_UPDATE_CARD, intent); if (Cards == null) { return; } if (mUserInfo != null) { mUserInfo.cards = Cards; mUserInfo.card_count = Cards.size(); } setCardCount(); return; } if (action.equals(Setting.BROADCAST_UPDATE_USER_ACCESS_GROUP)) { ArrayList<ListAccessGroup> accessGroups = getExtraData( Setting.BROADCAST_UPDATE_USER_ACCESS_GROUP, intent); if (accessGroups == null) { return; } if (mUserInfo != null) { mUserInfo.access_groups = accessGroups; } setAccessGroupCount(); return; } if (action.equals(Setting.BROADCAST_PREFRENCE_REFRESH)) { if (mLayout == null || mContext == null) { return; } mLayout.setDateStart(mUserInfo.getTimeFormmat(mTimeConvertProvider, User.UserTimeType.start_datetime, TimeConvertProvider.DATE_TYPE.FORMAT_DATE)); mLayout.setDateEnd(mUserInfo.getTimeFormmat(mTimeConvertProvider, User.UserTimeType.expiry_datetime, TimeConvertProvider.DATE_TYPE.FORMAT_DATE)); return; } if (action.equals(Setting.BROADCAST_UPDATE_PERMISSION)) { ArrayList<CloudRole> permissions = getExtraData(Setting.BROADCAST_UPDATE_PERMISSION, intent); if (permissions == null) { return; } if (mUserInfo != null) { mUserInfo.roles = (ArrayList<CloudRole>) permissions.clone(); } setPermission(); return; } } }; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Setting.BROADCAST_UPDATE_FINGER); intentFilter.addAction(Setting.BROADCAST_UPDATE_CARD); intentFilter.addAction(Setting.BROADCAST_UPDATE_USER_ACCESS_GROUP); intentFilter.addAction(Setting.BROADCAST_PREFRENCE_REFRESH); intentFilter.addAction(Setting.BROADCAST_UPDATE_PERMISSION); LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, intentFilter); } }
From source file:GUI.ReadFile.java
public boolean readTrace(String fileName) { FileReader fileReader;//ww w . j a va 2 s . com CSVParser csvFileParser; boolean isSuccess = true; CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(TRACE_HEADER_MAPPING); try { ArrayList<String> Activity_set = new ArrayList<String>(); HashSet<String> ID_set = new HashSet<String>(); traces = new ArrayList<Trace>(); //initialize FileReader object System.out.println(fileName); fileReader = new FileReader(fileName); //initialize CSVParser object csvFileParser = new CSVParser(fileReader, csvFileFormat); //Get a list of CSV file records List<CSVRecord> csvRecords = csvFileParser.getRecords(); Trace t = new Trace(""); //Read the CSV file records starting from the second record to skip the header for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); String ID = record.get(CaseID); if (!ID_set.contains(ID) || (i == csvRecords.size() - 1)) { //Discard void trace if (i != 1) { traces.add(t); } ID_set.add(ID); t = new Trace(ID); } Activity ac = new Activity(record.get(Activity), record.get(StartTime), record.get(CompleteTime), record.get(Timestamp)); t.add_activity(ac); if (!Activity_set.contains(ac.get_name())) { Activity_set.add(ac.get_name()); } } //sort activity set by string Collections.sort(Activity_set); //sort trace by ID Collections.sort(traces, new Comparator<Trace>() { @Override public int compare(Trace t1, Trace t2) { return Integer.parseInt(t1.get_ID()) < Integer.parseInt(t2.get_ID()) ? -1 : 1; } }); //Set activity set for each trace for (Trace T : traces) { T.set_ActivitySet((List<String>) Activity_set.clone()); } } catch (Exception e) { System.out.println("Error in CsvFileReader !!!"); e.printStackTrace(); isSuccess = false; return isSuccess; } if (isSuccess) { try { fileReader.close(); csvFileParser.close(); } catch (IOException e) { System.out.println("Error while closing fileReader/csvFileParser !!!"); } } return isSuccess; }
From source file:org.apache.hadoop.hbase.index.coprocessor.regionserver.ScanFilterEvaluator.java
@SuppressWarnings("unchecked") Set<List<List<List<Column>>>> getColsBreakUps(Set<Column> columns) { int totalColsCount = columns.size(); // Breakups should be sorted such that the best one come before the others. The best one is the // one with lower number of splits. If the number of splits same, then the which contains more // cols in one split. // eg: When there are total 5 cols, then split [7] is better than [4,1] and [4,1] is better // than [3,2] Comparator<List<List<List<Column>>>> comparator = new Comparator<List<List<List<Column>>>>() { @Override//from www .j a va2s . c om public int compare(List<List<List<Column>>> l1, List<List<List<Column>>> l2) { List<List<Column>> firstColsCombl1 = l1.get(0); List<List<Column>> firstColsCombl2 = l2.get(0); int result = firstColsCombl1.size() - firstColsCombl2.size(); if (result != 0) return result; int size = Math.min(firstColsCombl1.size(), firstColsCombl2.size()); for (int i = 0; i < size; i++) { int colsSizeInSplit1 = firstColsCombl1.get(i).size(); int colsSizeInSplit2 = firstColsCombl2.get(i).size(); result = colsSizeInSplit1 - colsSizeInSplit2; if (result != 0) return -result; } return 0; } }; Set<List<List<List<Column>>>> listOfCols = new TreeSet<List<List<List<Column>>>>(comparator); ColCombination comb = new ColCombination(); ArrayList<Integer> breakUp = null; int firstItemColsCount = totalColsCount; while (firstItemColsCount >= 1) { breakUp = new ArrayList<Integer>(); breakUp.add(firstItemColsCount); int totalColsCountInBreakUp = firstItemColsCount; while (totalColsCountInBreakUp < totalColsCount) { // Fill with 1... breakUp.add(1); totalColsCountInBreakUp++; } listOfCols.add(makeColCombination(columns, breakUp, comb)); // now try to combine the after 1st entry 1s into bigger items. // But this combined value never should be more than the 1st value. // group last 2 items and create a new breakup.. while (true) { // In order to do this group there should be atleast 3 elements in the breakUp list. if (breakUp.size() < 3) { break; } breakUp = (ArrayList<Integer>) breakUp.clone(); int lastElem = breakUp.remove(breakUp.size() - 1); int secondLastElem = breakUp.remove(breakUp.size() - 1); // Add this element to the current last. ie. the old second last element // Well this element must be 1 only. int newLastElem = lastElem + secondLastElem; if (newLastElem > firstItemColsCount) { break; } breakUp.add(newLastElem); listOfCols.add(makeColCombination(columns, breakUp, comb)); } firstItemColsCount--; } return listOfCols; }
From source file:net.i2cat.netconf.NetconfSession.java
public void connect() throws TransportException, NetconfProtocolException { RPCElement reply;/*from www. j a v a 2s . c om*/ Hello clientHello; Hello serverHello; ArrayList<Capability> activeCapabilities; ArrayList<Capability> clientCapabilities; ArrayList<Capability> serverCapabilities; messageQueue = new MessageQueue(); messageQueue.addListener(this); try { transport = transportFactory.getTransport(sessionContext.getURI().getScheme()); } catch (TransportNotRegisteredException e) { TransportException te = new TransportException(e.getMessage()); te.initCause(e); throw te; } transport.setMessageQueue(messageQueue); transport.addListener(this); // initialize message id sessionContext.setLastMessageId(0); transport.connect(sessionContext); log.info("Transport connected"); clientHello = new Hello(); clientCapabilities = Capability.getSupportedCapabilities(); clientHello.setCapabilities(clientCapabilities); log.info("Sending hello"); transport.sendAsyncQuery(clientHello); try { if (sessionContext.containsKey(SessionContext.TIMEOUT)) { reply = messageQueue.blockingConsumeById("0", sessionContext.getTimeout()); } else { reply = messageQueue.blockingConsumeById("0"); } } catch (UncheckedTimeoutException e) { throw new TransportException("No reply to hello -- timeout.", e); } catch (Exception e) { throw new TransportException("Error while getting reply: " + e.getMessage(), e); } // message-id, it is // indexed under 0. if (!(reply instanceof Hello)) throw new NetconfProtocolException("First element received from server is not a <hello> message."); else serverHello = (Hello) reply; log.info("Received server hello."); this.sessionId = serverHello.getSessionId(); // trim to common capabilities. serverCapabilities = serverHello.getCapabilities(); activeCapabilities = (ArrayList<Capability>) clientCapabilities.clone(); activeCapabilities.retainAll(serverCapabilities); log.debug("ACT_CAP " + activeCapabilities); sessionContext.setActiveCapabilities(activeCapabilities); sessionContext.setClientCapabilities(clientCapabilities); sessionContext.setServerCapabilities(serverCapabilities); log.info("Session " + this.sessionId + " opened with:"); for (Capability capability : activeCapabilities) log.info(" - Capability: " + capability); /* Activate flags */ // Activate keep Alive command // timerKeepAlive = new TimerKeepAlive(this); // timerKeepAlive.start(PERIOD); }
From source file:org.prom5.analysis.petrinet.cpnexport.HLToCPNTranslator.java
/** * Generates the inscriptions for the inner part of the model. So, this means * that the arcs and places in between the first and last transition get the correct * inscription, respectively the correct type. * @param transition ColoredTransition/*from w ww . j a v a2s . com*/ */ private void generateInscriptionsInnerPart(ColoredTransition transition) { // needed for push/pull ArrayList<CpnColorSet> colorSetWithoutGroup = new ArrayList<CpnColorSet>(); HLGroup group = transition.getHighLevelTransition().getGroup(); ArrayList<CpnColorSet> colorSets = new ArrayList<CpnColorSet>(); ArrayList<CpnColorSet> colorSetsNoGroup = new ArrayList<CpnColorSet>(); CpnColorSet colorSetsCPN = null; CpnColorSet colorSetsNoGroupCPN = null; colorSets.add(colorsetTranslator.getColorSetCaseID()); if (ManagerConfiguration.getInstance().isThroughputTimeMonitorEnabled()) { colorSets.add(colorsetTranslator.getColorSetStartCase()); } if (!transition.isInvisibleTask() && (ManagerConfiguration.getInstance().isResourcePerspectiveEnabled()) && !transition.getHighLevelTransition().isAutomatic()) { if (ManagerConfiguration.getInstance().isPullEnabled()) { // need to have a group with and without group colorSetsNoGroup = (ArrayList<CpnColorSet>) colorSets.clone(); colorSetsNoGroupCPN = colorsetTranslator.productCpnColorSet(colorSetsNoGroup); } colorSets.add(colorsetTranslator.getColorSetGroup(group)); } colorSetsCPN = colorsetTranslator.productCpnColorSet(colorSets); SubpageMapping mapping = transition.getSubpageMapping(); Iterator<Place> places = transition.getSubpage().getPlaces().iterator(); while (places.hasNext()) { ColoredPlace p = (ColoredPlace) places.next(); if (mapping.getMappingForSubPlace(p) == null) { String arcInscription = ""; // if pull is enabled and we are considering place with name // W and the resource perspective is enabled and there are resources // then the product color set needs to be changed (so without resources) if (p.getIdentifier().equals(namePlaceWaiting) && ManagerConfiguration.getInstance().isPullEnabled()) { if (!transition.getHighLevelTransition().isAutomatic()) { // do not need a colorset with a group p.setPlaceType(CpnUtils.getCpnValidName(colorSetsNoGroupCPN.getNameColorSet())); } else { p.setPlaceType(CpnUtils.getCpnValidName(colorSetsCPN.getNameColorSet())); } } else { p.setPlaceType(CpnUtils.getCpnValidName(colorSetsCPN.getNameColorSet())); } // ensure that the ingoing arcs and outgoing arcs have the correct // inscription (tuple of a resource and a case-id) arcInscription = "(" + variableTranslator.getCpnVarForCaseId().getVarName(); if (ManagerConfiguration.getInstance().isThroughputTimeMonitorEnabled()) { arcInscription = arcInscription + "," + variableTranslator.getCpnVarForStartCase().getVarName(); } if ((ManagerConfiguration.getInstance().isResourcePerspectiveEnabled()) && !transition.getHighLevelTransition().isAutomatic() && !transition.isInvisibleTask()) { String withRes = "," + variableTranslator.getCpnVarForGroup(group).getVarName(); if (p.getIdentifier().equals(namePlaceWaiting)) { if (ManagerConfiguration.getInstance().isPushEnabled()) { arcInscription = arcInscription + withRes; } else { // nothing } } else { arcInscription = arcInscription + withRes; } } arcInscription = arcInscription + ")"; Iterator<ColoredEdge> edgesIn = p.getInEdgesIterator(); while (edgesIn.hasNext()) { ColoredEdge edge = edgesIn.next(); edge.setArcInscription(arcInscription + edge.getArcInscription()); } Iterator<ColoredEdge> edgesOut = p.getOutEdgesIterator(); while (edgesOut.hasNext()) { ColoredEdge edge = edgesOut.next(); edge.setArcInscription(arcInscription); } } } }
From source file:org.openbravo.erpCommon.ad_forms.ModuleManagement.java
/** * Returns the list of modules which license must be acquired to be installed in the instance. * Currently it only removes core from the list of not allowed modules because it is not needed to * acquire a license for the module, just the Professional Subscription. It could be implemented * to remove also all the free commercial modules, in case this info came from CR. * // w ww. j a v a2 s . c o m * @param notAllowedModules * List with all the not allowed commercial modules * @return List with all the commercial modules that need a license to be acquired */ @SuppressWarnings("unchecked") private List<Module> getModulesToAcquire(ArrayList<Module> notAllowedModules) { List<Module> rt = (List<Module>) notAllowedModules.clone(); for (Module mod : rt) { if ("0".equals(mod.getModuleID())) { rt.remove(mod); break; } } return rt; }
From source file:org.processmining.analysis.petrinet.cpnexport.HLToCPNTranslator.java
/** * Generates the inscriptions for the inner part of the model. So, this * means that the arcs and places in between the first and last transition * get the correct inscription, respectively the correct type. * /*from w ww . jav a 2s . c o m*/ * @param transition * ColoredTransition */ private void generateInscriptionsInnerPart(ColoredTransition transition) { // needed for push/pull ArrayList<CpnColorSet> colorSetWithoutGroup = new ArrayList<CpnColorSet>(); HLGroup group = transition.getHighLevelTransition().getGroup(); ArrayList<CpnColorSet> colorSets = new ArrayList<CpnColorSet>(); ArrayList<CpnColorSet> colorSetsNoGroup = new ArrayList<CpnColorSet>(); CpnColorSet colorSetsCPN = null; CpnColorSet colorSetsNoGroupCPN = null; colorSets.add(colorsetTranslator.getColorSetCaseID()); if (ManagerConfiguration.getInstance().isThroughputTimeMonitorEnabled()) { colorSets.add(colorsetTranslator.getColorSetStartCase()); } if (!transition.isInvisibleTask() && (ManagerConfiguration.getInstance().isResourcePerspectiveEnabled()) && !transition.getHighLevelTransition().isAutomatic()) { if (ManagerConfiguration.getInstance().isPullEnabled()) { // need to have a group with and without group colorSetsNoGroup = (ArrayList<CpnColorSet>) colorSets.clone(); colorSetsNoGroupCPN = colorsetTranslator.productCpnColorSet(colorSetsNoGroup); } colorSets.add(colorsetTranslator.getColorSetGroup(group)); } colorSetsCPN = colorsetTranslator.productCpnColorSet(colorSets); SubpageMapping mapping = transition.getSubpageMapping(); Iterator<Place> places = transition.getSubpage().getPlaces().iterator(); while (places.hasNext()) { ColoredPlace p = (ColoredPlace) places.next(); if (mapping.getMappingForSubPlace(p) == null) { String arcInscription = ""; // if pull is enabled and we are considering place with name // W and the resource perspective is enabled and there are // resources // then the product color set needs to be changed (so without // resources) if (p.getIdentifier().equals(namePlaceWaiting) && ManagerConfiguration.getInstance().isPullEnabled()) { if (!transition.getHighLevelTransition().isAutomatic()) { // do not need a colorset with a group p.setPlaceType(CpnUtils.getCpnValidName(colorSetsNoGroupCPN.getNameColorSet())); } else { p.setPlaceType(CpnUtils.getCpnValidName(colorSetsCPN.getNameColorSet())); } } else { p.setPlaceType(CpnUtils.getCpnValidName(colorSetsCPN.getNameColorSet())); } // ensure that the ingoing arcs and outgoing arcs have the // correct // inscription (tuple of a resource and a case-id) arcInscription = "(" + variableTranslator.getCpnVarForCaseId().getVarName(); if (ManagerConfiguration.getInstance().isThroughputTimeMonitorEnabled()) { arcInscription = arcInscription + "," + variableTranslator.getCpnVarForStartCase().getVarName(); } if ((ManagerConfiguration.getInstance().isResourcePerspectiveEnabled()) && !transition.getHighLevelTransition().isAutomatic() && !transition.isInvisibleTask()) { String withRes = "," + variableTranslator.getCpnVarForGroup(group).getVarName(); if (p.getIdentifier().equals(namePlaceWaiting)) { if (ManagerConfiguration.getInstance().isPushEnabled()) { arcInscription = arcInscription + withRes; } else { // nothing } } else { arcInscription = arcInscription + withRes; } } arcInscription = arcInscription + ")"; Iterator<ColoredEdge> edgesIn = p.getInEdgesIterator(); while (edgesIn.hasNext()) { ColoredEdge edge = edgesIn.next(); edge.setArcInscription(arcInscription + edge.getArcInscription()); } Iterator<ColoredEdge> edgesOut = p.getOutEdgesIterator(); while (edgesOut.hasNext()) { ColoredEdge edge = edgesOut.next(); edge.setArcInscription(arcInscription); } } } }
From source file:org.opencyc.constraintsolver.ForwardCheckingSearcher.java
/** * Recurses to instantiate the rule in the constraint problem microtheory with all * remaining variables as bindings. Returns <tt>true</tt> iff no domains are wiped out. * * @param rule the instantiated constraint rule * @param remainingRuleVariables the variables left to instantiate in the constraint rule * @param bindings the list of bindings instantiated so far * @param level the current level of solution search depth * @param currentBinding the current variable and bound value * @return <tt>true</tt> iff no remaining variable domains are wiped out *//* w w w . j a v a 2 s .c o m*/ protected boolean checkForwardInstantiatedRule(CycList instantiatedRule, ArrayList remainingRuleVariables, ArrayList bindings, int level, Binding currentBinding) throws IOException { CycVariable selectedVariable = currentBinding.getCycVariable(); if (remainingRuleVariables.size() == 0) { // This is the terminating recursion case, with no more variables left to instantiate. boolean instantiatedRuleResult = ConstraintRule.evaluateConstraintRule(instantiatedRule); if (verbosity > 2) { System.out.println(" bindings " + bindings); System.out.println(" " + instantiatedRule.cyclify() + " --> " + instantiatedRuleResult); } if (!instantiatedRuleResult) { CycVariable variable; Object value; for (int i = 0; i < bindings.size(); i++) { Binding binding = (Binding) bindings.get(i); variable = binding.getCycVariable(); if (!variable.equals(selectedVariable)) { value = binding.getValue(); if (verbosity > 6) System.out.println( " " + binding.cyclify() + " is ruled out by " + currentBinding.cyclify()); valueDomains.markDomain(variable, value, new Integer(level)); if (valueDomains.isDomainWipedOut(variable)) { if (verbosity > 6) System.out.println(" domain wiped out for " + variable); return false; } } } } return true; } else { // Recurse to instantiate the remaining variables. CycVariable variable = (CycVariable) remainingRuleVariables.get(0); ArrayList domainValues = valueDomains.getUnmarkedDomainValues(variable); int limit = valueDomains.getUnmarkedDomainSize(variable); if (verbosity > 4) { System.out.println("variable " + variable); System.out.println(" domain " + domainValues); System.out.println(" limit " + limit); } Object value; CycList newInstantiatedRule; for (int i = 0; i < limit; i++) { value = domainValues.get(i); Binding newCurrentBinding = new Binding(variable, value); ArrayList newBindings = new ArrayList(); newBindings.addAll(bindings); newBindings.add(new Binding(variable, value)); newInstantiatedRule = instantiatedRule.subst(value, variable); if (verbosity > 4) System.out.println(" instantiated rule\n " + newInstantiatedRule.cyclify()); ArrayList newRemainingRuleVariables = (ArrayList) remainingRuleVariables.clone(); newRemainingRuleVariables.remove(0); if (!checkForwardInstantiatedRule(newInstantiatedRule, newRemainingRuleVariables, newBindings, level, currentBinding)) { return false; } } } return true; }