List of usage examples for java.util Stack Stack
public Stack()
From source file:com.bluexml.xforms.controller.alfresco.agents.MappingAgent.java
/** * Creates or loads the instance for a default class form. * /* ww w . j a va 2 s. c om*/ * @param transaction * the transaction * @param type * the content type * @param id * the id * @param initParams * the init params * @param idAsServlet * whether the request comes from a servlet * * @return the class * * @throws ServletException * the alfresco controller exception */ public Document getInstanceClass(AlfrescoTransaction transaction, String type, String id, boolean formIsReadOnly, boolean isServletRequest) throws ServletException { Document instance = null; try { if (id == null) { instance = createClassFormsInstance(transaction, type, formIsReadOnly, isServletRequest); } else { instance = controller.getObjectInstance(transaction, id, new Stack<AssociationType>(), formIsReadOnly, isServletRequest); } } catch (ServletException se) { throw se; // just propagate } catch (Exception e) { throw new ServletException(e); } return instance; }
From source file:com.google.dart.compiler.metrics.Tracer.java
private ThreadLocal<Stack<TraceEvent>> initPendingEvents() { return new ThreadLocal<Stack<TraceEvent>>() { @Override//from w w w. j av a2 s. c o m protected Stack<TraceEvent> initialValue() { return new Stack<TraceEvent>(); } }; }
From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java
/** * Perform a selection query that retrieves all points in the given range. * The range is specified in the two-dimensional array positions. * @param in/* w w w .j a v a 2 s . c om*/ * @param query_mbr * @return * @throws IOException */ public static Node aggregateQuery(FSDataInputStream in, Rectangle query_mbr) throws IOException { long treeStartPosition = in.getPos(); Node result = new Node(); int numOfSelectedRecords = 0; int resolution = in.readInt(); short fillValue = in.readShort(); int cardinality = in.readInt(); final Vector<Integer> selectedNodesPos = new Vector<Integer>(); final Vector<Integer> selectedStarts = new Vector<Integer>(); final Vector<Integer> selectedEnds = new Vector<Integer>(); StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution); // Nodes to be searched. Contains node positions in the array of nodes Stack<Integer> nodes_2b_searched = new Stack<Integer>(); nodes_2b_searched.add(0); // Root node (ID=1) Rectangle node_mbr = new Rectangle(); while (!nodes_2b_searched.isEmpty()) { int node_pos = nodes_2b_searched.pop(); stockQuadTree.getNodeMBR(node_pos, node_mbr); if (query_mbr.contains(node_mbr)) { // Add this node to the selection list and stop this branch selectedNodesPos.add(node_pos); } else if (query_mbr.intersects(node_mbr)) { int first_child_id = stockQuadTree.nodesID[node_pos] * 4 + 0; int first_child_pos = Arrays.binarySearch(stockQuadTree.nodesID, first_child_id); if (first_child_pos < 0) { // No children. Hit a leaf node // Scan and add matching points only java.awt.Point record_coords = new Point(); for (int record_pos = stockQuadTree.nodesStartPosition[node_pos]; record_pos < stockQuadTree.nodesEndPosition[node_pos]; record_pos++) { stockQuadTree.getRecordCoords(record_pos, record_coords); if (query_mbr.contains(record_coords)) { // matched a record. if (!selectedEnds.isEmpty() && selectedEnds.lastElement() == record_pos) { // Merge with an adjacent range selectedEnds.set(selectedEnds.size() - 1, record_pos + 1); } else { // Add a new range of unit width selectedStarts.add(record_pos); selectedEnds.add(record_pos + 1); } numOfSelectedRecords++; } } } else { // Non-leaf node. Add all children to the list of nodes to search // Add in reverse order to the stack so that results come in sorted order nodes_2b_searched.add(first_child_pos + 3); nodes_2b_searched.add(first_child_pos + 2); nodes_2b_searched.add(first_child_pos + 1); nodes_2b_searched.add(first_child_pos + 0); } } } // Result 1: Accumulate all values // Sort disk offsets to eliminate backward seeks if (!selectedStarts.isEmpty()) { LOG.debug("Aggregate query selected " + selectedNodesPos.size() + " nodes and " + numOfSelectedRecords + " records"); final IndexedSortable sortable = new IndexedSortable() { @Override public int compare(int i, int j) { return selectedStarts.get(i) - selectedStarts.get(j); } @Override public void swap(int i, int j) { int temp = selectedStarts.get(i); selectedStarts.set(i, selectedStarts.get(j)); selectedStarts.set(j, temp); temp = selectedEnds.get(i); selectedEnds.set(i, selectedEnds.get(j)); selectedEnds.set(j, temp); } }; new QuickSort().sort(sortable, 0, selectedStarts.size()); long dataStartPosition = getValuesStartOffset(cardinality); Point resultCoords = new Point(); // Return all values in the selected ranges for (int iRange = 0; iRange < selectedStarts.size(); iRange++) { int treeStart = selectedStarts.get(iRange); int treeEnd = selectedEnds.get(iRange); long startPosition = dataStartPosition + selectedStarts.get(iRange) * cardinality * 2; in.seek(startPosition); for (int treePos = treeStart; treePos < treeEnd; treePos++) { // Retrieve the coords for the point at treePos stockQuadTree.getRecordCoords(treePos, resultCoords); // Read all entries at current position for (int iValue = 0; iValue < cardinality; iValue++) { short value = in.readShort(); if (value != fillValue) result.accumulate(value); } } } } // Result 2: Accumulate all nodes if (!selectedNodesPos.isEmpty()) { long nodesStartPosition = treeStartPosition + getNodesStartOffset(resolution, cardinality); // Sort node positions to eliminate backward seeks IndexedSortable nodeSortable = new IndexedSortable() { @Override public int compare(int i, int j) { return selectedNodesPos.get(i) - selectedNodesPos.get(j); } @Override public void swap(int i, int j) { int temp = selectedNodesPos.get(i); selectedNodesPos.set(i, selectedNodesPos.get(j)); selectedNodesPos.set(j, temp); } }; new QuickSort().sort(nodeSortable, 0, selectedNodesPos.size()); Node selectedNode = new Node(); for (int node_pos : selectedNodesPos) { long nodePosition = nodesStartPosition + node_pos * NodeSize; in.seek(nodePosition); selectedNode.readFields(in); result.accumulate(selectedNode); } } return result; }
From source file:com.zeroio.webdav.WebdavServlet.java
/** * PROPFIND Method.//from w ww . j a va 2 s.co m * * @param context Description of the Parameter * @throws ServletException Description of the Exception * @throws IOException Description of the Exception */ protected void doPropfind(ActionContext context) throws ServletException, IOException { String path = getRelativePath(context.getRequest()); //fix for windows clients if (path.equals("/files")) { path = ""; } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) { context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN); return; } if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) { //Fix for MACOSX finder. Do not allow requests for files starting with a period return; } //System.out.println("METHOD PROPFIND....PATH: " + path); // Properties which are to be displayed. Vector properties = null; // Propfind depth by default 1 for performance reasons int depth = 1; // Propfind type int type = FIND_ALL_PROP; String depthStr = context.getRequest().getHeader("Depth"); if (depthStr == null) { depth = INFINITY; } else { if (depthStr.equals("0")) { depth = 0; } else if (depthStr.equals("1")) { depth = 1; } else if (depthStr.equals("infinity")) { depth = INFINITY; } } /* * Read the request xml and determine all the properties */ Node propNode = null; DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource(context.getRequest().getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: if (currentNode.getNodeName().endsWith("prop")) { type = FIND_BY_PROPERTY; propNode = currentNode; } if (currentNode.getNodeName().endsWith("propname")) { type = FIND_PROPERTY_NAMES; } if (currentNode.getNodeName().endsWith("allprop")) { type = FIND_ALL_PROP; } break; } } } catch (Exception e) { // Most likely there was no content : we use the defaults. // TODO : Enhance that ! //e.printStackTrace(System.out); } if (type == FIND_BY_PROPERTY) { properties = new Vector(); if (!properties.contains("creationdate")) { //If the request did not contain creationdate property then add this to requested properties //to make the information available for clients properties.addElement("creationdate"); } NodeList childList = propNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); String propertyName = null; if (nodeName.indexOf(':') != -1) { propertyName = nodeName.substring(nodeName.indexOf(':') + 1); } else { propertyName = nodeName; } // href is a live property which is handled differently properties.addElement(propertyName); break; } } } // Properties have been determined // Retrieve the resources Connection db = null; boolean exists = true; boolean status = true; Object current = null; Object child = null; ModuleContext resources = null; SystemStatus thisSystem = null; StringBuffer xmlsb = new StringBuffer(); try { db = this.getConnection(context); resources = getCFSResources(db, context); if (resources == null) { context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } thisSystem = this.getSystemStatus(context); current = resources.lookup(thisSystem, db, path); if (current instanceof ModuleContext) { //System.out.println( ((ModuleContext) current).toString()); } } catch (NamingException e) { //e.printStackTrace(System.out); exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector currentLockNullResources = (Vector) lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = (String) lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS); context.getResponse().setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING); parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type, properties); generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); //e.printStackTrace(System.out); return; } } } } } catch (SQLException e) { e.printStackTrace(System.out); context.getResponse().sendError(CFS_SQLERROR, e.getMessage()); status = false; } finally { this.freeConnection(db, context); } if (!status) { return; } if (!exists) { context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, path); return; } context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS); context.getResponse().setContentType("text/xml; charset=UTF-8"); // Create multistatus object ////System.out.println("Creating Multistatus Object"); XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING); //System.out.println("Depth: " + depth); if (depth == 0) { parseProperties(context, resources, generatedXML, path, type, properties); } else { // The stack always contains the object of the current level Stack stack = new Stack(); stack.push(path); // Stack of the objects one level below Stack stackBelow = new Stack(); while ((!stack.isEmpty()) && (depth >= 0)) { String currentPath = (String) stack.pop(); try { if (!currentPath.equals(path)) { //object at url currentPath not yet looked up. so perform lookup at url currentPath child = resources.lookup(currentPath); parseProperties(context, resources, generatedXML, currentPath, type, properties); } } catch (NamingException e) { e.printStackTrace(System.out); continue; } if (!status) { return; } if ((current instanceof ModuleContext) && depth > 0) { // Get a list of all the resources at the current path and store them // in the stack try { NamingEnumeration enum1 = ((ModuleContext) current).list(""); int count = 0; while (enum1.hasMoreElements()) { NameClassPair ncPair = (NameClassPair) enum1.nextElement(); String newPath = currentPath; if (!(newPath.endsWith("/"))) { newPath += "/"; } newPath += ncPair.getName(); //System.out.println("STACKING CHILD: " + newPath); stackBelow.push(newPath); count++; } if (currentPath.equals(path) && count == 0) { // This directory does not have any files or folders. //System.out.println("DIRECTORY HAS NO FILES OR FOLDERS..."); parseProperties(context, resources, generatedXML, properties); } } catch (NamingException e) { //e.printStackTrace(System.out); context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } // Displaying the lock-null resources present in that collection String lockPath = currentPath; if (lockPath.endsWith("/")) { lockPath = lockPath.substring(0, lockPath.length() - 1); } Vector currentLockNullResources = (Vector) lockNullResources.get(lockPath); if (currentLockNullResources != null) { Enumeration lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = (String) lockNullResourcesList.nextElement(); System.out.println("Lock null path: " + lockNullPath); parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type, properties); } } } if (stack.isEmpty()) { depth--; stack = stackBelow; stackBelow = new Stack(); } xmlsb.append(generatedXML.toString()); //System.out.println("xml : " + generatedXML.toString()); generatedXML.sendData(); } } Iterator locks = lockNullResources.keySet().iterator(); while (locks.hasNext()) { String lockpath = (String) locks.next(); //System.out.println("LOCK PATH: " + lockpath); } generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING); xmlsb.append(generatedXML.toString()); generatedXML.sendData(); //System.out.println("xml: " + xmlsb.toString()); }
From source file:com.aurel.track.exchange.excel.ExcelImportBL.java
/** * Get the workItems list and validate if all the fields of the excel sheet * are correct// ww w . j a va2 s .c om * * @param workbook * @param selectedSheet * @param personID * @param locale * @param columnIndexToFieldIDMap * @param fieldIDToColumnIndexMap * @param lastSavedIdentifierFieldIDIsSet * @param defaultValuesMap * @param invalidValueHandlingMap * @param gridErrorsMap * @param rowErrorsMap * @return */ static SortedMap<Integer, TWorkItemBean> getAndValidateGridData(Workbook workbook, Integer selectedSheet, Integer personID, Locale locale, Map<Integer, Integer> columnIndexToFieldIDMap, Map<Integer, Integer> fieldIDToColumnIndexMap, Set<Integer> lastSavedIdentifierFieldIDIsSet, Map<Integer, Integer> defaultValuesMap, Map<Integer, Integer> invalidValueHandlingMap, Map<Integer, Map<Integer, List<Integer>>> rowNoToPseudoFieldsOriginal, Map<Integer, Map<Integer, List<Integer>>> rowNoToPseudoFieldsExcel, Map<Integer, SortedMap<Integer, SortedMap<String, ErrorData>>> gridErrorsMap, Map<Integer, SortedSet<Integer>> rowErrorsMap, Map<Integer, SortedSet<Integer>> requiredFieldErrorsMap, Map<Integer, Integer> rowToParentRow) { SortedMap<Integer, TWorkItemBean> workItemBeansMap = new TreeMap<Integer, TWorkItemBean>(); Sheet sheet = workbook.getSheetAt(selectedSheet.intValue()); // get the column indexes for project and issueType Integer projectColumn = fieldIDToColumnIndexMap.get(SystemFields.INTEGER_PROJECT); Integer issueTypeColumn = fieldIDToColumnIndexMap.get(SystemFields.INTEGER_ISSUETYPE); // Maps to spare additional database accesses for default values Map<Integer, String> defaultShowValuesMap = new HashMap<Integer, String>(); Map<Integer, String> defaultLocalizedFieldLabels = new HashMap<Integer, String>(); Integer originalProject = null; Integer originalIssueType = null; Set<Integer> mandatoryIdentifierFields = ExcelFieldMatchBL.getMandatoryIdentifierFields(); Map<Integer, Map<String, ILabelBean>> systemLookups = loadBaseLookups(personID, locale); Map<String, ILabelBean> projectLookups = systemLookups.get(SystemFields.INTEGER_PROJECT); Map<Integer, Map<Integer, Map<String, ILabelBean>>> projectSpecificLookups = null; if (projectLookups != null) { projectSpecificLookups = loadProjectLookups(GeneralUtils .createIntegerListFromBeanList(GeneralUtils.createListFromCollection(projectLookups.values()))); } boolean projectSpecificIDsActive = ApplicationBean.getInstance().getSiteBean().getProjectSpecificIDsOn(); Map<Integer, TProjectBean> projectBeansMap = new HashMap<Integer, TProjectBean>(); if (projectSpecificIDsActive) { List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personID); if (projectBeans != null) { for (TProjectBean projectBean : projectBeans) { Integer projectID = projectBean.getObjectID(); projectBeansMap.put(projectID, projectBean); String label = projectBean.getLabel(); String projectPrefix = projectBean.getPrefix(); if (projectPrefix == null || "".equals(projectPrefix)) { LOGGER.info("The project " + label + " with ID " + projectID + " has no prefix, consquently project specific item numbers might not be recognized"); } } } } /** * Process the rows only to gather the projects to issueTypes to get the * roles and restrictions once for all issues */ Map<Integer, Set<Integer>> projectToIssueTypesMap = new HashMap<Integer, Set<Integer>>(); for (Row row : sheet) { int rowNum = row.getRowNum(); if (rowNum == 0) { // only the data rows are processed (the header row is not // important now) continue; } SerializableBeanAllowedContext serializableBeanAllowedContext = new SerializableBeanAllowedContext(); serializableBeanAllowedContext.setPersonID(personID); serializableBeanAllowedContext.setNew(true); // get the project and issueType first because the other fields // could depend on these issueTypes // process the project column Integer projectID = null; if (projectColumn != null) { try { projectID = (Integer) getAttributeValue(row.getCell(projectColumn), SystemFields.INTEGER_PROJECT, null, serializableBeanAllowedContext, locale, invalidValueHandlingMap, systemLookups, projectSpecificLookups); } catch (Exception e) { } } if (projectID == null) { // no project column exists on the sheet: take the default value // which is // surely specified, otherwise it would fail at // validateRequiredColumns() projectID = defaultValuesMap.get(SystemFields.INTEGER_PROJECT); } if (projectID != null) { serializableBeanAllowedContext.setProjectID(projectID); } // process the issueType column Integer issueTypeID = null; if (issueTypeColumn != null) { try { issueTypeID = (Integer) getAttributeValue(row.getCell(issueTypeColumn), SystemFields.INTEGER_ISSUETYPE, null, serializableBeanAllowedContext, locale, invalidValueHandlingMap, systemLookups, projectSpecificLookups); } catch (Exception e) { } } if (issueTypeID == null) { // no issue type column exists on the sheet: take the default // value which is // surely specified, otherwise it would fail at // validateRequiredColumns() issueTypeID = defaultValuesMap.get(SystemFields.INTEGER_ISSUETYPE); } if (projectID != null) { Set<Integer> issueTypes = projectToIssueTypesMap.get(projectID); if (issueTypes == null) { issueTypes = new HashSet<Integer>(); projectToIssueTypesMap.put(projectID, issueTypes); } if (issueTypeID != null) { issueTypes.add(issueTypeID); } } } Map<Integer, Map<Integer, Map<Integer, TFieldConfigBean>>> projectsToIssueTypesToFieldConfigsMapForBottomUpFields = null; Map<Integer, Map<Integer, Map<String, Object>>> projectsIssueTypesFieldSettingsMapForBottomUpFields = null; Map<Integer, Map<Integer, Map<Integer, Integer>>> fieldRestrictions = AccessBeans .getFieldRestrictions(personID, projectToIssueTypesMap, null, true); Set<Integer> possibleBottomUpFields = FieldRuntimeBL.getPossibleBottomUpFields(); for (Iterator<Integer> iterator = possibleBottomUpFields.iterator(); iterator.hasNext();) { if (!fieldIDToColumnIndexMap.containsKey(iterator.next())) { // remove possible bottom up field if not mapped iterator.remove(); } if (!possibleBottomUpFields.isEmpty()) { // at least one bottom up date was mapped projectsToIssueTypesToFieldConfigsMapForBottomUpFields = FieldRuntimeBL .loadFieldConfigsInContextsAndTargetProjectAndIssueType(projectToIssueTypesMap, possibleBottomUpFields, locale, null, null); projectsIssueTypesFieldSettingsMapForBottomUpFields = FieldRuntimeBL .getFieldSettingsForFieldConfigs(projectsToIssueTypesToFieldConfigsMapForBottomUpFields); } } /** * now process the rows in detail one by one */ Stack<Integer> parentStack = new Stack<Integer>(); Map<Integer, Integer> rowToIndent = new HashMap<Integer, Integer>(); for (Row row : sheet) { int rowNum = row.getRowNum(); if (rowNum == 0) { // only the data rows are processed (the header row is not // important now) continue; } boolean excelValueFound = false; // whether the project column is mapped and excel value if found for // project boolean mappedProject = false; SerializableBeanAllowedContext serializableBeanAllowedContext = new SerializableBeanAllowedContext(); serializableBeanAllowedContext.setPersonID(personID); serializableBeanAllowedContext.setNew(true); // get the project and issueType first because the other fields // could depend on these issueTypes // process the project column Integer projectID = null; if (projectColumn != null) { try { projectID = (Integer) getAttributeValue(row.getCell(projectColumn), SystemFields.INTEGER_PROJECT, null, serializableBeanAllowedContext, locale, invalidValueHandlingMap, systemLookups, projectSpecificLookups); if (projectID != null) { mappedProject = true; excelValueFound = true; } } catch (ExcelImportNotExistingCellValueException e) { addGridError(gridErrorsMap, NOT_EXISTING_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(projectColumn), SystemFields.INTEGER_PROJECT, e.getMessage()); } catch (ExcelImportNotAllowedCellValueException e) { addGridError(gridErrorsMap, NOT_ALLOWED_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(projectColumn), SystemFields.INTEGER_PROJECT, e.getMessage()); } catch (ExcelImportInvalidCellValueException e) { addGridError(gridErrorsMap, INVALID_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(projectColumn), SystemFields.INTEGER_PROJECT, e.getMessage()); } } if (projectID == null) { // no project column exists on the sheet: take the default value // which is // surely specified, otherwise it would fail at // validateRequiredColumns() projectID = defaultValuesMap.get(SystemFields.INTEGER_PROJECT); } if (projectID != null) { serializableBeanAllowedContext.setProjectID(projectID); } // process the issueType column Integer issueTypeID = null; if (issueTypeColumn != null) { try { issueTypeID = (Integer) getAttributeValue(row.getCell(issueTypeColumn), SystemFields.INTEGER_ISSUETYPE, null, serializableBeanAllowedContext, locale, invalidValueHandlingMap, systemLookups, projectSpecificLookups); if (issueTypeID != null) { excelValueFound = true; } } catch (ExcelImportNotExistingCellValueException e) { addGridError(gridErrorsMap, NOT_EXISTING_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(issueTypeColumn), SystemFields.INTEGER_ISSUETYPE, e.getMessage()); } catch (ExcelImportNotAllowedCellValueException e) { addGridError(gridErrorsMap, NOT_ALLOWED_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(issueTypeColumn), SystemFields.INTEGER_ISSUETYPE, e.getMessage()); } catch (ExcelImportInvalidCellValueException e) { addGridError(gridErrorsMap, INVALID_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(issueTypeColumn), SystemFields.INTEGER_ISSUETYPE, e.getMessage()); } } if (issueTypeID == null) { // no issue type column exists on the sheet: take the default // value which is // surely specified, otherwise it would fail at // validateRequiredColumns() issueTypeID = defaultValuesMap.get(SystemFields.INTEGER_ISSUETYPE); } if (issueTypeID != null) { serializableBeanAllowedContext.setIssueTypeID(issueTypeID); } /* * gather the values for the identifier fields and try to get an * existing workItem by these fields */ Map<Integer, Object> identifierFieldValues = new HashMap<Integer, Object>(); if (lastSavedIdentifierFieldIDIsSet != null && !lastSavedIdentifierFieldIDIsSet.isEmpty()) { for (Integer fieldID : lastSavedIdentifierFieldIDIsSet) { Integer attributeFieldID = fieldID; if (SystemFields.INTEGER_ISSUENO.equals(fieldID) && projectSpecificIDsActive) { attributeFieldID = SystemFields.INTEGER_PROJECT_SPECIFIC_ISSUENO; } Object attributeValue = null; Integer columnIndex = null; try { columnIndex = fieldIDToColumnIndexMap.get(fieldID); attributeValue = getAttributeValue(row.getCell(columnIndex), attributeFieldID, null, serializableBeanAllowedContext, locale, invalidValueHandlingMap, systemLookups, projectSpecificLookups); if (attributeValue != null) { identifierFieldValues.put(fieldID, attributeValue); excelValueFound = true; } } catch (ExcelImportNotExistingCellValueException e) { if (!SystemFields.INTEGER_PROJECT.equals(fieldID) && !SystemFields.INTEGER_ISSUETYPE.equals(fieldID)) { // if project or issueType are set as identifier // fields and // have grid error they should be already collected // in gridErrorsMap addGridError(gridErrorsMap, NOT_EXISTING_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } } catch (ExcelImportNotAllowedCellValueException e) { if (!SystemFields.INTEGER_PROJECT.equals(fieldID) && !SystemFields.INTEGER_ISSUETYPE.equals(fieldID)) { // if project or issueType are set as identifier // fields and // have grid error they should be already collected // in gridErrorsMap addGridError(gridErrorsMap, NOT_ALLOWED_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } } catch (ExcelImportInvalidCellValueException e) { if (!SystemFields.INTEGER_PROJECT.equals(fieldID) && !SystemFields.INTEGER_ISSUETYPE.equals(fieldID)) { // if project or issueType are set as identifier // fields and // have grid error they should be already collected // in gridErrorsMap addGridError(gridErrorsMap, INVALID_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } } } } // always initialize the next workItem to null TWorkItemBean workItemBean = null; boolean itemIsNew = false; if (!identifierFieldValues.isEmpty()) { if (identifierFieldValues.get(SystemFields.INTEGER_ISSUENO) != null) { // is issueNo field mapped? if (projectSpecificIDsActive) { // get by project specific itemID String projectSpecificID = null; try { projectSpecificID = (String) identifierFieldValues.get(SystemFields.INTEGER_ISSUENO); } catch (Exception e) { } if (projectSpecificID != null) { // it should be trimmed because in excel the child // issues are indented workItemBean = ItemBL.loadWorkItemByProjectSpecificID(projectID, mappedProject, projectBeansMap, projectSpecificID.trim()); if (workItemBean != null && LOGGER.isDebugEnabled()) { LOGGER.debug("WorkItem " + projectSpecificID + " from row " + rowNum + " found by projectSpecificID"); } } } else { // get by "global" workItemID Integer workItemID = null; try { workItemID = (Integer) identifierFieldValues.get(SystemFields.INTEGER_ISSUENO); } catch (Exception e) { } if (workItemID != null) { workItemBean = ItemBL.loadWorkItemSystemAttributes(workItemID); } if (workItemBean != null && LOGGER.isDebugEnabled()) { LOGGER.debug("WorkItem " + workItemID + " from row " + rowNum + " found by workItemID"); } } if (workItemBean == null) { // the issueNo field is set as identifier and the // corresponding issue does't exist, report as error addGridError(gridErrorsMap, WORKITEM_NOTEXIST_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter( fieldIDToColumnIndexMap.get(SystemFields.INTEGER_ISSUENO)), SystemFields.INTEGER_ISSUENO, identifierFieldValues.get(SystemFields.INTEGER_ISSUENO).toString()); continue; } } if (workItemBean == null) { // workItem was not found by issueNo // (issueNo field was not mapped or issueNo value is missing // from excel or // the issue's project is not accessible if // projectSpecificIDsActive) // try with user defined identifier fields try { workItemBean = ItemBL.loadWorkItemSystemAttributes(identifierFieldValues); } catch (ExcelImportNotUniqueIdentifiersException e) { addRowError(rowErrorsMap, WORKITEM_MORE_THAN_ONE_EXIST, rowNum); continue; } if (workItemBean != null && LOGGER.isDebugEnabled()) { LOGGER.debug("WorkItem from row " + rowNum + " found by user defined identifier fields"); } } if (workItemBean != null) { // existing workItem originalProject = workItemBean.getProjectID(); originalIssueType = workItemBean.getListTypeID(); // is it editable by the current person? if (!AccessBeans.isAllowedToChange(workItemBean, personID)) { addRowError(rowErrorsMap, WORKITEM_NO_EDIT_RIGHT, rowNum); continue; } // load also the custom attributes because when the workItem // will be updated // the custom attributes will also be compared to the // original value ItemBL.loadWorkItemCustomAttributes(workItemBean); serializableBeanAllowedContext.setWorkItemBeanOriginal(workItemBean); serializableBeanAllowedContext.setNew(false); // LOGGER.debug("WorkItem " + workItemBean.getObjectID() + // " from row " + rowNum + " found"); } } boolean missingRequiredFound = false; if (workItemBean == null) { // not existing found by identifier fields, create a new one workItemBean = new TWorkItemBean(); if (identifierFieldValues != null) { // preset the new workItem with the processed identifier // values for (Map.Entry<Integer, Object> identifierEntry : identifierFieldValues.entrySet()) { workItemBean.setAttribute(identifierEntry.getKey(), identifierEntry.getValue()); } } itemIsNew = true; LOGGER.debug("WorkItem from row " + rowNum + " not found. A new one will be created."); } if (projectID != null) { workItemBean.setAttribute(SystemFields.INTEGER_PROJECT, null, projectID); } else { if (itemIsNew) { // project column not mapped addRowError(requiredFieldErrorsMap, SystemFields.INTEGER_PROJECT, rowNum); missingRequiredFound = true; } } if (issueTypeID != null) { workItemBean.setAttribute(SystemFields.INTEGER_ISSUETYPE, null, issueTypeID); } else { if (itemIsNew) { // project column not mapped addRowError(requiredFieldErrorsMap, SystemFields.INTEGER_ISSUETYPE, rowNum); missingRequiredFound = true; } } if (missingRequiredFound) { continue; } Map<Integer, Integer> restrictedFields = null; projectID = workItemBean.getProjectID(); issueTypeID = workItemBean.getListTypeID(); if (projectID != null && issueTypeID != null) { Map<Integer, Map<Integer, Integer>> issueTypeRestrictions = fieldRestrictions.get(projectID); if (issueTypeRestrictions != null) { restrictedFields = issueTypeRestrictions.get(issueTypeID); } if (restrictedFields == null) { // no project or issue type mapped get the restriction now restrictedFields = AccessBeans.getFieldRestrictions(personID, projectID, issueTypeID, true); issueTypeRestrictions = new HashMap<Integer, Map<Integer, Integer>>(); issueTypeRestrictions.put(issueTypeID, restrictedFields); fieldRestrictions.put(projectID, issueTypeRestrictions); } // new values exist if (originalProject != null && originalIssueType != null) { // workItem existed if (!projectID.equals(originalProject) || !issueTypeID.equals(originalIssueType)) { if (!AccessBeans.isAllowedToChange(workItemBean, personID)) { // move not allowed addRowError(rowErrorsMap, WORKITEM_NO_EDIT_RIGHT, rowNum); continue; } } } else { // new workItem if (!AccessBeans.isAllowedToCreate(personID, projectID, issueTypeID)) { // create not allowed addRowError(rowErrorsMap, WORKITEM_NO_CREATE_RIGHT, rowNum); continue; } } } // process the remaining cells Map<Integer, Integer> rowNoToIndentLevel = new HashMap<Integer, Integer>(); for (Cell cell : row) { boolean attributeChanged = false; int columnIndex = cell.getColumnIndex(); Integer fieldID = columnIndexToFieldIDMap.get(columnIndex); Integer fieldForRestriction = fieldID; if (fieldID == null) { // LOGGER.debug("No mapping found for column " + // columnIndex); continue; } if (fieldID.equals(SystemFields.INTEGER_PROJECT) || fieldID.equals(SystemFields.INTEGER_ISSUETYPE) || identifierFieldValues.containsKey(fieldID) || mandatoryIdentifierFields.contains(fieldID)) { // these values are already read continue; } if (fieldID.intValue() < 0) { // pseudo field: now only watchers if (fieldID.intValue() == TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST || fieldID.intValue() == TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST) { fieldForRestriction = FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.WATCHERS; String watcherValue = getStringCellValue(cell); if (watcherValue == null || "".equals(watcherValue.trim())) { continue; } Map<Integer, List<Integer>> watcherMapOriginal = rowNoToPseudoFieldsOriginal.get(rowNum); if (watcherMapOriginal == null) { watcherMapOriginal = new HashMap<Integer, List<Integer>>(); rowNoToPseudoFieldsOriginal.put(rowNum, watcherMapOriginal); } List<Integer> watcherListOriginal = null; TWorkItemBean workItemBeanOriginal = serializableBeanAllowedContext .getWorkItemBeanOriginal(); if (workItemBeanOriginal != null) { if (fieldID.intValue() == TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST) { watcherListOriginal = GeneralUtils.createIntegerListFromBeanList( PersonBL.getDirectInformants(workItemBeanOriginal.getObjectID())); } else { watcherListOriginal = GeneralUtils.createIntegerListFromBeanList( PersonBL.getDirectConsultants(workItemBeanOriginal.getObjectID())); } watcherMapOriginal.put(fieldID, watcherListOriginal); } List<Integer> watcherListExcel = new LinkedList<Integer>(); String[] watcherNames = watcherValue .split("\\" + ConsultedInformedLoaderBL.WATCHER_SPLITTER_VALUES_STRING); if (watcherNames != null) { Map<Integer, List<Integer>> watcherMapExcel = rowNoToPseudoFieldsExcel.get(rowNum); if (watcherMapExcel == null) { watcherMapExcel = new HashMap<Integer, List<Integer>>(); rowNoToPseudoFieldsExcel.put(rowNum, watcherMapExcel); } watcherMapExcel.put(fieldID, watcherListExcel); for (int i = 0; i < watcherNames.length; i++) { String watcherName = watcherNames[i]; Integer objectID = null; try { objectID = getWatcherValue(watcherName, fieldID, systemLookups, watcherListOriginal, serializableBeanAllowedContext, locale); } catch (ExcelImportNotExistingCellValueException e) { addGridError(gridErrorsMap, NOT_EXISTING_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } catch (ExcelImportNotAllowedCellValueException e) { addGridError(gridErrorsMap, NOT_ALLOWED_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } if (objectID != null) { watcherListExcel.add(objectID); excelValueFound = true; } } } attributeChanged = ConsInfBL.watcherChanged(watcherListOriginal, watcherListExcel); } else { if (fieldID.intValue() == ExcelFieldMatchBL.LOCAL_PARENT_PSEUDO_COLUMN) { // local parent - child hierarchy (for new items) Integer pseudoHierarchyColumn = fieldIDToColumnIndexMap .get(ExcelFieldMatchBL.LOCAL_PARENT_PSEUDO_COLUMN); if (pseudoHierarchyColumn != null) { String hierarchyColumn = getStringCellValue(row.getCell(pseudoHierarchyColumn)); if (hierarchyColumn != null && hierarchyColumn.length() > 0) { int previousIndent = 0; if (!parentStack.isEmpty()) { Integer previousRow = parentStack.peek(); if (rowToIndent.get(previousRow) != null) { previousIndent = rowToIndent.get(previousRow).intValue(); } } int actualIndent = hierarchyColumn.length(); rowToIndent.put(rowNum, actualIndent); rowNoToIndentLevel.put(rowNum, actualIndent); if (previousIndent == actualIndent) { // sibling: same parent as the sibling's // parent if (!parentStack.isEmpty()) { // remove the sibling from stack parentStack.pop(); if (!parentStack.isEmpty()) { // if the stack is still not // empty then the peek is teh // parent Integer parentRow = parentStack.peek(); rowToParentRow.put(rowNum, parentRow); } } } else { if (actualIndent > previousIndent) { // child of the previous row if (actualIndent - previousIndent > 1) { // jump more than one in deep is // error addGridError(gridErrorsMap, INCONSISTENT_HIERARCHY_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, hierarchyColumn); } if (!parentStack.isEmpty()) { // add previous row as parent Integer parentRow = parentStack.peek(); rowToParentRow.put(rowNum, parentRow); } } else { // new hierarchy: nothing to do with // the previous row int difference = previousIndent - actualIndent; for (int i = 0; i <= difference; i++) { // pop to find the parent if (!parentStack.isEmpty()) { parentStack.pop(); } } if (!parentStack.isEmpty()) { Integer parentRow = parentStack.peek(); rowToParentRow.put(rowNum, parentRow); } } } } else { // no hierarchy string: top level item while (!parentStack.isEmpty()) { // empty the stack parentStack.pop(); } } // add row to stack for possible children parentStack.push(rowNum); } } } } else { IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID); Object attributeValue = null; if (fieldTypeRT.isComposite() || fieldTypeRT.isMultipleValues()) { String compositeOrMultipleValue = getStringCellValue(cell); if (compositeOrMultipleValue == null || "".equals(compositeOrMultipleValue.trim())) { workItemBean.setAttribute(fieldID, null, null); continue; } // we suppose that all composite and multiple values are // lookup values // TODO refactor if that is not true String[] parts; if (fieldTypeRT.isMultipleValues()) { parts = compositeOrMultipleValue .split(CustomSelectBaseRT.OPTION_SPLITTER_VALUES_STRING); List<Integer> multipleValues = new ArrayList<Integer>(); for (int i = 0; i < parts.length; i++) { String part = parts[i]; Integer objectID = null; try { objectID = getLookupValue(part, fieldTypeRT, fieldID, systemLookups, projectSpecificLookups, serializableBeanAllowedContext, null, invalidValueHandlingMap, locale); } catch (ExcelImportNotExistingCellValueException e) { addGridError(gridErrorsMap, NOT_EXISTING_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } catch (ExcelImportNotAllowedCellValueException e) { addGridError(gridErrorsMap, NOT_ALLOWED_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } if (objectID != null) { multipleValues.add(objectID); } } if (!multipleValues.isEmpty()) { attributeValue = multipleValues.toArray(); excelValueFound = true; } } else { int numberOfParts = ((CustomCompositeBaseRT) fieldTypeRT).getNumberOfParts(); parts = compositeOrMultipleValue .split("\\" + CustomCompositeBaseRT.PART_SPLITTER_VALUES_STRING); if (parts != null && parts.length > numberOfParts) { addGridError(gridErrorsMap, WRONG_COMPOSITE_SIZE, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, compositeOrMultipleValue); } Map<Integer, Integer> componentPartsMap = new HashMap<Integer, Integer>(); attributeValue = new HashMap<Integer, Object>(); if (parts != null) { for (int i = 0; i < parts.length; i++) { String part = parts[i]; Integer objectID = null; IFieldTypeRT componentFieldType = ((CustomCompositeBaseRT) fieldTypeRT) .getCustomFieldType(i + 1); if (componentFieldType != null) { try { objectID = getLookupValue(part, componentFieldType, fieldID, systemLookups, projectSpecificLookups, serializableBeanAllowedContext, componentPartsMap, invalidValueHandlingMap, locale); } catch (ExcelImportNotExistingCellValueException e) { addGridError(gridErrorsMap, NOT_EXISTING_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } catch (ExcelImportNotAllowedCellValueException e) { addGridError(gridErrorsMap, NOT_ALLOWED_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } if (objectID == null) { // workItemBean.setAttribute(fieldID, // Integer.valueOf(i+1), null); ((Map<Integer, Object>) attributeValue).put(Integer.valueOf(i + 1), null); } else { componentPartsMap.put(Integer.valueOf(i + 1), objectID); // workItemBean.setAttribute(fieldID, // Integer.valueOf(i+1), new // Object[] {objectID}); ((Map<Integer, Object>) attributeValue).put(Integer.valueOf(i + 1), new Object[] { objectID }); excelValueFound = true; } } } } } } else { // simple field // Object attributeValue = null; try { attributeValue = getAttributeValue(cell, fieldID, null, serializableBeanAllowedContext, locale, invalidValueHandlingMap, systemLookups, projectSpecificLookups); } catch (ExcelImportNotExistingCellValueException e) { addGridError(gridErrorsMap, NOT_EXISTING_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } catch (ExcelImportNotAllowedCellValueException e) { addGridError(gridErrorsMap, NOT_ALLOWED_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } catch (ExcelImportInvalidCellValueException e) { addGridError(gridErrorsMap, INVALID_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } if (attributeValue != null) { excelValueFound = true; if (possibleBottomUpFields.contains(fieldID)) { TFieldConfigBean fieldConfigBean = FieldRuntimeBL .getFieldConfigForProjectIssueTypeField( projectsToIssueTypesToFieldConfigsMapForBottomUpFields, projectID, issueTypeID, fieldID); Object fieldSettings = FieldRuntimeBL.getFieldSettingsForProjectIssueTypeField( projectsIssueTypesFieldSettingsMapForBottomUpFields, projectID, issueTypeID, fieldID); if (fieldTypeRT.getHierarchicalBehavior(fieldID, fieldConfigBean, fieldSettings) == HIERARCHICAL_BEHAVIOR_OPTIONS.COMPUTE_BOTTOM_UP && ItemBL.hasChildren(workItemBean.getObjectID())) { Date trackPlusAttributeValue = (Date) workItemBean.getAttribute(fieldID); if (EqualUtils.notEqual(trackPlusAttributeValue, (Date) attributeValue)) { // add read only restrictions for start // and end date for non leaf workItems LOGGER.debug("Parent change restriction for bottom up date " + fieldID); addGridError(gridErrorsMap, NOT_EDITABLE_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, getStringCellValue(cell)); } } /* * if * (ApplicationBean.getInstance().getSiteBean * ().getSummaryItemsBehavior() && * ItemBL2.hasChildren * (workItemBean.getObjectID())) { Date * trackPlusAttributeValue = * (Date)workItemBean.getAttribute(fieldID); if * (EqualUtils.notEqual(trackPlusAttributeValue, * (Date)attributeValue)) { //add read only * restrictions for start and end date for non * leaf workItems LOGGER.debug( * "Summary parent change restriction for date " * + fieldID); addGridError(gridErrorsMap, * NOT_EDITABLE_ERRORS, rowNum, * ExcelFieldMatchBL * .colNumericToLetter(columnIndex), fieldID, * getStringCellValue(cell)); } } */ } } } attributeChanged = fieldTypeRT.valueModified(attributeValue, workItemBean.getAttribute(fieldID)); workItemBean.setAttribute(fieldID, null, attributeValue); } if (attributeChanged) { try { verifyFieldRestrictions(fieldForRestriction, restrictedFields, cell, locale); } catch (ExcelImportNotModifiableCellValueException e) { addGridError(gridErrorsMap, NOT_EDITABLE_ERRORS, rowNum, ExcelFieldMatchBL.colNumericToLetter(columnIndex), fieldID, e.getMessage()); } } } if (!excelValueFound) { // not a single excel value found in any cell from the row // simply neglect this row. // expanded row count can be greater than the number of real // workItem rows // for example when the content of some rows is deleted but the // rows are not deleted // and empty rows may remain in the excel LOGGER.info("The row number " + (rowNum + 1) + " contains only empty cells and will be neglected"); continue; } // add the default values for those fields which didn't have column // in // excel sheet or have column but the value is empty or not valid Iterator<Integer> itrDefaultValueFields = defaultValuesMap.keySet().iterator(); while (itrDefaultValueFields.hasNext()) { Integer fieldID = itrDefaultValueFields.next(); if (/*!fieldIDToColumnIndexMap.containsKey(fieldID) ||*/workItemBean.getAttribute(fieldID, null) == null) { if (invalidValueHandlingMap.containsKey(fieldID)) { if (DEFAULT_IF_NOT_EXIST_OR_EMPTY.equals(invalidValueHandlingMap.get(fieldID))) { IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID, null); ILookup lookup = (ILookup) fieldTypeRT; Integer defaultObjectID = defaultValuesMap.get(fieldID); if (defaultObjectID != null) { boolean allowed = lookup.lookupBeanAllowed(defaultObjectID, serializableBeanAllowedContext); if (allowed) { workItemBean.setAttribute(fieldID, null, defaultObjectID); } else { // for example when no default project // and/or issue type is specified the // default manager and responsible // lists contain the users which are manager // or responsible in any of the projects // (but maybe not in all) LOGGER.debug("The default value is not allowed for field " + fieldID + " on row " + rowNum); // cache the show values and localized // labels to spare additional database // accesses String showValue; if (defaultShowValuesMap.containsKey(fieldID)) { showValue = defaultShowValuesMap.get(fieldID); } else { showValue = fieldTypeRT.getShowValue(defaultObjectID, locale); defaultShowValuesMap.put(fieldID, showValue); } String localizedLabel; if (defaultLocalizedFieldLabels.containsKey(fieldID)) { localizedLabel = defaultLocalizedFieldLabels.get(fieldID); } else { localizedLabel = FieldRuntimeBL.getLocalizedDefaultFieldLabel(fieldID, locale); defaultLocalizedFieldLabels.put(fieldID, localizedLabel); } addGridError(gridErrorsMap, NOT_ALLOWED_DEFAULT_VALUES_ERRORS, rowNum, localizedLabel, fieldID, showValue); } } } } } } workItemBeansMap.put(rowNum, workItemBean); } return workItemBeansMap; }
From source file:org.opennms.netmgt.correlation.ncs.DependencyRulesTest.java
private List<NCSComponent> findPathToSubcomponent(NCSComponent svc, final String subForeignSource, final String subForeignId) { VisitorWithReturn<List<NCSComponent>> visitor = new VisitorWithReturn<List<NCSComponent>>() { Stack<NCSComponent> m_stack = new Stack<NCSComponent>(); @Override/* w ww .ja v a 2 s .c o m*/ public void visitComponent(NCSComponent component) { m_stack.push(component); if (subForeignSource.equals(component.getForeignSource()) && subForeignId.equals(component.getForeignId())) { setRetVal(new LinkedList<NCSComponent>(m_stack)); } } @Override public void completeComponent(NCSComponent component) { m_stack.pop(); } }; return visitWithRetVal(svc, visitor, null); }
From source file:de.uni_koblenz.jgralab.utilities.rsa.Rsa2Tg.java
/** * Sets up several a {@link SchemaGraph} and data structures before the * processing can start.//w w w .ja va 2 s .c o m */ @Override public void startDocument() { sg = GrumlSchema.instance().createSchemaGraph_InMemoryStorage(); // Initializing all necessary data structures for processing purposes. xmiIdStack = new Stack<String>(); idMap = new HashMap<String, Vertex>(); packageStack = new Stack<Package>(); generalizations = new LocalGenericGraphMarker<Set<String>>(sg); realizations = new HashMap<String, Set<String>>(); attributeType = new LocalGenericGraphMarker<String>(sg); recordComponentType = new LocalGenericGraphMarker<String>(sg); domainMap = new HashMap<String, Domain>(); preliminaryVertices = new HashSet<Vertex>(); ownedEnds = new HashSet<IncidenceClass>(); constraints = new HashMap<String, List<String>>(); idsOfOldIncidenceclassAtNewEdgeClass = new HashSet<String>(); comments = new HashMap<String, List<String>>(); redefinesAtVertex = new LocalGenericGraphMarker<Set<String>>(sg); redefinesAtEdge = new LocalGenericGraphMarker<Set<String>>(sg); subsets = new LocalGenericGraphMarker<Set<String>>(sg); edgeStereotypedVertexClasses = new HashSet<VertexClass>(); edgeStereotypedEdgeClasses = new HashSet<EdgeClass>(); isBinaryEdgeAlreadyConverted = new LocalBooleanGraphMarker(sg); nestedElements = new LocalGenericGraphMarker<Set<GraphElementClass>>(sg); isNestingIncidenceOrEdgeClass = new LocalBooleanGraphMarker(sg); ignoredPackages = new HashSet<Package>(); modelRootElementNestingDepth = 1; preliminaryMayBeNestedInVertexClass = sg.createVertexClass(); preliminaryMayBeNestedInVertexClass .set_qualifiedName("preliminary VertexClass for preliminary MayBeNestedInEdges"); wrongEdgeClasses = new HashSet<EdgeClass>(); getMayBeNestedInRepresentation = new LocalGenericGraphMarker<MayBeNestedIn>(sg); }
From source file:com.almarsoft.GroundhogReader.MessageListActivity.java
private void fillListNonRecursive(Article root, int depth, String replyto) { Stack<MiniHeader> stack = new Stack<MiniHeader>(); boolean markReplies = mPrefs.getBoolean("markReplies", true); boolean finished = false; String clean_subject;//ww w. j av a 2s .c o m MiniHeader tmpMiniItem; HeaderItemClass ih = null; String[] refsArray; String msgId; ArrayList<HeaderItemClass> nonStarredItems = new ArrayList<HeaderItemClass>(); HashSet<String> bannedTrollsSet = DBUtils.getBannedTrolls(getApplicationContext()); HashSet<String> starredSet = DBUtils.getStarredSubjectsSet(getApplicationContext()); // Proxy for speed HashSet<String> myPostsSetProxy = mMyPostsSet; ArrayList<HeaderItemClass> headerItemsListProxy = new ArrayList<HeaderItemClass>(); int refsArrayLen; while (!finished) { if (root == null) finished = true; root.setReplyTo(replyto); if (!root.isDummy()) { ih = new HeaderItemClass(root, depth); // Don't feed the troll if (!bannedTrollsSet.contains(root.getFrom())) { // Put the replies in red (if configured) if (markReplies) { refsArray = root.getReferences(); refsArrayLen = refsArray.length; msgId = null; if (refsArray != null && refsArrayLen > 0) { msgId = refsArray[refsArrayLen - 1]; } if (msgId != null && myPostsSetProxy != null && myPostsSetProxy.contains(msgId)) ih.myreply = true; else ih.myreply = false; } clean_subject = root.simplifiedSubject(); if (starredSet.contains(clean_subject)) { ih.starred = true; headerItemsListProxy.add(ih); // Starred items first } else { // Nonstarred items will be added to mHeaderItemsList at the end nonStarredItems.add(ih); } } } if (root.next != null) { tmpMiniItem = new MiniHeader(root.next, depth, replyto); stack.push(tmpMiniItem); } if (root.kid != null) { replyto = root.getFrom(); if (!root.isDummy()) ++depth; root = root.kid; } else if (!stack.empty()) { tmpMiniItem = stack.pop(); root = tmpMiniItem.article; depth = tmpMiniItem.depth; replyto = tmpMiniItem.replyto; } else finished = true; } // Now add the non starred items after the starred ones int nonStarredItemsLen = nonStarredItems.size(); for (int i = 0; i < nonStarredItemsLen; i++) { headerItemsListProxy.add(nonStarredItems.get(i)); } mHeaderItemsList = headerItemsListProxy; nonStarredItems = null; }
From source file:edu.umn.cs.spatialHadoop.core.RTree.java
/** * Searches the RTree starting from the given start position. This is either * a node number or offset of an element. If it's a node number, it performs * the search in the subtree rooted at this node. If it's an offset number, * it searches only the object found there. * It is assumed that the openQuery() has been called before this function * and that endQuery() will be called afterwards. * @param query_mbr/*from w w w. j a v a 2s .co m*/ * @param output * @param start - where to start searching * @param end - where to end searching. Only used when start is an offset of * an object. * @return * @throws IOException */ protected int search(Shape query_shape, ResultCollector<T> output, int start, int end) throws IOException { Rectangle query_mbr = query_shape.getMBR(); int resultSize = 0; // Special case for an empty tree if (height == 0) return 0; Stack<Integer> toBeSearched = new Stack<Integer>(); // Start from the given node toBeSearched.push(start); if (start >= nodeCount) { toBeSearched.push(end); } Rectangle node_mbr = new Rectangle(); // Holds one data line from tree data Text line = new Text2(); while (!toBeSearched.isEmpty()) { int searchNumber = toBeSearched.pop(); int mbrsToTest = searchNumber == 0 ? 1 : degree; if (searchNumber < nodeCount) { long nodeOffset = NodeSize * searchNumber; structure.seek(nodeOffset); int dataOffset = structure.readInt(); for (int i = 0; i < mbrsToTest; i++) { node_mbr.readFields(structure); int lastOffset = (searchNumber + i) == nodeCount - 1 ? treeSize : structure.readInt(); if (query_mbr.contains(node_mbr)) { // The node is full contained in the query range. // Save the time and do full scan for this node toBeSearched.push(dataOffset); // Checks if this node is the last node in its level // This can be easily detected because the next node in the level // order traversal will be the first node in the next level // which means it will have an offset less than this node if (lastOffset <= dataOffset) lastOffset = treeSize; toBeSearched.push(lastOffset); } else if (query_mbr.isIntersected(node_mbr)) { // Node partially overlaps with query. Go deep under this node if (searchNumber < nonLeafNodeCount) { // Search child nodes toBeSearched.push((searchNumber + i) * degree + 1); } else { // Search all elements in this node toBeSearched.push(dataOffset); // Checks if this node is the last node in its level // This can be easily detected because the next node in the level // order traversal will be the first node in the next level // which means it will have an offset less than this node if (lastOffset <= dataOffset) lastOffset = treeSize; toBeSearched.push(lastOffset); } } dataOffset = lastOffset; } } else { int firstOffset, lastOffset; // Search for data items (records) lastOffset = searchNumber; firstOffset = toBeSearched.pop(); data.seek(firstOffset + treeStartOffset); LineReader lineReader = new LineReader(data); while (firstOffset < lastOffset) { firstOffset += lineReader.readLine(line); stockObject.fromText(line); if (stockObject.isIntersected(query_shape)) { resultSize++; if (output != null) output.collect(stockObject); } } } } return resultSize; }
From source file:forge.game.phase.PhaseHandler.java
public final void addExtraPhase(final PhaseType afterPhase, final PhaseType extraPhase) { // 500.8. Some effects can add phases to a turn. They do this by adding the phases directly after the specified phase. // If multiple extra phases are created after the same phase, the most recently created phase will occur first. if (!extraPhases.containsKey(afterPhase)) { extraPhases.put(afterPhase, new Stack<PhaseType>()); }/*from w w w .ja v a2 s. c o m*/ extraPhases.get(afterPhase).push(extraPhase); }