List of usage examples for java.util Deque add
boolean add(E e);
From source file:org.alfresco.repo.search.impl.lucene.ADMLuceneIndexerImpl.java
public int updateFullTextSearch(int size) throws LuceneIndexException { checkAbleToDoWork(IndexUpdateStatus.ASYNCHRONOUS); if (getLuceneConfig().isContentIndexingEnabled() == false) { return 0; }//from w ww . j a va 2s .c o m // if (!mainIndexExists()) // { // remainingCount = size; // return; // } try { toFTSIndex = new LinkedHashMap<String, Deque<Helper>>(size * 2); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.add(new TermQuery(new Term("FTSSTATUS", "Dirty")), Occur.SHOULD); booleanQuery.add(new TermQuery(new Term("FTSSTATUS", "New")), Occur.SHOULD); int count = 0; Searcher searcher = null; try { searcher = getSearcher(null); // commit on another thread - appears like there is no index ...try later if (searcher == null) { remainingCount = size; return 0; } Hits hits; try { hits = searcher.search(booleanQuery); } catch (IOException e) { throw new LuceneIndexException( "Failed to execute query to find content which needs updating in the index", e); } for (int i = 0; i < hits.length(); i++) { Document doc = hits.doc(i); // For backward compatibility with existing indexes, cope with FTSSTATUS being stored directly on // the real document without an FTSREF Field ftsRef = doc.getField("FTSREF"); String id = doc.getField("ID").stringValue(); String ref = ftsRef == null ? id : ftsRef.stringValue(); Helper helper = new Helper(id, doc.getField("TX").stringValue()); Deque<Helper> helpers = toFTSIndex.get(ref); if (helpers == null) { helpers = new LinkedList<Helper>(); toFTSIndex.put(ref, helpers); count++; } helpers.add(helper); if (count >= size) { break; } } count = hits.length(); } finally { if (searcher != null) { try { searcher.close(); } catch (IOException e) { throw new LuceneIndexException("Failed to close searcher", e); } } } if (toFTSIndex.size() > 0) { checkAbleToDoWork(IndexUpdateStatus.ASYNCHRONOUS); IndexWriter writer = null; try { writer = getDeltaWriter(); int done = 0; for (Map.Entry<String, Deque<Helper>> entry : toFTSIndex.entrySet()) { // Document document = helper.document; NodeRef ref = new NodeRef(entry.getKey()); done += entry.getValue().size(); List<Document> docs; try { docs = readDocuments(ref.toString(), FTSStatus.Clean, true, false, false, null, null, null, null); } catch (Throwable t) { // Try to recover from failure s_logger.error("FTS index of " + ref + " failed. Reindexing without FTS", t); docs = readDocuments(ref.toString(), FTSStatus.Clean, false, false, false, null, null, null, null); } for (Document doc : docs) { try { writer.addDocument(doc /* * TODO: Select the language based analyser */); } catch (IOException e) { throw new LuceneIndexException("Failed to add document while updating fts index", e); } } if (writer.docCount() > size) { break; } } remainingCount = count - done; return done; } finally { if (writer != null) { closeDeltaWriter(); } } } else { return 0; } } catch (IOException e) { setRollbackOnly(); throw new LuceneIndexException("Failed FTS update", e); } catch (LuceneIndexException e) { setRollbackOnly(); throw new LuceneIndexException("Failed FTS update", e); } }
From source file:org.openscore.lang.compiler.modeller.ExecutableBuilder.java
private Workflow compileWorkFlow(List<Map<String, Map<String, Object>>> workFlowRawData, Map<String, String> imports, Workflow onFailureWorkFlow, boolean onFailureSection) { Deque<Task> tasks = new LinkedList<>(); Validate.notEmpty(workFlowRawData, "Flow must have tasks in its workflow"); PeekingIterator<Map<String, Map<String, Object>>> iterator = new PeekingIterator<>( workFlowRawData.iterator()); boolean isOnFailureDefined = onFailureWorkFlow != null; String defaultFailure = isOnFailureDefined ? onFailureWorkFlow.getTasks().getFirst().getName() : FAILURE_RESULT;// w ww . j a v a 2 s .co m Set<String> taskNames = new HashSet<>(); while (iterator.hasNext()) { Map<String, Map<String, Object>> taskRawData = iterator.next(); Map<String, Map<String, Object>> nextTaskData = iterator.peek(); String taskName = taskRawData.keySet().iterator().next(); if (taskNames.contains(taskName)) { throw new RuntimeException("Task name: \'" + taskName + "\' appears more than once in the workflow. Each task name in the workflow must be unique"); } taskNames.add(taskName); Map<String, Object> taskRawDataValue; String message = "Task: " + taskName + " syntax is illegal.\nBelow task name, there should be a map of values in the format:\ndo:\n\top_name:"; try { taskRawDataValue = taskRawData.values().iterator().next(); if (MapUtils.isNotEmpty(taskRawDataValue) && taskRawDataValue.containsKey(LOOP_KEY)) { message = "Task: " + taskName + " syntax is illegal.\nBelow the 'loop' keyword, there should be a map of values in the format:\nfor:\ndo:\n\top_name:"; taskRawDataValue.putAll((Map<String, Object>) taskRawDataValue.remove(LOOP_KEY)); } } catch (ClassCastException ex) { throw new RuntimeException(message); } String defaultSuccess; if (nextTaskData != null) { defaultSuccess = nextTaskData.keySet().iterator().next(); } else { defaultSuccess = onFailureSection ? FAILURE_RESULT : SUCCESS_RESULT; } Task task = compileTask(taskName, taskRawDataValue, defaultSuccess, imports, defaultFailure); tasks.add(task); } if (isOnFailureDefined) { tasks.addAll(onFailureWorkFlow.getTasks()); } return new Workflow(tasks); }
From source file:org.olat.core.util.i18n.I18nManager.java
/** * Internal helper to resolve keys within the given value. The optional * currentProperties can be used to improve performance when looking up * something in the current properties file * /* ww w .j av a 2 s . co m*/ * @param locale * @param bundleName * @param key * @param currentProperties * @param overlayEnabled true: lookup first in overlay; false: don't lookup in overlay * @param recursionLevel * @param recursionLevel the current recursion level. Incremented within this * method * @return the resolved value */ private String resolveValuesInternalKeys(Locale locale, String bundleName, String key, Properties currentProperties, boolean overlayEnabled, int recursionLevel, String value) { if (recursionLevel > 9) { log.warn("Terminating resolving of properties after 10 levels, stopped in bundle::" + bundleName + " and key::" + key); return value; } recursionLevel++; StringBuilder resolvedValue = new StringBuilder(); int lastPos = 0; Matcher matcher = resolvingKeyPattern.matcher(value); while (matcher.find()) { resolvedValue.append(value.substring(lastPos, matcher.start())); String toResolvedBundle = matcher.group(1); String toResolvedKey = matcher.group(2); if (toResolvedBundle == null || toResolvedBundle.equals("")) { // $:my.key is valid syntax, points to $current.bundle:my.key toResolvedBundle = bundleName; } if (toResolvedBundle.equals(bundleName) && currentProperties != null) { // Resolve within bundle String resolvedKey = currentProperties.getProperty(toResolvedKey); if (resolvedKey == null) { // Not found, use original (added in next iteration) lastPos = matcher.start(); } else { resolvedValue.append(resolveValuesInternalKeys(locale, bundleName, toResolvedKey, currentProperties, overlayEnabled, recursionLevel, resolvedKey)); lastPos = matcher.end(); } } else { // Resolve using other bundle String resolvedKey = getLocalizedString(toResolvedBundle, toResolvedKey, null, locale, overlayEnabled, true, true, true, false, recursionLevel); if (StringHelper.containsNonWhitespace(resolvedKey)) { resolvedValue.append(resolvedKey); lastPos = matcher.end(); } else { // Not found, use original (added in next iteration) lastPos = matcher.start(); } } // add resolved key to references index if (cachingEnabled) { String identifyer = buildI18nItemIdentifyer(toResolvedBundle, toResolvedKey); Deque<String> referencingBundles = referencingBundlesIndex.get(identifyer); if (referencingBundles == null) { Deque<String> newReferencingBundles = new ArrayDeque<>(); referencingBundles = referencingBundlesIndex.putIfAbsent(identifyer, newReferencingBundles); if (referencingBundles == null) { referencingBundles = newReferencingBundles; } } referencingBundles.add(bundleName); } } // Add rest of value resolvedValue.append(value.substring(lastPos)); return resolvedValue.toString(); }
From source file:org.ciasaboark.tacere.database.DatabaseInterface.java
public Deque<EventInstance> getAllActiveEvents() { //TODO better SQL select Deque<EventInstance> events = new ArrayDeque<EventInstance>(); String whereClause = Columns.EFFECTIVE_END + " > ? AND " + Columns.BEGIN + " < ?"; long beginTime = System.currentTimeMillis() - (EventInstance.MILLISECONDS_IN_MINUTE * (long) prefs.getBufferMinutes()); long endTime = System.currentTimeMillis() + (EventInstance.MILLISECONDS_IN_MINUTE * (long) prefs.getBufferMinutes()); String[] whereArgs = new String[] { String.valueOf(beginTime), String.valueOf(endTime) }; Cursor cursor = null;//from www . ja v a 2 s. c o m try { cursor = eventsDB.query(EventDatabaseOpenHelper.TABLE_EVENTS, LOCAL_DB_PROJECTION, whereClause, whereArgs, null, null, null); while (cursor.moveToNext()) { long id = cursor.getLong(LOCAL_DB_PROJECTION_ID); long calId = cursor.getLong(LOCAL_DB_PROJECTION_CAL_ID); long eventId = cursor.getLong(LOCAL_DB_PROJECTION_EVENT_ID); long begin = cursor.getLong(LOCAL_DB_PROJECTION_BEGIN); long end = cursor.getLong(LOCAL_DB_PROJECTION_ORIGINAL_END); String title = cursor.getString(LOCAL_DB_PROJECTION_TITLE); String description = cursor.getString(LOCAL_DB_PROJECTION_DESCRIPTION); String location = cursor.getString(LOCAL_DB_PROJECTION_LOCATION); int displayColor = cursor.getInt(LOCAL_DB_PROJECTION_DISPLAY_COLOR); boolean isAllDay = cursor.getInt(LOCAL_DB_PROJECTION_ALLDAY) == 1; boolean isAvailable = cursor.getInt(LOCAL_DB_PROJECTION_AVAILABLE) == 1; int ringerInt = cursor.getInt(LOCAL_DB_PROJECTION_RINGER); RingerType ringerType = RingerType.getTypeForInt(ringerInt); int extendMinutes = cursor.getInt(LOCAL_DB_PROJECTION_EXTEND_MINUTES); EventInstance e = new EventInstance(calId, id, eventId, title, begin, end, description, displayColor, isAvailable, isAllDay, extendMinutes); e.setLocation(location); e.setRingerType(ringerType); if (e.isActiveBetween(beginTime, endTime)) { events.add(e); } } } catch (Exception e) { Log.d(TAG, "error getting cursor for active events"); } finally { if (cursor != null) { cursor.close(); } } return events; }
From source file:de.uni_potsdam.hpi.asg.logictool.mapping.SequenceBasedAndGateDecomposer.java
private void getNewSteps(IOBehaviourSimulationStep step, Signal sig, Set<IOBehaviour> newSequences, Deque<IOBehaviourSimulationStep> newSteps, Set<Signal> relevant) { int occurrences = Collections.frequency(step.getStates(), step.getNextState()); if (occurrences >= 2) { boolean isLoop = false; int[] a = new int[occurrences]; int index = 0; for (int i = step.getStates().size() - 1; i >= 0; i--) { if (step.getStates().get(i) == step.getNextState()) { a[index++] = i;/* ww w . ja v a 2 s . c o m*/ } } Map<Integer, List<State>> lists = new HashMap<>(); int endindex = step.getStates().size(); List<State> xlist = null; for (int startindex : a) { xlist = step.getStates().subList(startindex, endindex); lists.put(endindex, xlist); endindex = startindex; } boolean finished = false; int smallesidloop = -1; for (Entry<Integer, List<State>> l1 : lists.entrySet()) { for (Entry<Integer, List<State>> l2 : lists.entrySet()) { if (l1.getKey() != l2.getKey()) { if (l1.getValue().equals(l2.getValue())) { // System.out.println("loop: listmatch!"); isLoop = true; smallesidloop = l1.getKey() < l2.getKey() ? l1.getKey() : l2.getKey(); xlist = l1.getValue(); finished = true; break; } } } if (finished) { break; } } if (isLoop) { // System.out.println("Loop: " + xlist + ", listsize: " + lists.size()); // System.out.println("Smallestid : " + smallesidloop + ", size: " + step.getStates().size()); step.findStateAndClean(step.getStates().size() - smallesidloop - 1, pool, newSteps); return; } } for (Entry<Transition, State> entry : step.getNextState().getNextStates().entrySet()) { //System.out.println(entry.toString()); if (entry.getKey().getSignal() == sig) { List<Transition> seq = new ArrayList<>(step.getSequence()); IOBehaviour beh = new IOBehaviour(seq, step.getStart(), step.getNextState()); newSequences.add(beh); } else { IOBehaviourSimulationStep newStep; try { newStep = pool.borrowObject(); } catch (Exception e) { e.printStackTrace(); logger.error("Could not borrow object"); return; } newStep.getSequence().addAll(step.getSequence()); if (relevant.contains(entry.getKey().getSignal())) { newStep.getSequence().add(entry.getKey()); } newStep.setStart(step.getStart()); newStep.setNextState(entry.getValue()); newStep.getStates().addAll(step.getStates()); newStep.getStates().add(step.getNextState()); newStep.setPrevStep(step); step.getNextSteps().add(newStep); newSteps.add(newStep); } } step.killIfCan(pool); }
From source file:io.cloudslang.lang.compiler.modeller.ExecutableBuilder.java
private WorkflowModellingResult compileWorkFlow(List<Map<String, Map<String, Object>>> workFlowRawData, Map<String, String> imports, Workflow onFailureWorkFlow, boolean onFailureSection, String namespace, SensitivityLevel sensitivityLevel) { List<RuntimeException> errors = new ArrayList<>(); Deque<Step> steps = new LinkedList<>(); Set<String> stepNames = new HashSet<>(); Deque<Step> onFailureSteps = !(onFailureSection || onFailureWorkFlow == null) ? onFailureWorkFlow.getSteps() : new LinkedList<Step>(); List<String> onFailureStepNames = getStepNames(onFailureSteps); boolean onFailureStepFound = onFailureStepNames.size() > 0; String defaultFailure = onFailureStepFound ? onFailureStepNames.get(0) : ScoreLangConstants.FAILURE_RESULT; PeekingIterator<Map<String, Map<String, Object>>> iterator = new PeekingIterator<>( workFlowRawData.iterator()); while (iterator.hasNext()) { Map<String, Map<String, Object>> stepRawData = iterator.next(); String stepName = getStepName(stepRawData); validateStepName(stepName, errors); if (stepNames.contains(stepName) || onFailureStepNames.contains(stepName)) { errors.add(new RuntimeException("Step name: \'" + stepName + "\' appears more than once in the workflow. " + UNIQUE_STEP_NAME_MESSAGE_SUFFIX)); }/* w ww . ja va2s.com*/ stepNames.add(stepName); Map<String, Object> stepRawDataValue; String message = "Step: " + stepName + " syntax is illegal.\nBelow step name, there should " + "be a map of values in the format:\ndo:\n\top_name:"; try { stepRawDataValue = stepRawData.values().iterator().next(); if (MapUtils.isNotEmpty(stepRawDataValue)) { boolean loopKeyFound = stepRawDataValue.containsKey(LOOP_KEY); boolean parallelLoopKeyFound = stepRawDataValue.containsKey(PARALLEL_LOOP_KEY); if (loopKeyFound) { if (parallelLoopKeyFound) { errors.add(new RuntimeException( "Step: " + stepName + " syntax is illegal.\nBelow step name, " + "there can be either \'loop\' or \'aync_loop\' key.")); } message = "Step: " + stepName + " syntax is illegal.\nBelow the 'loop' keyword, there " + "should be a map of values in the format:\nfor:\ndo:\n\top_name:"; @SuppressWarnings("unchecked") Map<String, Object> loopRawData = (Map<String, Object>) stepRawDataValue.remove(LOOP_KEY); stepRawDataValue.putAll(loopRawData); } if (parallelLoopKeyFound) { message = "Step: " + stepName + " syntax is illegal.\nBelow the 'parallel_loop' keyword, there " + "should be a map of values in the format:\nfor:\ndo:\n\top_name:"; @SuppressWarnings("unchecked") Map<String, Object> parallelLoopRawData = (Map<String, Object>) stepRawDataValue .remove(PARALLEL_LOOP_KEY); errors.addAll(preCompileValidator.checkKeyWords(stepName, SlangTextualKeys.PARALLEL_LOOP_KEY, parallelLoopRawData, Collections.emptyList(), parallelLoopValidKeywords, null)); parallelLoopRawData.put(PARALLEL_LOOP_KEY, parallelLoopRawData.remove(FOR_KEY)); stepRawDataValue.putAll(parallelLoopRawData); } } } catch (ClassCastException ex) { stepRawDataValue = new HashMap<>(); errors.add(new RuntimeException(message)); } String defaultSuccess; Map<String, Map<String, Object>> nextStepData = iterator.peek(); if (nextStepData != null) { defaultSuccess = nextStepData.keySet().iterator().next(); } else { defaultSuccess = onFailureSection ? ScoreLangConstants.FAILURE_RESULT : SUCCESS_RESULT; } String onFailureStepName = onFailureStepFound ? onFailureStepNames.get(0) : null; StepModellingResult stepModellingResult = compileStep(stepName, stepRawDataValue, defaultSuccess, imports, defaultFailure, namespace, onFailureStepName, onFailureSection, sensitivityLevel); errors.addAll(stepModellingResult.getErrors()); steps.add(stepModellingResult.getStep()); } if (onFailureStepFound) { steps.addAll(onFailureSteps); } return new WorkflowModellingResult(new Workflow(steps), errors); }