Package com.cedarsoft.wicket.breadcrumb

Source Code of com.cedarsoft.wicket.breadcrumb.PageStructure

/**
* Copyright (C) cedarsoft GmbH.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*         http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.cedarsoft.wicket.breadcrumb;

import com.cedarsoft.commons.struct.ChildNotFoundException;
import com.cedarsoft.commons.struct.Node;
import com.cedarsoft.commons.struct.Path;
import com.cedarsoft.commons.struct.Route;
import com.google.common.base.Strings;
import org.apache.wicket.Page;

import javax.annotation.Nonnull;
import java.util.ArrayDeque;
import java.util.Queue;

/**
*
*/
public class PageStructure {
  private Node rootNode;

  public PageStructure( @Nonnull Node rootNode ) {
    this.rootNode = rootNode;
  }

  @Nonnull
  public Node getRootNode() {
    return rootNode;
  }

  //todo cache results
  @Nonnull
  public Node findNode( @Nonnull Class<? extends Page> pageClass ) {
    Queue<Node> queue = new ArrayDeque<Node>();
    queue.add( rootNode );

    while ( !queue.isEmpty() ) {
      Node current = queue.poll();
      if ( pageClass.equals( current.getLookup().lookup( Class.class ) ) ) {
        return current;
      }
      queue.addAll( current.getChildren() );
    }
    throw new IllegalArgumentException( "No Node found for " + pageClass );
  }

  @Nonnull
  public Route getRoute( @Nonnull Path path ) throws ChildNotFoundException {
    return Route.buildRoute( getRootNode(), path );
  }

  @Nonnull
  public Route findRoute( @Nonnull Class<? extends Page> pageClass ) {
    Path path = findNode( pageClass ).getPath();
    return getRoute( path.absolute() );
  }

  @Override
  public String toString() {
    return getRootNode().toString();
  }

  @Nonnull
  public String toTree() {
    return toTree( rootNode, 0 );
  }

  @Nonnull
  private String toTree( @Nonnull Node node, int depth ) {
    StringBuilder builder = new StringBuilder();

    builder
      .append( Strings.repeat( "\t", depth ) )
      .append( "- " )
      .append( node.getName() ).append( "\n" );

    for ( Node child : node.getChildren() ) {
      builder.append( toTree( child, depth + 1 ) );
    }

    return builder.toString();
  }
}
TOP

Related Classes of com.cedarsoft.wicket.breadcrumb.PageStructure

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.