List of usage examples for java.util Stack peek
public synchronized E peek()
From source file:org.sakaiproject.site.impl.BaseSite.java
/** * {@inheritDoc}//from ww w.jav a 2s . c o m */ public Element toXml(Document doc, Stack stack) { Element site = doc.createElement("site"); if (stack.isEmpty()) { doc.appendChild(site); } else { ((Element) stack.peek()).appendChild(site); } site.setAttribute("id", getId()); if (m_title != null) site.setAttribute("title", m_title); // encode the short description if (m_shortDescription != null) Xml.encodeAttribute(site, "short-description-enc", m_shortDescription); // encode the description if (m_description != null) Xml.encodeAttribute(site, "description-enc", m_description); site.setAttribute("joinable", Boolean.valueOf(m_joinable).toString()); if (m_joinerRole != null) site.setAttribute("joiner-role", m_joinerRole); site.setAttribute("published", Boolean.valueOf(m_published).toString()); if (m_icon != null) site.setAttribute("icon", m_icon); if (m_info != null) site.setAttribute("info", m_info); if (m_skin != null) site.setAttribute("skin", m_skin); site.setAttribute("pubView", Boolean.valueOf(m_pubView).toString()); site.setAttribute("customPageOrdered", Boolean.valueOf(m_customPageOrdered).toString()); site.setAttribute("type", m_type); site.setAttribute("created-id", m_createdUserId); site.setAttribute("modified-id", m_lastModifiedUserId); site.setAttribute("created-time", m_createdTime.toString()); site.setAttribute("modified-time", m_lastModifiedTime.toString()); // properties stack.push(site); getProperties().toXml(doc, stack); stack.pop(); // site pages Element list = doc.createElement("pages"); site.appendChild(list); stack.push(list); for (Iterator iPages = getPages().iterator(); iPages.hasNext();) { BaseSitePage page = (BaseSitePage) iPages.next(); page.toXml(doc, stack); } stack.pop(); // TODO: site groups return site; }
From source file:com.bettervectordrawable.lib.graphics.drawable.VectorDrawable.java
private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme) throws XmlPullParserException, IOException { final VectorDrawableState state = mVectorState; final VPathRenderer pathRenderer = state.mVPathRenderer; boolean noPathTag = true; // Use a stack to help to build the group tree. // The top of the stack is always the current group. final Stack<VGroup> groupStack = new Stack<VGroup>(); groupStack.push(pathRenderer.mRootGroup); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { final String tagName = parser.getName(); final VGroup currentGroup = groupStack.peek(); if (SHAPE_PATH.equals(tagName)) { final VFullPath path = new VFullPath(); path.inflate(res, attrs, theme); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); }/* w w w . j ava2 s .c om*/ noPathTag = false; state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_CLIP_PATH.equals(tagName)) { final VClipPath path = new VClipPath(); path.inflate(res, attrs, theme); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); } state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_GROUP.equals(tagName)) { VGroup newChildGroup = new VGroup(); newChildGroup.inflate(res, attrs, theme); currentGroup.mChildren.add(newChildGroup); groupStack.push(newChildGroup); if (newChildGroup.getGroupName() != null) { pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(), newChildGroup); } state.mChangingConfigurations |= newChildGroup.mChangingConfigurations; } } else if (eventType == XmlPullParser.END_TAG) { final String tagName = parser.getName(); if (SHAPE_GROUP.equals(tagName)) { groupStack.pop(); } } eventType = parser.next(); } // Print the tree out for debug. if (DBG_VECTOR_DRAWABLE) { printGroupTree(pathRenderer.mRootGroup, 0); } if (noPathTag) { final StringBuffer tag = new StringBuffer(); if (tag.length() > 0) { tag.append(" or "); } tag.append(SHAPE_PATH); throw new XmlPullParserException("no " + tag + " defined"); } }
From source file:org.ploin.web.faces.core.BackNavigationHandler.java
@Override public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) { String viewId = facesContext.getViewRoot().getViewId(); log.debug("outcome " + outcome); HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest(); HttpSession session = request.getSession(); Stack<String> lastViewIds = (Stack<String>) session.getAttribute("lastViewIds"); if (lastViewIds == null) lastViewIds = new Stack<String>(); session.setAttribute("ploinFacesFromViewId", viewId); if (outcome != null) { if ("back".equals(outcome)) { String lastViewId = lastViewIds.pop(); navigateToViewId(facesContext, lastViewId); return; } else if ("backback".equals(outcome)) { lastViewIds.pop();//from w w w .j a va 2 s . com String lastViewId = lastViewIds.pop(); navigateToViewId(facesContext, lastViewId); return; } else if ("backbackback".equals(outcome)) { lastViewIds.pop(); lastViewIds.pop(); String lastViewId = lastViewIds.pop(); navigateToViewId(facesContext, lastViewId); return; } else if ("back4".equals(outcome)) { lastViewIds.pop(); lastViewIds.pop(); lastViewIds.pop(); String lastViewId = lastViewIds.pop(); navigateToViewId(facesContext, lastViewId); return; } else if ("back5".equals(outcome)) { lastViewIds.pop(); lastViewIds.pop(); lastViewIds.pop(); lastViewIds.pop(); String lastViewId = lastViewIds.pop(); navigateToViewId(facesContext, lastViewId); return; } else { String out = outcome; if (out == null) out = ""; out = out.replaceFirst("->", ""); if (lastViewIds.isEmpty()) lastViewIds.push(viewId); else if (!lastViewIds.peek().equals(viewId) && !out.equals(viewId)) lastViewIds.push(viewId); if (lastViewIds.size() > 10) lastViewIds.remove(0); if (outcome.startsWith("->")) { outcome = outcome.replaceFirst("->", ""); navigateToViewId(facesContext, outcome); return; } } } session.setAttribute("lastViewIds", lastViewIds); super.handleNavigation(facesContext, fromAction, outcome); log.debug("after navigation"); }
From source file:com.unboundid.scim2.common.utils.Parser.java
/** * Read a filter from the reader.//from w w w.ja va2s . c om * * @param reader The reader to read the filter from. * @param isValueFilter Whether to read the filter as a value filter. * @return The parsed filter. * @throws BadRequestException If the filter string could not be parsed. */ private static Filter readFilter(final StringReader reader, final boolean isValueFilter) throws BadRequestException { final Stack<Filter> outputStack = new Stack<Filter>(); final Stack<String> precedenceStack = new Stack<String>(); String token; String previousToken = null; while ((token = readFilterToken(reader, isValueFilter)) != null) { if (token.equals("(") && expectsNewFilter(previousToken)) { precedenceStack.push(token); } else if (token.equalsIgnoreCase(FilterType.NOT.getStringValue()) && expectsNewFilter(previousToken)) { // "not" should be followed by an ( String nextToken = readFilterToken(reader, isValueFilter); if (nextToken == null) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } if (!nextToken.equals("(")) { final String msg = String.format("Expected '(' at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } precedenceStack.push(token); } else if (token.equals(")") && !expectsNewFilter(previousToken)) { String operator = closeGrouping(precedenceStack, outputStack, false); if (operator == null) { final String msg = String.format( "No opening parenthesis matching closing " + "parenthesis at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } if (operator.equalsIgnoreCase(FilterType.NOT.getStringValue())) { // Treat "not" the same as "(" except wrap everything in a not filter. outputStack.push(Filter.not(outputStack.pop())); } } else if (token.equalsIgnoreCase(FilterType.AND.getStringValue()) && !expectsNewFilter(previousToken)) { // and has higher precedence than or. precedenceStack.push(token); } else if (token.equalsIgnoreCase(FilterType.OR.getStringValue()) && !expectsNewFilter(previousToken)) { // pop all the pending ands first before pushing or. LinkedList<Filter> andComponents = new LinkedList<Filter>(); while (!precedenceStack.isEmpty()) { if (precedenceStack.peek().equalsIgnoreCase(FilterType.AND.getStringValue())) { precedenceStack.pop(); andComponents.addFirst(outputStack.pop()); } else { break; } if (!andComponents.isEmpty()) { andComponents.addFirst(outputStack.pop()); outputStack.push(Filter.and(andComponents)); } } precedenceStack.push(token); } else if (token.endsWith("[") && expectsNewFilter(previousToken)) { // This is a complex value filter. final Path filterAttribute; try { filterAttribute = parsePath(token.substring(0, token.length() - 1)); } catch (final BadRequestException e) { Debug.debugException(e); final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark, e.getMessage()); throw BadRequestException.invalidFilter(msg); } if (filterAttribute.isRoot()) { final String msg = String.format("Attribute path expected at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } outputStack.push(Filter.hasComplexValue(filterAttribute, readFilter(reader, true))); } else if (isValueFilter && token.equals("]") && !expectsNewFilter(previousToken)) { break; } else if (expectsNewFilter(previousToken)) { // This must be an attribute path followed by operator and maybe value. final Path filterAttribute; try { filterAttribute = parsePath(token); } catch (final BadRequestException e) { Debug.debugException(e); final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark, e.getMessage()); throw BadRequestException.invalidFilter(msg); } if (filterAttribute.isRoot()) { final String msg = String.format("Attribute path expected at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } String op = readFilterToken(reader, isValueFilter); if (op == null) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } if (op.equalsIgnoreCase(FilterType.PRESENT.getStringValue())) { outputStack.push(Filter.pr(filterAttribute)); } else { ValueNode valueNode; try { // Mark the beginning of the JSON value so we can later reset back // to this position and skip the actual chars that were consumed // by Jackson. The Jackson parser is buffered and reads everything // until the end of string. reader.mark(0); ScimJsonFactory scimJsonFactory = (ScimJsonFactory) JsonUtils.getObjectReader() .getFactory(); JsonParser parser = scimJsonFactory.createScimFilterParser(reader); // The object mapper will return a Java null for JSON null. // Have to distinguish between reading a JSON null and encountering // the end of string. if (parser.getCurrentToken() == null && parser.nextToken() == null) { // End of string. valueNode = null; } else { valueNode = parser.readValueAsTree(); // This is actually a JSON null. Use NullNode. if (valueNode == null) { valueNode = JsonUtils.getJsonNodeFactory().nullNode(); } } // Reset back to the beginning of the JSON value. reader.reset(); // Skip the number of chars consumed by JSON parser. reader.skip(parser.getCurrentLocation().getCharOffset()); } catch (IOException e) { final String msg = String.format("Invalid comparison value at position %d: %s", reader.mark, e.getMessage()); throw BadRequestException.invalidFilter(msg); } if (valueNode == null) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } if (op.equalsIgnoreCase(FilterType.EQUAL.getStringValue())) { outputStack.push(Filter.eq(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.NOT_EQUAL.getStringValue())) { outputStack.push(Filter.ne(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.CONTAINS.getStringValue())) { outputStack.push(Filter.co(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.STARTS_WITH.getStringValue())) { outputStack.push(Filter.sw(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.ENDS_WITH.getStringValue())) { outputStack.push(Filter.ew(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.GREATER_THAN.getStringValue())) { outputStack.push(Filter.gt(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.GREATER_OR_EQUAL.getStringValue())) { outputStack.push(Filter.ge(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.LESS_THAN.getStringValue())) { outputStack.push(Filter.lt(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.LESS_OR_EQUAL.getStringValue())) { outputStack.push(Filter.le(filterAttribute, valueNode)); } else { final String msg = String.format("Unrecognized attribute operator '%s' at position %d. " + "Expected: eq,ne,co,sw,ew,pr,gt,ge,lt,le", op, reader.mark); throw BadRequestException.invalidFilter(msg); } } } else { final String msg = String.format("Unexpected character '%s' at position %d", token, reader.mark); throw BadRequestException.invalidFilter(msg); } previousToken = token; } closeGrouping(precedenceStack, outputStack, true); if (outputStack.isEmpty()) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } return outputStack.pop(); }
From source file:android.support.graphics.drawable.VectorDrawableCompat.java
private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme) throws XmlPullParserException, IOException { final VectorDrawableCompatState state = mVectorState; final VPathRenderer pathRenderer = state.mVPathRenderer; boolean noPathTag = true; // Use a stack to help to build the group tree. // The top of the stack is always the current group. final Stack<VGroup> groupStack = new Stack<VGroup>(); groupStack.push(pathRenderer.mRootGroup); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { final String tagName = parser.getName(); final VGroup currentGroup = groupStack.peek(); if (SHAPE_PATH.equals(tagName)) { final VFullPath path = new VFullPath(); path.inflate(res, attrs, theme, parser); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); }/*from w w w . ja v a 2 s.c om*/ noPathTag = false; state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_CLIP_PATH.equals(tagName)) { final VClipPath path = new VClipPath(); path.inflate(res, attrs, theme, parser); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); } state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_GROUP.equals(tagName)) { VGroup newChildGroup = new VGroup(); newChildGroup.inflate(res, attrs, theme, parser); currentGroup.mChildren.add(newChildGroup); groupStack.push(newChildGroup); if (newChildGroup.getGroupName() != null) { pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(), newChildGroup); } state.mChangingConfigurations |= newChildGroup.mChangingConfigurations; } } else if (eventType == XmlPullParser.END_TAG) { final String tagName = parser.getName(); if (SHAPE_GROUP.equals(tagName)) { groupStack.pop(); } } eventType = parser.next(); } // Print the tree out for debug. if (DBG_VECTOR_DRAWABLE) { printGroupTree(pathRenderer.mRootGroup, 0); } if (noPathTag) { final StringBuffer tag = new StringBuffer(); if (tag.length() > 0) { tag.append(" or "); } tag.append(SHAPE_PATH); throw new XmlPullParserException("no " + tag + " defined"); } }
From source file:org.netxilia.server.rest.HomeResource.java
/** * build the HTML tags for a tree like view * /* w w w. j a va 2 s. c o m*/ * @param foldersSheet * @param treeview * @throws NetxiliaBusinessException * @throws NetxiliaResourceException */ private DefaultMutableTreeNode buildWorkbookTree(IWorkbook workbook, ISheet foldersSheet, Set<SheetFullName> sheetNames) throws NetxiliaResourceException, NetxiliaBusinessException { DefaultMutableTreeNode workbookNode = new DefaultMutableTreeNode( new TreeViewData(workbook.getId().getKey(), workbook.getName(), "workbook")); Stack<DefaultMutableTreeNode> stockNodes = new Stack<DefaultMutableTreeNode>(); stockNodes.push(workbookNode); Set<SheetFullName> alreadyInsertedSheets = new HashSet<SheetFullName>(); if (foldersSheet != null) { Matrix<CellData> folderCells = foldersSheet.receiveCells(AreaReference.ALL).getNonBlocking(); for (List<CellData> row : folderCells.getRows()) { int level = 0; String nodeName = null; for (CellData cell : row) { if (cell.getValue() != null) { nodeName = cell.getValue().getStringValue(); if (nodeName != null && nodeName.length() > 0) { level = cell.getReference().getColumnIndex(); break; } } } if (nodeName == null) { // empty line - ignored continue; } // first level for folders is 1 (under the root node) level = level + 1; SheetFullName sheetName = new SheetFullName(workbook.getName(), nodeName); boolean isSheet = sheetNames.contains(sheetName); if (isSheet) { alreadyInsertedSheets.add(sheetName); } DefaultMutableTreeNode crt = new DefaultMutableTreeNode(new TreeViewData(sheetName.toString(), sheetName.getSheetName(), isSheet ? "sheet" : "folder")); while (!stockNodes.empty()) { DefaultMutableTreeNode node = stockNodes.peek(); if (level > node.getLevel()) { // make sure is the direct child node.add(crt); break; } stockNodes.pop(); } stockNodes.push(crt); } } // add the sheets not already added for (SheetFullName sheetName : sheetNames) { if (alreadyInsertedSheets.contains(sheetName)) { continue; } DefaultMutableTreeNode sheetNode = new DefaultMutableTreeNode( new TreeViewData(sheetName.toString(), sheetName.getSheetName(), "sheet")); workbookNode.add(sheetNode); } return workbookNode; }
From source file:com.pinterest.rocksplicator.controller.tasks.ChainedTask.java
@Override public void process(Context ctx) throws Exception { long id = ctx.getId(); final String cluster = ctx.getCluster(); final String worker = ctx.getWorker(); final TaskQueue taskQueue = ctx.getTaskQueue(); Stack<TaskBase> tasks = new Stack<>(); tasks.push(getParameter().getT2());/*w w w . j av a 2 s . co m*/ tasks.push(getParameter().getT1()); while (!tasks.isEmpty()) { TaskBase taskBase = tasks.pop(); AbstractTask task = TaskFactory.getWorkerTask(taskBase); if (task == null) { taskQueue.failTask(id, "Failed to instantiate task " + taskBase.name); return; } else if (task instanceof ChainedTask) { ChainedTask chainedTask = (ChainedTask) task; tasks.push(chainedTask.getParameter().getT2()); tasks.push(chainedTask.getParameter().getT1()); } else { LocalAckTaskQueue lq = new LocalAckTaskQueue(taskQueue); ctx = new Context(id, cluster, lq, worker); try { task.process(ctx); } catch (Exception ex) { LOG.error("Unexpected exception from task: {} in task chain.", task.getName(), ex); lq.failTask(id, ex.getMessage()); } LocalAckTaskQueue.State state = lq.getState(); if (state.state == LocalAckTaskQueue.State.StateName.UNFINISHED) { LOG.error("Task {} finished processing without ack", id); return; } else if (state.state == LocalAckTaskQueue.State.StateName.FAILED) { LOG.error("Task {} failed with reason: {}. Abort the task chain.", id, state.output); taskQueue.failTask(id, state.output); return; } else if (tasks.isEmpty()) { LOG.info("Finished processing chained task"); taskQueue.finishTask(id, state.output); return; } long nextId = taskQueue.finishTaskAndEnqueueRunningTask(id, state.output, tasks.peek(), worker); if (nextId < 0) { LOG.error("Failed to finish task {} and enqueue new task {}", id, tasks.peek()); return; } else { id = nextId; } } } }
From source file:org.seasar.mayaa.impl.builder.TemplateBuilderImpl.java
protected void walkParsedTree(Template template, Stack stack, NodeTreeWalker original, Set divided) { if (original == null) { throw new IllegalArgumentException(); }/* w w w. java 2 s .c om*/ Iterator it = original.iterateChildNode(); while (it.hasNext()) { SpecificationNode child; try { child = (SpecificationNode) it.next(); } catch (ConcurrentModificationException e) { LOG.error("original.childNodes ???????", e); throw e; } saveToCycle(child, child); if (QM_MAYAA.equals(child.getQName())) { continue; } InjectionChain chain = getDefaultInjectionChain(); SpecificationNode injected = resolveOriginalNode(child, chain); if (injected == null) { throw new TemplateNodeNotResolvedException(original.toString()); } saveToCycle(child, injected); ProcessorTreeWalker processor = resolveInjectedNode(template, stack, child, injected, divided); if (processor != null) { stack.push(processor); walkParsedTree(template, stack, child, divided); stack.pop(); } } if (isOptimizeEnabled()) { ProcessorTreeWalker parent = (ProcessorTreeWalker) stack.peek(); int count = parent.getChildProcessorSize(); if (count > 0) { List childProcessors = new ArrayList(); for (int i = 0; i < count; i++) { childProcessors.add(parent.getChildProcessor(i)); } parent.clearChildProcessors(); optimizeProcessors(template, parent, childProcessors, divided); } } }
From source file:com.hippo.vector.VectorDrawable.java
private void inflateInternal(Context context, XmlPullParser parser, AttributeSet attrs) throws XmlPullParserException, IOException { final VectorDrawableState state = mVectorState; final VPathRenderer pathRenderer = state.mVPathRenderer; boolean noPathTag = true; // Use a stack to help to build the group tree. // The top of the stack is always the current group. final Stack<VGroup> groupStack = new Stack<>(); groupStack.push(pathRenderer.mRootGroup); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { final String tagName = parser.getName(); final VGroup currentGroup = groupStack.peek(); if (SHAPE_PATH.equals(tagName)) { final VFullPath path = new VFullPath(); path.inflate(context, attrs); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); }//from w w w.j a va 2s. c o m noPathTag = false; state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_CLIP_PATH.equals(tagName)) { final VClipPath path = new VClipPath(); path.inflate(context, attrs); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); } state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_GROUP.equals(tagName)) { VGroup newChildGroup = new VGroup(); newChildGroup.inflate(context, attrs); currentGroup.mChildren.add(newChildGroup); groupStack.push(newChildGroup); if (newChildGroup.getGroupName() != null) { pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(), newChildGroup); } state.mChangingConfigurations |= newChildGroup.mChangingConfigurations; } } else if (eventType == XmlPullParser.END_TAG) { final String tagName = parser.getName(); if (SHAPE_GROUP.equals(tagName)) { groupStack.pop(); } } eventType = parser.next(); } // Print the tree out for debug. if (DBG_VECTOR_DRAWABLE) { printGroupTree(pathRenderer.mRootGroup, 0); } if (noPathTag) { final StringBuilder tag = new StringBuilder(); if (tag.length() > 0) { tag.append(" or "); } tag.append(SHAPE_PATH); throw new XmlPullParserException("no " + tag + " defined"); } }
From source file:org.sakaiproject.component.app.messageforums.DiscussionForumServiceImpl.java
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments) { Base64 base64Encoder = new Base64(); StringBuilder results = new StringBuilder(); try {/*from w ww . j a va 2s .co m*/ int forumCount = 0; results.append("archiving " + getLabel() + " context " + Entity.SEPARATOR + siteId + Entity.SEPARATOR + SiteService.MAIN_CONTAINER + ".\n"); // start with an element with our very own (service) name Element element = doc.createElement(DiscussionForumService.class.getName()); element.setAttribute(VERSION_ATTR, ARCHIVE_VERSION); ((Element) stack.peek()).appendChild(element); stack.push(element); if (siteId != null && siteId.trim().length() > 0) { Area dfArea = areaManager.getAreaByContextIdAndTypeId(siteId, typeManager.getDiscussionForumType()); if (dfArea != null) { Element dfElement = doc.createElement(MESSAGEFORUM); //List forums = dfManager.getDiscussionForumsByContextId(siteId); List forums = dfManager.getDiscussionForumsWithTopicsMembershipNoAttachments(siteId); if (forums != null && !forums.isEmpty()) { Iterator forumsIter = forums.iterator(); while (forumsIter.hasNext()) { DiscussionForum forum = (DiscussionForum) forumsIter.next(); if (forum != null) { forumCount++; Element df_data = doc.createElement(DISCUSSION_FORUM); df_data.setAttribute(DISCUSSION_FORUM_TITLE, forum.getTitle()); df_data.setAttribute(DRAFT, forum.getDraft().toString()); df_data.setAttribute(LOCKED, forum.getLocked().toString()); df_data.setAttribute(MODERATED, forum.getModerated().toString()); df_data.setAttribute(SORT_INDEX, forum.getSortIndex().toString()); try { String encoded = new String( base64Encoder.encode(forum.getExtendedDescription().getBytes())); df_data.setAttribute(DISCUSSION_FORUM_DESC, encoded); } catch (Exception e) { //LOG.warn("Encode DF Extended Desc - " + e); df_data.setAttribute(DISCUSSION_FORUM_DESC, ""); } try { String encoded = new String( base64Encoder.encode(forum.getShortDescription().getBytes())); df_data.setAttribute(DISCUSSION_FORUM_SHORT_DESC, encoded); } catch (Exception e) { //LOG.warn("Encode DF Short Desc - " + e); df_data.setAttribute(DISCUSSION_FORUM_SHORT_DESC, ""); } List atts = forumManager.getForumById(true, forum.getId()).getAttachments(); for (int i = 0; i < atts.size(); i++) { Element forum_attachment = doc.createElement(ATTACHMENT); String attachId = ((Attachment) atts.get(i)).getAttachmentId(); forum_attachment.setAttribute(ATTACH_ID, attachId); df_data.appendChild(forum_attachment); } Set forumMembershipItems = forum.getMembershipItemSet(); if (forumMembershipItems != null && forumMembershipItems.size() > 0) { Element forum_permissions = doc.createElement(PERMISSIONS); Iterator membershipIter = forumMembershipItems.iterator(); while (membershipIter.hasNext()) { DBMembershipItem membershipItem = (DBMembershipItem) membershipIter.next(); Element permission = doc.createElement(PERMISSION); permission.setAttribute(PERMISSION_TYPE, membershipItem.getType().toString()); permission.setAttribute(PERMISSION_NAME, membershipItem.getName()); permission.setAttribute(PERMISSION_LEVEL_NAME, membershipItem.getPermissionLevelName()); if (PermissionLevelManager.PERMISSION_LEVEL_NAME_CUSTOM .equals(membershipItem.getPermissionLevelName())) { List customPerms = permissionManager.getCustomPermissions(); if (customPerms != null && customPerms.size() > 0) { Element customPermissions = doc.createElement(CUSTOM_PERMISSIONS); for (int i = 0; i < customPerms.size(); i++) { String name = (String) customPerms.get(i); String hasPermission = permissionManager .getCustomPermissionByName(name, membershipItem.getPermissionLevel()) .toString(); customPermissions.setAttribute(name, hasPermission); } permission.appendChild(customPermissions); } } forum_permissions.appendChild(permission); } df_data.appendChild(forum_permissions); } List topicList = dfManager .getTopicsByIdWithMessagesMembershipAndAttachments(forum.getId()); if (topicList != null && topicList.size() > 0) { Iterator topicIter = topicList.iterator(); while (topicIter.hasNext()) { DiscussionTopic topic = (DiscussionTopic) topicIter.next(); Element topic_data = doc.createElement(DISCUSSION_TOPIC); topic_data.setAttribute(TOPIC_TITLE, topic.getTitle()); topic_data.setAttribute(DRAFT, topic.getDraft().toString()); topic_data.setAttribute(LOCKED, topic.getLocked().toString()); topic_data.setAttribute(MODERATED, topic.getModerated().toString()); if (topic.getSortIndex() != null) { topic_data.setAttribute(SORT_INDEX, topic.getSortIndex().toString()); } else { topic_data.setAttribute(SORT_INDEX, ""); } Element topic_properties = doc.createElement(PROPERTIES); Element topic_short_desc = doc.createElement(PROPERTY); try { String encoded = new String( base64Encoder.encode(topic.getShortDescription().getBytes())); topic_short_desc.setAttribute(NAME, TOPIC_SHORT_DESC); topic_short_desc.setAttribute(ENCODE, BASE64); topic_short_desc.setAttribute(VALUE, encoded); } catch (Exception e) { //LOG.warn("Encode Topic Short Desc - " + e); topic_short_desc.setAttribute(NAME, TOPIC_SHORT_DESC); topic_short_desc.setAttribute(ENCODE, BASE64); topic_short_desc.setAttribute(VALUE, ""); } topic_properties.appendChild(topic_short_desc); Element topic_long_desc = doc.createElement(PROPERTY); try { String encoded = new String(base64Encoder .encode(topic.getExtendedDescription().getBytes())); topic_long_desc.setAttribute(NAME, TOPIC_LONG_DESC); topic_long_desc.setAttribute(ENCODE, BASE64); topic_long_desc.setAttribute(VALUE, encoded); } catch (Exception e) { //LOG.warn("Encode Topic Ext Desc - " + e); topic_long_desc.setAttribute(NAME, TOPIC_LONG_DESC); topic_long_desc.setAttribute(ENCODE, BASE64); topic_long_desc.setAttribute(VALUE, ""); } topic_properties.appendChild(topic_long_desc); topic_data.appendChild(topic_properties); // permissions Set topicMembershipItems = topic.getMembershipItemSet(); if (topicMembershipItems != null && topicMembershipItems.size() > 0) { Element topic_permissions = doc.createElement(PERMISSIONS); Iterator topicMembershipIter = topicMembershipItems.iterator(); while (topicMembershipIter.hasNext()) { DBMembershipItem membershipItem = (DBMembershipItem) topicMembershipIter .next(); Element permission = doc.createElement(PERMISSION); permission.setAttribute(PERMISSION_TYPE, membershipItem.getType().toString()); permission.setAttribute(PERMISSION_NAME, membershipItem.getName()); permission.setAttribute(PERMISSION_LEVEL_NAME, membershipItem.getPermissionLevelName()); topic_permissions.appendChild(permission); if (PermissionLevelManager.PERMISSION_LEVEL_NAME_CUSTOM .equals(membershipItem.getPermissionLevelName())) { List customPerms = permissionManager.getCustomPermissions(); if (customPerms != null && customPerms.size() > 0) { Element customPermissions = doc .createElement(CUSTOM_PERMISSIONS); for (int i = 0; i < customPerms.size(); i++) { String name = (String) customPerms.get(i); String hasPermission = permissionManager .getCustomPermissionByName(name, membershipItem.getPermissionLevel()) .toString(); customPermissions.setAttribute(name, hasPermission); } permission.appendChild(customPermissions); } } } topic_data.appendChild(topic_permissions); } List topicAtts = forumManager.getTopicByIdWithAttachments(topic.getId()) .getAttachments(); for (int j = 0; j < topicAtts.size(); j++) { Element topic_attachment = doc.createElement(ATTACHMENT); String attachId = ((Attachment) topicAtts.get(j)).getAttachmentId(); topic_attachment.setAttribute(ATTACH_ID, attachId); topic_data.appendChild(topic_attachment); } df_data.appendChild(topic_data); } } dfElement.appendChild(df_data); } } } results.append("archiving " + getLabel() + ": (" + forumCount + ") messageforum DF items archived successfully.\n"); ((Element) stack.peek()).appendChild(dfElement); stack.push(dfElement); } else { results.append("archiving " + getLabel() + ": empty messageforum DF archived.\n"); } } stack.pop(); } catch (DOMException e) { LOG.error(e.getMessage(), e); } return results.toString(); }