@Override
  public Configuration getConfiguration(GraphContext context) {
    return ConfigurationBuilder.begin()
        .addRule()
        // for all files ending in java, properties, and xml,
        // query for the regular expression {ip}
        .when(FileContent.matches("{ip}").inFilesNamed("{*}.{type}"))
        .perform(
            new AbstractIterationOperation<FileLocationModel>() {
              // when a result is found, create an inline hint.
              // reference the inline hint with the static ip marker so that we can query for it
              // in the static ip report.
              public void perform(
                  GraphRewrite event, EvaluationContext context, FileLocationModel payload) {
                // for all file location models that match the regular expression in the where
                // clause, add
                // the IP Location Model to the
                // graph
                StaticIPLocationModel location =
                    GraphService.addTypeToModel(
                        event.getGraphContext(), payload, StaticIPLocationModel.class);

                location.setTitle("Static IP: " + location.getSourceSnippit());
                location.setHint(
                    "When migrating environments, static IP addresses may need to be modified or eliminated.");
                location.setEffort(0);
              }
            })
        .where("ip")
        .matches("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b")
        .where("type")
        .matches("java|properties|xml");
  }
    @Override
    public Configuration getConfiguration(RuleLoaderContext ruleLoaderContext) {
      Set<String> catchallTags = Collections.singleton("catchall");
      Set<String> otherTags = new HashSet<>();
      otherTags.add("tag1");
      otherTags.add("tag2");
      otherTags.add("tag3");

      return ConfigurationBuilder.begin()
          .addRule()
          .when(JavaClass.references("java.util.{*}"))
          .perform(
              Hint.titled("java.util.* found")
                  .withText("Catchall hint is here")
                  .withEffort(7)
                  .withTags(catchallTags))
          .addRule()
          .when(JavaClass.references("java.net.URL"))
          .perform(
              Hint.titled("java.net.URL")
                  .withText("Java Net URL is here (no catchall")
                  .withEffort(13)
                  .withTags(otherTags))
          .addRule()
          .when(JavaClass.references("java.util.HashMap"))
          .perform(
              Hint.titled("java.util.HashMap")
                  .withText("Java Net URL is here (no catchall")
                  .withEffort(42));
    }
  @Override
  public Configuration getConfiguration(GraphContext context) {
    ConditionBuilder applicationsFound = Query.fromType(WindupConfigurationModel.class);

    AbstractIterationOperation<WindupConfigurationModel> addApplicationReportIndex =
        new AbstractIterationOperation<WindupConfigurationModel>() {
          @Override
          public void perform(
              GraphRewrite event, EvaluationContext context, WindupConfigurationModel payload) {
            for (FileModel inputPath : payload.getInputPaths()) {
              ProjectModel projectModel = inputPath.getProjectModel();
              if (projectModel == null) {
                throw new WindupException("Error, no project found in: " + inputPath.getFilePath());
              }
              createApplicationReportIndex(event.getGraphContext(), projectModel);
            }
          }

          @Override
          public String toString() {
            return "AddApplicationReportIndex";
          }
        };

    return ConfigurationBuilder.begin()
        .addRule()
        .when(applicationsFound)
        .perform(addApplicationReportIndex);
  }
    // @formatter:off
    @Override
    public Configuration getConfiguration(GraphContext context) {
      AbstractIterationOperation<FileLocationModel> addTypeRefToList =
          new AbstractIterationOperation<FileLocationModel>() {
            @Override
            public void perform(
                GraphRewrite event, EvaluationContext context, FileLocationModel payload) {
              xmlFiles.add(payload);
            }
          };

      return ConfigurationBuilder.begin()
          .addRule()
          .when(
              XmlFile.matchesXpath("/abc:beans")
                  .namespace("abc", "http://www.springframework.org/schema/beans")
                  .as("first"))
          .perform(
              Classification.as("Spring File")
                  .and(
                      Iteration.over("first")
                          .when(
                              XmlFile.from(Iteration.singleVariableIterationName("first"))
                                  .matchesXpath("//windupv1:file-gate")
                                  .namespace("windupv1", "http://www.jboss.org/schema/windup"))
                          .perform(addTypeRefToList)
                          .endIteration()));
    }
  @Override
  public Configuration getConfiguration(final ServletContext context) {
    return ConfigurationBuilder.begin()

        // one single transformer
        .addRule()
        .when(Path.matches("{something}.txt").where("something").matches(".*"))
        .perform(Transform.with(UppercaseTransformer.class));
  }
  @Override
  public Configuration getConfiguration(final ServletContext context) {
    Configuration config =
        ConfigurationBuilder.begin()
            .addRule()
            .when(Direction.isInbound().and(Path.matches("/{path}")))
            .perform(Forward.to("/{path}/{path}"))
            .addRule()
            .when(Direction.isInbound().and(Path.matches("/success/success")))
            .perform(SendStatus.code(200));

    return config;
  }
 // @formatter:off
 @Override
 public Configuration getConfiguration(RuleLoaderContext ruleLoaderContext) {
   return ConfigurationBuilder.begin()
       .addRule()
       .perform(
           new GraphOperation() {
             @Override
             public void perform(GraphRewrite event, EvaluationContext context) {
               WindupConfigurationModel configuration =
                   WindupConfigurationService.getConfigurationModel(event.getGraphContext());
               for (FileModel inputPath : configuration.getInputPaths()) {
                 createReportIndex(event.getGraphContext(), inputPath.getProjectModel());
               }
             }
           });
 }
  @Override
  public Configuration getConfiguration(final ServletContext context) {
    Configuration config =
        ConfigurationBuilder.begin()
            .addRule(Join.path("/metadata").to("/internalMetadata"))
            .addRule()
            .perform(Log.message(Level.INFO, "Just loggin somethin'."))
            .addRule()
            .when(Path.matches("/internalMetadata"))
            .perform(
                new Operation() {
                  @Override
                  public void perform(Rewrite event, EvaluationContext context) {
                    throw new IllegalStateException("expected");
                  }
                });

    return config;
  }
 // @formatter:off
 @Override
 public Configuration getConfiguration(GraphContext context) {
   return ConfigurationBuilder.begin()
       .addRule()
       .when(Query.find(FileModel.class).withProperty(FileModel.IS_DIRECTORY, true))
       .perform(
           Iteration.over(FileModel.class)
               .perform(new RecurseDirectoryAndAddFiles())
               .endIteration())
       .addRule()
       .when(
           Query.find(FileModel.class)
               .withProperty(FileModel.IS_DIRECTORY, false)
               .withProperty(
                   FileModel.FILE_PATH,
                   QueryPropertyComparisonType.REGEX,
                   ZipUtil.getEndsWithZipRegularExpression()))
       .perform(Iteration.over().perform(new AddArchiveReferenceInformation()).endIteration());
 }
 @Override
 public Configuration getConfiguration(final ServletContext context) {
   return ConfigurationBuilder.begin()
       .addRule()
       .when(
           Direction.isInbound().and(Path.matches("/forward")).and(RequestParameter.exists("foo")))
       .perform(Forward.to("/forward2?baz=cab"))
       .addRule()
       .when(
           Direction.isInbound()
               .and(Path.matches("/forward2"))
               .and(RequestParameter.exists("foo"))
               .and(RequestParameter.exists("baz")))
       .perform(SendStatus.code(200))
       .addRule()
       .when(
           Direction.isInbound()
               .and(Path.matches("/forward-fail"))
               .and(RequestParameter.exists("foo")))
       .perform(Forward.to("/forward2"));
 }
 @Override
 public Configuration getConfiguration(final ServletContext context) {
   Configuration config =
       ConfigurationBuilder.begin()
           .addRule(Join.path("/{lang}/{path}.xhtml").to("/{path}.xhtml"))
           .where("path")
           .transposedBy(LocaleTransposition.bundle("bundle", "lang"))
           .addRule(Join.path("/{lang}/{path}").to("/{path}"))
           .where("path")
           .configuredBy(LocaleTransposition.bundle("bundle", "lang"))
           .addRule(Join.path("/{lang}/{path}/transposition_only").to("/{path}"))
           .where("path")
           .transposedBy(LocaleTransposition.bundle("bundle", "lang"))
           .addRule(Join.path("/{lang}/{path}/transposition_failed_1").to("/{path}"))
           .where("path")
           .transposedBy(
               LocaleTransposition.bundle("bundle", "lang")
                   .onTranspositionFailed(
                       new HttpOperation() {
                         @Override
                         public void performHttp(
                             HttpServletRewrite event, EvaluationContext context) {
                           SendStatus.code(201).performHttp(event, context);
                         }
                       }))
           .addRule(Join.path("/{lang}/{path}/transposition_failed_2").to("/{path}"))
           .where("path")
           .transposedBy(
               LocaleTransposition.bundle("bundle", "lang")
                   .onTranspositionFailed(
                       new HttpOperation() {
                         @Override
                         public void performHttp(
                             HttpServletRewrite event, EvaluationContext context) {
                           SendStatus.code(202).performHttp(event, context);
                         }
                       }));
   return config;
 }
 /**
  * Uses the ReWrtie ConfigurationBuilder to define a set of rules used for the URL rewriting. We
  * define a single rule that rewrites requests for the index page if the request is determined to
  * originate from a mobile browser.
  *
  * @param context the ServletContext
  * @return the ReWrite Configuration
  */
 @Override
 public Configuration getConfiguration(final ServletContext context) {
   return ConfigurationBuilder.begin()
       .defineRule()
       .when(
           Direction.isInbound()
               .and(Path.matches("/").or(Path.matches("/index.jsf")))
               .and(
                   new HttpCondition() {
                     @Override
                     public boolean evaluateHttp(
                         HttpServletRewrite httpServletRewrite,
                         EvaluationContext evaluationContext) {
                       HttpServletRequest request = httpServletRewrite.getRequest();
                       String userAgentStr = request.getHeader("user-agent");
                       String httpAccept = request.getHeader("Accept");
                       UAgentInfo uAgentInfo = new UAgentInfo(userAgentStr, httpAccept);
                       return uAgentInfo.detectTierIphone() || uAgentInfo.detectTierTablet();
                     }
                   }))
       .perform(Forward.to("/secure/mobile/addSale.jsf"));
 }
Esempio n. 13
0
  @Override
  public Configuration getConfiguration(GraphContext arg0) {
    ConditionBuilder allProjects = Query.find(MavenProjectModel.class).as("projectModels");

    AbstractIterationOperation<MavenProjectModel> setupParentModule =
        new AbstractIterationOperation<MavenProjectModel>(MavenProjectModel.class, "projectModel") {
          @Override
          public void perform(
              GraphRewrite event, EvaluationContext context, MavenProjectModel payload) {
            setMavenParentProject(payload);
          }
        };

    return ConfigurationBuilder.begin()
        .addRule()
        .when(allProjects)
        .perform(
            Iteration.over("projectModels")
                .as("projectModel")
                .perform(setupParentModule)
                .endIteration());
  }
 /* (non-Javadoc)
  * @see org.ocpsoft.rewrite.config.ConfigurationProvider#getConfiguration(java.lang.Object)
  */
 @Override
 public Configuration getConfiguration(ServletContext context) {
   log.debug("Preparing legacy Person rewrite configuration");
   final ConfigurationBuilder builder = ConfigurationBuilder.begin();
   for (Map.Entry<String, TenantState> entry : tenantRepo.getStates().entrySet()) {
     if (entry.getValue() == TenantState.ACTIVE) {
       final String tenantId = entry.getKey();
       final PersonRepository personRepo = personRepos.get(tenantId);
       final Set<String> slugPaths = personRepo.findAllSlugsByStatus(StatusMask.ACTIVE_ONLY);
       if (!slugPaths.isEmpty()) {
         log.debug("{}» Rewriting {} old Person URIs", tenantId, slugPaths.size());
         for (String slugPath : slugPaths) {
           builder
               .addRule()
               .when(Direction.isInbound().and(Path.matches("/" + slugPath)))
               .perform(
                   Redirect.permanent(
                       "/" + SeoBookmarkableMapper.DEFAULT_LOCALE_PREF_ID + "/" + slugPath));
         }
       }
     }
   }
   return builder;
 }
Esempio n. 15
0
 @Override
 public final Configuration getConfiguration(RuleLoaderContext ruleLoaderContext) {
   return ConfigurationBuilder.begin().addRule().when(this).perform(this);
 }
Esempio n. 16
0
  @Override
  public Configuration getConfiguration(final ServletContext context) {
    return ConfigurationBuilder.begin()
        .defineRule()

        /**
         * Define the inbound conditions and conversion mechanisms to be used when handling inbound
         * requests.
         */
        .when(
            Method.isGet()
                .and(
                    Path.matches("/store/product/{pid}")
                        .where("pid")
                        .matches("\\d+")
                        .constrainedBy(
                            new Constraint<String>() {
                              @Override
                              public boolean isSatisfiedBy(
                                  Rewrite event, EvaluationContext context, String value) {
                                Integer valueOf = Integer.valueOf(value);
                                return false;
                              }
                            })
                        .bindsTo(
                            Evaluation.property("pid")
                                .convertedBy(ProductConverter.class)
                                .validatedBy(ProductValidator.class))))
        .perform(
            new HttpOperation() {
              @Override
              public void performHttp(
                  final HttpServletRewrite event, final EvaluationContext context) {
                /**
                 * Extract the stored {pid} from our Path and load the Product. This is an example
                 * of how we can use a converter to directly bind and store the object we want into
                 * a binding. {@link Evaluation} is an low-level construct, and binds array values
                 * that must be dereferenced. If using other bindings such as {@link El}, the value
                 * will be bound directly to the type of the referenced property type, and this
                 * array downcast is not necessary.
                 */
                Product product = (Product) Evaluation.property("pid").retrieve(event, context);

                /**
                 * Marshal the Product into XML using JAXB. This has been extracted into a utility
                 * class.
                 */
                try {
                  XMLUtil.streamFromObject(
                      Product.class, product, event.getResponse().getOutputStream());
                } catch (IOException e) {
                  throw new RuntimeException(e);
                }

                /**
                 * Set the content type and status code of the response, this again could be
                 * extracted into a REST utility class.
                 */
                event.getResponse().setContentType("application/xml");
                ((HttpInboundServletRewrite) event).sendStatusCode(200);
              }
            })
        .defineRule()
        .when(Path.matches("/store/products").and(Method.isGet()))
        .perform(
            new HttpOperation() {
              @Override
              public void performHttp(
                  final HttpServletRewrite event, final EvaluationContext context) {
                try {
                  XMLUtil.streamFromObject(
                      ProductRegistry.class, products, event.getResponse().getOutputStream());
                  event.getResponse().setContentType("application/xml");
                  ((HttpInboundServletRewrite) event).sendStatusCode(200);
                } catch (Exception e) {
                  throw new RuntimeException(e);
                }
              }
            })
        .defineRule()
        .when(Path.matches("/store/products").and(Method.isPost()))
        .perform(
            new HttpOperation() {
              @Override
              public void performHttp(
                  final HttpServletRewrite event, final EvaluationContext context) {
                try {
                  Product product =
                      XMLUtil.streamToObject(Product.class, event.getRequest().getInputStream());
                  product = products.add(product);

                  /**
                   * Just for fun, set a response header containing the URL to the newly created
                   * Product.
                   */
                  String location =
                      new ParameterizedPattern(event.getContextPath() + "/store/product/{pid}")
                          .build(product.getId());
                  Response.addHeader("Location", location).perform(event, context);

                  event.getResponse().setContentType("text/html");
                  ((HttpInboundServletRewrite) event).sendStatusCode(200);
                } catch (Exception e) {
                  throw new RuntimeException(e);
                }
              }
            })
        .defineRule()
        .when(Path.matches("/"))
        .perform(
            new HttpOperation() {

              @Override
              public void performHttp(
                  final HttpServletRewrite event, final EvaluationContext context) {
                try {
                  PrintWriter writer = event.getResponse().getWriter();
                  writer.write(
                      "<html>"
                          + "<body>"
                          + "<h1>Rewrite Rest Demo</h1>"
                          + "Sorry for the boring page, there are no HTML pages in this demo! Try some of the following operations:"
                          + ""
                          + "<ul>"
                          + "<li>GET <a href=\""
                          + event.getContextPath()
                          + "/store/product/0\">/store/product/0</a></li>"
                          + "<li>GET <a href=\""
                          + event.getContextPath()
                          + "/store/products\">/store/products</a></li>"
                          + "<li>POST "
                          + event.getContextPath()
                          + "/store/products - This requires a rest client, or you can use `curl`<br/>"
                          + "curl --data \"&lt;product&gt;&lt;name&gt;James&lt;/name&gt;&lt;description&gt;yay&lt;/description&gt;&lt;price&gt;12.9&lt;/price&gt;&lt;/product&gt;\" http://localhost:8080/rewrite-showcase-rest/store/products</li>"
                          + "</ul>"
                          + "</body></html>");
                  SendStatus.code(200).perform(event, context);
                } catch (IOException e) {
                  throw new RuntimeException();
                }
              }
            });
  }