Ejemplo n.º 1
0
  @Test(expected = SendFailedException.class)
  public void testFreeMarkerTextMailMessageSendFailed() {
    String uuid = java.util.UUID.randomUUID().toString();
    String subject = "Text Message from $version Mail - " + uuid;
    String version = "Seam 3";

    // Port is two off so this should fail
    Wiser wiser = new Wiser(mailConfig.getServerPort() + 2);
    wiser.setHostname(mailConfig.getServerHost());
    try {
      wiser.start();

      person.setName(toName);
      person.setEmail(toAddress);

      mailMessage
          .get()
          .from(fromAddress)
          .replyTo(replyToAddress)
          .to(toAddress)
          .subject(new FreeMarkerTemplate(subject))
          .bodyText(
              new FreeMarkerTemplate(
                  resourceProvider.loadResourceStream("template.text.freemarker")))
          .put("person", person)
          .put("version", version)
          .importance(MessagePriority.HIGH)
          .send(session.get());
    } finally {
      stop(wiser);
    }
  }
Ejemplo n.º 2
0
  @Test(expected = SendFailedException.class)
  public void testTextMailMessageSendFailed() {
    String uuid = java.util.UUID.randomUUID().toString();
    String subject = "Text Message from $version Mail - " + uuid;
    String version = "Seam 3";
    mailConfig.setServerHost("localHost");
    mailConfig.setServerPort(8977);

    // Port is two off so this should fail
    Wiser wiser = new Wiser(mailConfig.getServerPort() + 2);
    try {
      wiser.start();

      person.setName(toName);
      person.setEmail(toAddress);

      mailMessage
          .get()
          .from(fromAddress, fromName)
          .replyTo(replyToAddress)
          .to(toAddress, toName)
          .subject(subject)
          .bodyText(new RenderTemplate(templateCompiler.get(), textTemplatePath))
          .put("person", person)
          .put("version", version)
          .importance(MessagePriority.HIGH)
          .send(session.get());
    } finally {
      stop(wiser);
    }
  }
 @Test
 @SpecAssertions({@SpecAssertion(section = DECORATOR_INVOCATION, id = "acb")})
 public void testDecoratorIsInvoked() {
   assertTrue(instance.isAmbiguous());
   Mule mule = instance.get();
   assertNotNull(mule);
 }
Ejemplo n.º 4
0
 @Override
 protected Object createTest() throws Exception {
   Instance<?> select = CDI.current().select(getTestClass().getJavaClass());
   if (select.isUnsatisfied()) {
     return getTestClass().getJavaClass().newInstance();
   } else {
     return select.get();
   }
 }
Ejemplo n.º 5
0
  @Test
  public void testSMTPSessionAuthentication() throws MessagingException, MalformedURLException {
    String subject = "HTML+Text Message from Seam Mail - " + java.util.UUID.randomUUID().toString();

    mailConfig.setServerHost("localHost");
    mailConfig.setServerPort(8978);

    Wiser wiser = new Wiser(mailConfig.getServerPort());
    wiser
        .getServer()
        .setAuthenticationHandlerFactory(
            new EasyAuthenticationHandlerFactory(new SMTPAuthenticator("test", "test12!")));
    try {
      wiser.start();

      person.setName(toName);
      person.setEmail(toAddress);

      mailMessage
          .get()
          .from(fromAddress, fromName)
          .to(person.getEmail(), person.getName())
          .subject(subject)
          .put("person", person)
          .put("version", "Seam 3")
          .bodyHtmlTextAlt(
              new RenderTemplate(templateCompiler.get(), htmlTemplatePath),
              new RenderTemplate(templateCompiler.get(), textTemplatePath))
          .importance(MessagePriority.LOW)
          .deliveryReceipt(fromAddress)
          .readReceipt("seam.test")
          .addAttachment(
              "htmlTemplatePath",
              "text/html",
              ContentDisposition.ATTACHMENT,
              resourceProvider.loadResourceStream(htmlTemplatePath))
          .addAttachment(
              new URLAttachment(
                  "http://design.jboss.org/seam/logo/final/seam_mail_85px.png",
                  "seamLogo.png",
                  ContentDisposition.INLINE))
          .send(gmailSession);
    } finally {
      stop(wiser);
    }

    Assert.assertTrue(
        "Didn't receive the expected amount of messages. Expected 1 got "
            + wiser.getMessages().size(),
        wiser.getMessages().size() == 1);

    MimeMessage mess = wiser.getMessages().get(0).getMimeMessage();

    Assert.assertEquals(
        "Subject has been modified", subject, MimeUtility.unfold(mess.getHeader("Subject", null)));
  }
Ejemplo n.º 6
0
 /**
  * {@link IdentityManager} instances are produced accordingly to the current {@link Partition} in
  * use. If no partition is provided, the default partition will be used.
  *
  * @return
  */
 @Produces
 @RequestScoped
 public IdentityManager createIdentityManager() {
   if (defaultPartition.isUnsatisfied() || defaultPartition.get() == null) {
     return new SecuredIdentityManager(this.partitionManager.createIdentityManager());
   } else {
     return new SecuredIdentityManager(
         this.partitionManager.createIdentityManager(defaultPartition.get()));
   }
 }
  @Test
  public void test() {
    WeldContainer weld = new Weld().initialize();
    Instance<CalculatorService> instance = weld.instance().select(CalculatorService.class);
    CalculatorService service = instance.get();

    assertEquals(21, service.sum(Arrays.asList(1, 2, 3, 4, 5, 6)));

    double resultDiv = service.div(42.0, 2.0);
    assertEquals(21.0, resultDiv, 0.0001);
  }
 /**
  * Creates a proper configuration form.
  *
  * @param policyDef
  */
 public IPolicyConfigurationForm createForm(PolicyDefinitionBean policyDef) {
   if ("IPWhitelistPolicy".equals(policyDef.getId())) { // $NON-NLS-1$
     return ipListFormFactory.get();
   }
   if ("IPBlacklistPolicy".equals(policyDef.getId())) { // $NON-NLS-1$
     return ipListFormFactory.get();
   }
   if ("BASICAuthenticationPolicy".equals(policyDef.getId())) { // $NON-NLS-1$
     return basicAuthFormFactory.get();
   }
   return defaultFormFactory.get();
 }
Ejemplo n.º 9
0
  @Override
  public void execute(FacesContext context) throws FacesException {
    /*
     * 1. Find the bean + method that matches the correct @RequestMapping.
     */
    Set<Bean<?>> beans = getBeanManager().getBeans(Object.class, new AnnotationLiteral<Any>() {});
    Iterator<Bean<?>> beanIterator = beans.iterator();
    RequestMappingInfo current = null;

    while (beanIterator.hasNext()) {
      Bean<?> bean = beanIterator.next();
      RequestMappingInfo info = findMethodRequestMapping(context, bean);

      if (current == null) {
        current = info;
      } else if (info != null && info.getLength() > current.getLength()) {
        current = info;
      }
    }

    String viewId = null;

    if (current != null) {
      /*
       * 2. Get an instance of that bean.
       */
      Instance instance =
          CDI.current().select(current.getBean().getBeanClass(), new AnnotationLiteral<Any>() {});

      try {
        /*
         * 3. Call the required method and capture its result.
         *
         * Currently assuming String invoke() signature, but that obviously
         * needs to be expanded.
         */
        viewId = (String) current.getMethod().invoke(instance.get(), new Object[0]);
      } catch (Throwable throwable) {
        throw new FacesException(throwable);
      }
      if (context.getViewRoot() == null) {
        UIViewRoot viewRoot = new UIViewRoot();
        viewRoot.setRenderKitId("HTML_BASIC");
        /*
         * 4. Set the resulting view id on the viewroot.
         */
        viewRoot.setViewId(viewId);
        context.setViewRoot(viewRoot);
      }
    }
  }
 @Produces
 public ServletDescriptor jerseyServlet() {
   String urlPattern = restServerConfiguration.getRestServletMapping();
   if (!applicationInstance.isUnsatisfied() && !applicationInstance.isAmbiguous()) {
     ApplicationPath annotation =
         ClassUtils.getAnnotation(applicationInstance.get().getClass(), ApplicationPath.class);
     if (annotation != null) {
       String path = annotation.value();
       urlPattern = path.endsWith("/") ? path + "*" : path + "/*";
     }
   }
   return new ServletDescriptor(
       SERVLET_NAME, null, new String[] {urlPattern}, 1, null, true, ServletContainer.class);
 }
  @Override
  public void doSearch() {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<QuestionType> cquery = builder.createQuery(QuestionType.class);
    Root<QuestionType> rqt = cquery.from(QuestionType.class);

    cquery
        .select(rqt)
        .where(
            builder.like(
                builder.lower(rqt.get(QuestionType_.name)), searchCriteria.getSearchPattern()));

    List<QuestionType> results =
        em.createQuery(cquery)
            .setMaxResults(searchCriteria.getFetchSize())
            .setFirstResult(searchCriteria.getFetchOffset())
            .getResultList();

    nextPageAvailable = results.size() > searchCriteria.getPageSize();
    if (nextPageAvailable) {
      // NOTE create new ArrayList since subList creates unserializable list
      questionTypes = new ArrayList<QuestionType>(results.subList(0, searchCriteria.getPageSize()));
    } else {
      questionTypes = results;
    }
    log.info(
        messageBuilder
            .get()
            .text("Found {0} hotel(s) matching search term [ {1} ] (limit {2})")
            .textParams(
                questionTypes.size(), searchCriteria.getQuery(), searchCriteria.getPageSize())
            .build()
            .getText());
  }
Ejemplo n.º 12
0
  protected <T> T safeGet(Instance<T> instance) {
    try {
      T object = instance.get();
      logger.debug("About to set object {} on task service", object);
      return object;
    } catch (AmbiguousResolutionException e) {
      // special handling in case cdi discovered multiple injections
      // that are actually same instances - e.g. weld on tomcat
      HashSet<T> available = new HashSet<T>();

      for (T object : instance) {
        available.add(object);
      }

      if (available.size() == 1) {
        return available.iterator().next();
      } else {
        throw e;
      }
    } catch (Throwable e) {
      logger.warn("Cannot get value of of instance {} due to {}", instance, e.getMessage());
    }

    return null;
  }
  @Override
  public Set<MavenRepositoryMetadata> getRepositoriesResolvingArtifact(
      final String pomXML, final MavenRepositoryMetadata... filter) {
    GAVPreferences gavPreferences = gavPreferencesProvider.get();
    gavPreferences.load();
    if (gavPreferences.isConflictingGAVCheckDisabled()) {
      return Collections.EMPTY_SET;
    }

    final InputStream pomStream = new ByteArrayInputStream(pomXML.getBytes(StandardCharsets.UTF_8));
    final MavenProject mavenProject = MavenProjectLoader.parseMavenPom(pomStream);
    final GAV gav =
        new GAV(mavenProject.getGroupId(), mavenProject.getArtifactId(), mavenProject.getVersion());

    final Set<MavenRepositoryMetadata> repositoriesResolvingArtifact =
        new HashSet<MavenRepositoryMetadata>();
    repositoriesResolvingArtifact.addAll(getRepositoriesResolvingArtifact(gav, mavenProject));

    // Filter results if necessary
    if (filter != null && filter.length > 0) {
      repositoriesResolvingArtifact.retainAll(Arrays.asList(filter));
    }

    return repositoriesResolvingArtifact;
  }
  @Produces
  @ApplicationScoped
  public Options commandLineInterfaceOptions() {
    Options options = new Options();

    options.addOption(
        builder()
            .longOpt("download-dataset")
            .desc("This option will download the dataset from internet")
            .build());

    options.addOption(
        builder().longOpt("dataset-dir").desc("Set the dataset directory path").build());

    options.addOption(builder().longOpt("help").desc("Print this message").build());

    experiments.forEach(
        experiment -> {
          Experiment annotation = experiment.getClass().getAnnotation(Experiment.class);

          options.addOption(
              builder()
                  .longOpt(annotation.name() + "-experiment")
                  .desc(annotation.description())
                  .build());
        });

    return options;
  }
 @Produces
 @Random
 public Room getRandomRoom() {
   List<String> roomNames = getRoomNames();
   String roomName = roomNames.get(random.nextInt(roomNames.size()));
   return roomInstance.select(new RoomName.RoomNameLiteral(roomName)).get();
 }
Ejemplo n.º 16
0
  @Override
  public User getUser() {
    User user = null;

    try {
      if (config.getMode() == ModeType.MOCK) {
        user =
            new User() {

              private static final long serialVersionUID = 1L;

              @Override
              public String getId() {
                return "mockuser";
              }

              @Override
              public Object getAttribute(Object key) {
                return null;
              }

              @Override
              public void setAttribute(Object key, Object value) {}
            };
      } else {
        user = service.get().getUser(credential.getUsername());
      }

    } catch (RaseaException e) {
      // TODO Colocar uma mensagem amigável para o programador saber o que ocorreu.
      e.printStackTrace();
    }

    return user;
  }
 @Test
 public void testAvailableTimeZonesProducerViaBean() {
   Assert.assertNotNull(availBean);
   List<ForwardingTimeZone> list = availBean.get().getAvailTimeZones();
   Assert.assertNotNull(list);
   Assert.assertTrue(!list.isEmpty());
   Assert.assertTrue(list.size() > 0);
 }
Ejemplo n.º 18
0
 @PostConstruct
 public void reset() {
   this.smallest = 0;
   this.guess = 0;
   this.remainingGuesses = 10;
   this.biggest = maxNumber;
   this.number = randomNumber.get();
 }
Ejemplo n.º 19
0
 @Test
 public void createRoute() {
   EventBridge b = bridge.get();
   Route r = b.createRoute(RouteType.EGRESS, Object.class);
   Assert.assertNotNull(r);
   Assert.assertEquals(RouteType.EGRESS, r.getType());
   Assert.assertEquals(Object.class, r.getPayloadType());
 }
  @Override
  public <T> void validateField(
      final String factType,
      final String fieldName,
      final T value,
      final Callback<Set<ConstraintViolation<T>>> callback) {
    if (factType == null || factType.isEmpty()) {
      callback.callback(Collections.emptySet());
      return;
    }
    if (fieldName == null || fieldName.isEmpty()) {
      callback.callback(Collections.emptySet());
      return;
    }
    if (callback == null) {
      return;
    }

    if (validatorInstance.isUnsatisfied()) {
      callback.callback(Collections.emptySet());
      return;

    } else if (validator == null) {
      validator = validatorInstance.get();
    }

    getTypeFieldsAnnotations(
        factType,
        (Map<String, Set<Annotation>> result) -> {
          final Set<ConstraintViolation<T>> violations = new HashSet<>();
          final Set<Annotation> fieldAnnotations = result.get(fieldName);
          if (fieldAnnotations == null || fieldAnnotations.isEmpty()) {
            callback.callback(violations);
            return;
          }

          for (Annotation fieldAnnotation : fieldAnnotations) {
            final Map<String, Object> fieldAnnotationAttributes = fieldAnnotation.getParameters();
            violations.addAll(
                validator.validate(
                    fieldAnnotation.getQualifiedTypeName(), fieldAnnotationAttributes, value));
          }
          callback.callback(violations);
        });
  }
 @Override
 public Relationship findById(Long id) {
   return queryBuilder
       .get()
       .select(RelationshipBean.class)
       .where()
       .equal(RelationshipBean_.id, id)
       .find();
 }
  @Override
  public Map<String, Object> getAttributes() {
    final ResourceConfig resourceConfig;
    if (!applicationInstance.isUnsatisfied() && !applicationInstance.isAmbiguous()) {
      resourceConfig = ResourceConfig.forApplication(applicationInstance.get());
    } else {
      resourceConfig = new ResourceConfig();
    }

    if (resourceConfig.getClasses().isEmpty()) {
      resourceConfig
          .registerClasses(jerseyCdiExtension.getProviders())
          .registerClasses(jerseyCdiExtension.getResources());
    }

    final String attributeName = RESOURCE_CONFIG + SERVLET_NAME;
    return singletonMap(attributeName, resourceConfig);
  }
  @AroundInvoke
  public Object manage(InvocationContext ic) throws Exception {

    if (!currentPlayer.get().isShot()) {
      // I'am doing science and I'am still alive!
      return ic.proceed();
    }

    return null;
  }
 @Test
 // WELD-556
 public void testDecoratedSFSBsAreRemoved() {
   StandardChickenHutch.reset();
   AlarmedChickenHutch.reset();
   chickenHutchInstance.get();
   assert StandardChickenHutch.isPing();
   assert AlarmedChickenHutch.isPing();
   assert StandardChickenHutch.isPredestroy();
 }
  @Override
  public Set<MavenRepositoryMetadata> getRepositoriesResolvingArtifact(
      final GAV gav, final Project project, final MavenRepositoryMetadata... filter) {
    GAVPreferences gavPreferences = gavPreferencesProvider.get();
    final PreferenceScopeResolutionStrategyInfo scopeResolutionStrategyInfo =
        scopeResolutionStrategies.getUserInfoFor(
            GuvnorPreferenceScopes.PROJECT, project.getEncodedIdentifier());
    gavPreferences.load(scopeResolutionStrategyInfo);
    if (gavPreferences.isConflictingGAVCheckDisabled()) {
      return Collections.EMPTY_SET;
    }

    final Set<MavenRepositoryMetadata> repositoriesResolvingArtifact =
        new HashSet<MavenRepositoryMetadata>();

    try {
      // Load Project's pom.xml
      final Path pomXMLPath = project.getPomXMLPath();
      final org.uberfire.java.nio.file.Path nioPomXMLPath = Paths.convert(pomXMLPath);
      final String pomXML = ioService.readAllString(nioPomXMLPath);

      final InputStream pomStream =
          new ByteArrayInputStream(pomXML.getBytes(StandardCharsets.UTF_8));
      final MavenProject mavenProject = MavenProjectLoader.parseMavenPom(pomStream);
      repositoriesResolvingArtifact.addAll(getRepositoriesResolvingArtifact(gav, mavenProject));

      // Filter results if necessary
      if (filter != null && filter.length > 0) {
        repositoriesResolvingArtifact.retainAll(Arrays.asList(filter));
      }

    } catch (IllegalArgumentException iae) {
      log.error(
          "Unable to get Remote Repositories for Project '"
              + project.getProjectName()
              + "'. Returning empty Collection. ",
          iae);

    } catch (NoSuchFileException nsfe) {
      log.error(
          "Unable to get Remote Repositories for Project '"
              + project.getProjectName()
              + "'. Returning empty Collection. ",
          nsfe);

    } catch (org.uberfire.java.nio.IOException ioe) {
      log.error(
          "Unable to get Remote Repositories for Project '"
              + project.getProjectName()
              + "'. Returning empty Collection. ",
          ioe);
    }

    return repositoriesResolvingArtifact;
  }
Ejemplo n.º 26
0
 public void pullStateItem() {
   FacesContext facesContext = context.get();
   if (facesContext != null
       && !facesContext.isPostback()
       && facesContext.getExternalContext().getRequestParameterMap().get("itemIndex") != null) {
     Integer itemIndex =
         Integer.valueOf(
             facesContext.getExternalContext().getRequestParameterMap().get("itemIndex"));
     this.pullStateItem(itemIndex);
   }
 }
Ejemplo n.º 27
0
 @Timeout
 public void timeout(Timer timer) {
   if (beanManager.getContext(ApplicationScoped.class).isActive()) {
     applicationScopeActive = true;
     if (beanId > 0.0) {
       if (beanId == simpleApplicationBeanInstance.get().getId()) {
         sameBean = true;
       }
     } else {
       beanId = simpleApplicationBeanInstance.get().getId();
     }
   }
   // CDITCK-221 - applicationScopeActive, beanId and sameBean have been set and are testable
   if (timer.getInfo().equals(CLIMB_COMMAND)) {
     climbed = true;
   }
   if (timer.getInfo().equals(DESCEND_COMMAND)) {
     descended = true;
   }
 }
Ejemplo n.º 28
0
 private void removeSessions(SamlNameId nameId, String idpEntityId, List<String> sessionIndexes) {
   for (SamlSpSessionImpl session : samlSpSessions.getSessions()) {
     if (session.getPrincipal().getNameId().equals(nameId)
         && session.getIdentityProvider().getEntityId().equals(idpEntityId)) {
       if (sessionIndexes.size() == 0 || sessionIndexes.contains(session.getSessionIndex())) {
         samlSpSessions.removeSession((SamlSpSessionImpl) session);
         samlServiceProviderSpi.get().loggedOut(session);
       }
     }
   }
 }
Ejemplo n.º 29
0
  private void configure() {
    String repositoryAlias = "";
    String branchName = "";
    if (!this.configured) {

      String uuid = Utils.getUUID(httpRequest.get());
      if (uuid == null) {
        uuid = httpRequest.get().getParameter("assetId");
      }
      if (uuid == null && path != null) {
        uuid = path;
      }
      if (uuid != null) {

        if (uuid.indexOf("@") == -1) {
          // simple fs pattern
          Pattern pattern = Pattern.compile(SEP + "(.*?)" + SEP);
          Matcher matcher = pattern.matcher(uuid);
          if (matcher.find()) {
            repositoryAlias = matcher.group(1);
          }
        } else {
          // git based pattern
          Pattern pattern = Pattern.compile("(://)(.*?)@(.*?)/");
          Matcher matcher = pattern.matcher(uuid);
          if (matcher.find()) {
            branchName = matcher.group(2);
            repositoryAlias = matcher.group(3);
          }
        }
      }

      RepositoryDescriptor found = provider.getRepositoryDescriptor(repositoryAlias, branchName);
      this.fileSystem = found.getFileSystem();
      this.repositoryRoot = found.getRepositoryRoot();
      this.repositoryRootPath = found.getRepositoryRootPath();
    }
  }
Ejemplo n.º 30
0
  public String update() {
    Login login = loginUser.get();
    this.conversation.end();

    try {
      if (this.id == null) {
        this.profiloUsoConsumo.setOwnerid(
            new OwnerId(login.getCurrentUser(), login.getCurrentDomain()));
        PermissionProp pp = new PermissionProp();
        pp.setSUBSETDOMAIN(SecAttrib.CONTROL);
        pp.setIDENTITYDOMAIN(SecAttrib.CONTROL);
        pp.setINTERSECTIONDOMAIN(SecAttrib.READ);
        pp.setOTHER(SecAttrib.NONE);

        this.profiloUsoConsumo.setPermissionprop(pp);

        ComposizioneEdifici comp =
            this.entityManager.merge(this.profiloUsoConsumo.getComposizioneEdificio());
        this.profiloUsoConsumo.setComposizioneEdificio(comp);
        this.entityManager.persist(this.profiloUsoConsumo);
        /*
        	ComposizioneEdifici comp=this.profiloUsoConsumo.getComposizioneEdificio();
        if (comp!=null) {
         comp=this.entityManager.find(ComposizioneEdifici.class, comp.getId());
          comp.addProfilo(this.profiloUsoConsumo);
           this.entityManager.merge(comp);
         }
        	 */

        return "search?faces-redirect=true";
      } else {
        // salvo dall'altro lato della relazione
        ComposizioneEdifici comp = this.profiloUsoConsumo.getComposizioneEdificio();
        /*
         	 if (comp!=null)
          {
        comp=this.entityManager.find(ComposizioneEdifici.class, comp.getId());
          comp.addProfilo(this.profiloUsoConsumo);
           this.entityManager.merge(comp);
            }
         	*/
        this.entityManager.merge(this.profiloUsoConsumo);
        return "view?faces-redirect=true&id=" + this.profiloUsoConsumo.getId();
      }

    } catch (Exception e) {
      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
      return null;
    }
  }