Exemplo n.º 1
0
  private void processBasicAuth(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    Context ctx = new SessionContext(new ServletRequestSessionMap(request));
    Identity identity = (Identity) ctx.get(Identity.class);

    if (identity == null) {
      throw new ServletException(
          "Identity not found - please ensure that the Identity component is created on startup.");
    }

    Credentials credentials = (Credentials) ctx.get(Credentials.class);

    boolean requireAuth = false;

    String header = request.getHeader("Authorization");
    if (header != null && header.startsWith("Basic ")) {
      String base64Token = header.substring(6);
      String token = new String(Base64.decode(base64Token));

      String username = "";
      String password = "";
      int delim = token.indexOf(":");

      if (delim != -1) {
        username = token.substring(0, delim);
        password = token.substring(delim + 1);
      }

      // Only reauthenticate if username doesn't match Identity.username and user isn't
      // authenticated
      if (!username.equals(credentials.getUsername()) || !identity.isLoggedIn()) {
        try {
          credentials.setPassword(password);
          authenticate(request, username);
        } catch (Exception ex) {
          log.warn("Error authenticating: " + ex.getMessage());
          requireAuth = true;
        }
      }
    }

    if (!identity.isLoggedIn() && !credentials.isSet()) {
      requireAuth = true;
    }

    try {
      if (!requireAuth) {
        chain.doFilter(request, response);
        return;
      }
    } catch (NotLoggedInException ex) {
      requireAuth = true;
    }

    if ((requireAuth && !identity.isLoggedIn())) {
      response.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authorized");
    }
  }
Exemplo n.º 2
0
  @TransactionAttribute
  public String guardar() {
    String salida = "";
    System.out.println("Guardar__________");
    Date now = Calendar.getInstance().getTime();
    getInstance().setLastUpdate(now);
    getInstance().setTiempoConsulta(FechasUtil.sumarRestaMinutosFecha(now, 5));
    try {
      if (getInstance().isPersistent()) {
        // System.out.println("Guardar__________1" + getInstance().getId());
        getInstance().setCode("REALIZADA");
        getInstance().setResponsable(profileS.getProfileByIdentityKey(identity.getUser().getKey()));
        getInstance().getSignosVitales().setFechaActual(now);
        // System.out.println("Guardar__________ 2");
        save(getInstance());
        if (turno.isPersistent()) {
          turno.setEstado("Realizada");
          save(turno);
        }
        FacesMessage msg =
            new FacesMessage(
                "Se actualizo Consulta Odontológica: " + getInstance().getId() + " con éxito");
        FacesContext.getCurrentInstance().addMessage("", msg);
        System.out.println("Guardar__________3");
      } else {
        getInstance().setCode("REALIZADA");
        getInstance().setFichaOdontologica(fichaOdontolog);
        getInstance().setResponsable(profileS.getProfileByIdentityKey(identity.getUser().getKey()));
        getInstance().getSignosVitales().setFechaActual(now);
        create(getInstance().getSignosVitales());
        create(getInstance());
        save(getInstance());
        if (turno.isPersistent()) {
          turno.setEstado("Realizada");
          save(turno);
        }
        FacesMessage msg =
            new FacesMessage(
                "Se creo nueva Consulta Odontológica: " + getInstance().getId() + " con éxito");
        FacesContext.getCurrentInstance().addMessage("", msg);

        salida =
            "/pages/depSalud/odontologia/consultaOdontologica.xhtml?faces-redirect=true"
                + "&fichaMedicaId="
                + getFichaMedicaId()
                + "&consultaOdontId="
                + getInstance().getId()
                + "&backView="
                + getBackView();
      }
    } catch (Exception e) {
      e.printStackTrace();
      FacesMessage msg = new FacesMessage("Error al guardar: " + getInstance().getId());
      FacesContext.getCurrentInstance().addMessage("", msg);
    }
    return salida;
  }
Exemplo n.º 3
0
  public void initialize() {
    log.debug("testing=" + isTesting());

    if (identity.isLoggedIn()) {
      log.debug("authenticated");
      // raiseLoginSuccessfulEvent();
      // return "authenticated";
    }

    if (isTesting()) {
      identity.logout();
      log.debug("not-authenticated");
      // return "testing";
    }

    /*
    if (username == null) {
    	ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    	HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    	username = request.getHeader("ARIES_USER");
    }
    */

    if (username == null) {
      log.debug("not-authenticated");
      // return "not-authenticated";
    }

    //		try {
    //			credentials.setUsername(username);
    //			credentials.setInitialized(true);
    //			SimplePrincipal principal = new SimplePrincipal(username);
    //			identity.acceptExternallyAuthenticatedPrincipal(principal);
    //			rememberMe.setEnabled(true);
    //		} catch (Exception e) {
    //			log.error("Error", e);
    //			return "";
    //		}

    log.info("logged in user: "******"logged in user: "******"Super-user: "******"authenticated");
    // raiseLoginSuccessfulEvent();
    // return "authenticated";
  }
 @Observer(value = KiWiEvents.CONTENT_UPDATED)
 public void onContentUpdated(ContentItem item) {
   User currentUser = (User) Component.getInstance("currentUser");
   Events.instance()
       .raiseAsynchronousEvent(
           KiWiEvents.CONTENT_UPDATED + "AsyncIE", item, currentUser, Identity.instance());
 }
Exemplo n.º 5
0
  public boolean authenticate() {
    log.debug("testing: " + isTesting());

    try {
      username = credentials.getUsername();
      String password = credentials.getPassword();

      if (StringUtils.isEmpty(username)) {
        messages.error("login", "User name must be specified.");
        return false;
      }

      if (username.equals("admin")) {
        identity.addRole("admin");
      }

      principal = userService.getUserByName(username);
      if (principal != null && principal.getPassword().equals(password)) {
        log.debug("authenticated: " + username);
        raiseUserAuthenticatedEvent();
        return true;
      }

      messages.error("login", "Invalid user name or password.");
      log.debug("not-authenticated");
      return false;

    } catch (Throwable e) {
      messages.error("login", e.getMessage());
      log.error("not-authenticated: " + e);
      return false;
    }
  }
Exemplo n.º 6
0
  public void init() {
    if (!isInitialized) {

      if (getFileId() == null)
        throw new InvalidWikiRequestException("Missing filedId request parameter");

      log.debug("initializing document history with file id: " + getFileId());

      if (currentFile == null) {
        log.debug("loading current file: " + getFileId());
        currentFile = wikiNodeDAO.findWikiDocument(getFileId());

        if (currentFile == null) {
          throw new org.jboss.seam.framework.EntityNotFoundException(
              getFileId(), WikiDocument.class);
        }

        if (!Identity.instance().hasPermission("Node", "read", currentFile)) {
          throw new AuthorizationException("You don't have permission for this operation");
        }
      }

      initializeHistoricalFileList();
    }

    isInitialized = true;
  }
Exemplo n.º 7
0
 private void handleLoadRuleAssetException(RuleAsset asset) {
   if (asset.metaData.categories.length == 0) {
     Identity.instance().checkPermission(new CategoryPathType(null), RoleTypes.ANALYST_READ);
   } else {
     RuntimeException exception = null;
     boolean passed = false;
     for (String cat : asset.metaData.categories) {
       try {
         Identity.instance().checkPermission(new CategoryPathType(cat), RoleTypes.ANALYST_READ);
         passed = true;
       } catch (RuntimeException re) {
         exception = re;
       }
     }
     if (!passed) {
       throw exception;
     }
   }
 }
 @Create
 public void create() {
   String userName = READ_ONLY_USER;
   if (Contexts.isApplicationContextActive()) {
     userName = Identity.instance().getCredentials().getUsername();
   }
   if (userName == null) {
     userName = READ_ONLY_USER;
   }
   repository = new RulesRepository(repositoryConfiguration.newSession(userName));
 }
 @Observer(value = KiWiEvents.ACTIVITY_REMOVETAG)
 public void onRemoveTag(User taggingUser, Tag tag) {
   User currentUser = (User) Component.getInstance("currentUser");
   Events.instance()
       .raiseAsynchronousEvent(
           KiWiEvents.ACTIVITY_REMOVETAG + "AsyncIE",
           taggingUser,
           tag,
           currentUser,
           Identity.instance());
 }
Exemplo n.º 10
0
 public boolean authenticate() {
   log.info("authenticating {0}", credentials.getUsername());
   // write your authentication logic here,
   // return true if the authentication was
   // successful, false otherwise
   if ("admin".equals(credentials.getUsername())) {
     identity.addRole("admin");
     return true;
   }
   return false;
 }
Exemplo n.º 11
0
 @SuppressWarnings("unchecked")
 public void loadMemberPictures() {
   memberImages =
       (List<MemberImage>)
           entityManager
               .createQuery(
                   "select i from MemberImage i where i.member.memberName = :name and not i = i.member.picture")
               .setParameter("name", memberName)
               .getResultList();
   Identity.instance().filterByPermission(memberImages, "view");
 }
Exemplo n.º 12
0
  public String exportAllData() {

    Identity.setSecurityEnabled(false);

    Collection<ContentItem> items = getContentItemService().getContentItems();

    File f = new File(pathToExportFile);
    OutputStream out = null;
    try {
      out = FileUtils.openOutputStream(f);
      exporter.exportItems(items, "application/x-kiwi", out);
    } catch (IOException ex) {
      log.error("Error by creating zip file #0", ex.getMessage());
    } finally {
      try {
        out.close();
      } catch (IOException ex) {
        log.error("Error by close outputstream #0", ex.getMessage());
      }
    }

    log.info("Create export file #0", f.getAbsolutePath());

    try {
      InputStream newIs = new FileInputStream(f);
      byte[] baBinary = new byte[newIs.available()];
      newIs.read(baBinary);

      HttpServletResponse response = (HttpServletResponse) extCtx.getResponse();

      String contentType = "application/zip";
      String fileName = "export.kiwi";

      response.setContentType(contentType);
      response.addHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");

      ServletOutputStream os = response.getOutputStream();
      os.write(baBinary);
      os.flush();
      os.close();
      facesContext.responseComplete();
    } catch (Exception ex) {
      log.error("Error by downloading file #0", ex.getMessage());
    } finally {
      try {
        out.close();
      } catch (IOException ex) {
        log.error("Error by close outputstream #0", ex.getMessage());
      }
    }

    return null;
  }
Exemplo n.º 13
0
 @TransactionAttribute
 public ConsultaOdontologica load() {
   if (isIdDefined()) {
     wire();
   }
   // log.info("sgssalud --> cargar instance " + getInstance());
   if (getInstance().isPersistent()) {
     if (getInstance().getResponsable() == null) {
       getInstance().setResponsable(profileS.getProfileByIdentityKey(identity.getUser().getKey()));
     }
   }
   return getInstance();
 }
Exemplo n.º 14
0
  /**
   * This actually does the hard work of loading up an asset based on its format.
   *
   * <p>Role-based Authorization check: This method can be accessed if user has following
   * permissions: 1. The user has a ANALYST_READ role or higher (i.e., ANALYST) and this role has
   * permission to access the category which the asset belongs to. Or. 2. The user has a
   * package.readonly role or higher (i.e., package.admin, package.developer) and this role has
   * permission to access the package which the asset belongs to.
   */
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public RuleAsset loadRuleAsset(String uuid) throws SerializationException {

    long time = System.currentTimeMillis();

    AssetItem item = getRulesRepository().loadAssetByUUID(uuid);
    RuleAsset asset = new RuleAsset();

    asset.uuid = item.getUUID();
    asset.name = item.getName();
    asset.description = item.getDescription();
    asset.lastModified = item.getLastModified().getTime();
    asset.lastContributor = item.getLastContributor();
    asset.state = (item.getState() != null) ? item.getState().getName() : "";
    asset.dateCreated = item.getCreatedDate().getTime();
    asset.checkinComment = item.getCheckinComment();
    asset.versionNumber = item.getVersionNumber();

    // load standard meta data
    asset.metaData = repositoryAssetOperations.populateMetaData(item);

    // Verify if the user has permission to access the asset through package
    // based permission.
    // If failed, then verify if the user has permission to access the asset
    // through category
    // based permission
    if (Contexts.isSessionContextActive()) {

      try {
        Identity.instance()
            .checkPermission(
                new PackageNameType(asset.metaData.packageName), RoleTypes.PACKAGE_READONLY);
      } catch (RuntimeException e) {
        handleLoadRuleAssetException(asset);
      }
    }

    PackageItem pkgItem = handlePackageItem(item, asset);

    log.debug(
        "Package: "
            + pkgItem.getName()
            + ", asset: "
            + item.getName()
            + ". Load time taken for asset: "
            + (System.currentTimeMillis() - time));
    UserInbox.recordOpeningEvent(item);
    return asset;
  }
Exemplo n.º 15
0
 @Override
 public void validerAuthorisation() {
   // On valide pour l'édition que l'utilisateur connecté est bien
   // propriétaire du bateau.
   if (getInstance().getUtilisateur() != null
       && utilisateurCourant != null
       && !getInstance()
           .getUtilisateur()
           .getPseudonyme()
           .equals(utilisateurCourant.getPseudonyme())
       && !Identity.instance().hasRole(Role.ADMIN)) {
     ResourceBundle messages = SeamResourceBundle.getBundle();
     throw new AuthorizationException(messages.getString("annonce.propriorequis"));
   }
 }
  @Test
  public void testLogin() throws Exception {
    Identity identity = Identity.instance();

    assertFalse(identity.isLoggedIn());

    identity.setUsername("gavin");
    identity.setPassword("foobar");
    identity.login();

    User user = (User) Component.getInstance("user");
    assertEquals("Gavin King", user.getName());
    assertEquals("gavin", user.getUsername());
    assertEquals("foobar", user.getPassword());
    assertFalse(Manager.instance().isLongRunningConversation());
    assertTrue(identity.isLoggedIn());

    identity.logout();
    assertTrue(Session.instance().isInvalid());

    assertFalse(identity.isLoggedIn());
  }
Exemplo n.º 17
0
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public void promoteAssetToGlobalArea(String uuid) {
    if (Contexts.isSessionContextActive()) {
      Identity.instance()
          .checkPermission(
              new PackageNameType(RulesRepository.RULE_GLOBAL_AREA), RoleTypes.PACKAGE_DEVELOPER);
    }

    log.info(
        "USER:"******" CHANGING PACKAGE OF asset: ["
            + uuid
            + "] to [ globalArea ]");
    getRulesRepository()
        .moveRuleItemPackage(RulesRepository.RULE_GLOBAL_AREA, uuid, "promote asset to globalArea");
  }
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public AnalysisReport analysePackage(String packageUUID) throws SerializationException {
    if (Contexts.isSessionContextActive()) {
      Identity.instance()
          .checkPermission(new PackageUUIDType(packageUUID), RoleType.PACKAGE_DEVELOPER.getName());
    }

    PackageItem packageItem = getAssetService().getRulesRepository().loadPackageByUUID(packageUUID);

    VerifierRunner runner = new VerifierRunner(defaultVerifier);

    AnalysisReport report =
        runner.verify(
            packageItem,
            new ScopesAgendaFilter(true, ScopesAgendaFilter.VERIFYING_SCOPE_KNOWLEDGE_PACKAGE));

    defaultVerifier.flushKnowledgeSession();

    return report;
  }
  private AnalysisReport performAssetVerification(
      RuleAsset asset, boolean useVerifierDefaultConfig, Set<String> activeWorkingSets)
      throws SerializationException {
    long startTime = System.currentTimeMillis();

    if (Contexts.isSessionContextActive()) {
      Identity.instance()
          .checkPermission(
              new PackageNameType(asset.getMetaData().getPackageName()),
              RoleType.PACKAGE_DEVELOPER.getName());
    }

    PackageItem packageItem =
        getAssetService().getRulesRepository().loadPackage(asset.getMetaData().getPackageName());

    List<String> constraintRules = applyWorkingSets(activeWorkingSets);

    Verifier verifierToBeUsed = null;
    if (useVerifierDefaultConfig) {
      verifierToBeUsed = defaultVerifier;
    } else {
      verifierToBeUsed = getWorkingSetVerifier(constraintRules);
    }

    log.debug("constraints rules: " + constraintRules);

    try {
      VerifierRunner runner = new VerifierRunner(verifierToBeUsed);
      AnalysisReport report = runner.verify(packageItem, chooseScopesAgendaFilterFor(asset));

      verifierToBeUsed.flushKnowledgeSession();

      log.debug("Asset verification took: " + (System.currentTimeMillis() - startTime));

      return report;

    } catch (Throwable t) {
      throw new SerializationException(t.getMessage());
    }
  }
Exemplo n.º 20
0
  /**
   * Import data from the reader provided as argument into the KiWi database.
   *
   * @param reader the reader from which to read the data
   * @param types the set of types to associate with each generated content item
   * @param tags the set of content items to use as tags
   * @param user the user to use as author of all imported data
   */
  @Override
  public int importData(
      Reader reader,
      String format,
      final Set<KiWiUriResource> types,
      final Set<ContentItem> tags,
      final User user,
      final Collection<ContentItem> output) {
    SyndFeedInput input = new SyndFeedInput();

    int count = 0;
    try {
      final SyndFeed feed = input.build(reader);

      Identity.setSecurityEnabled(false);
      count = importData(feed, types, tags, user, output);

    } catch (FeedException ex) {
      log.error("RSS/Atom feed could not be parsed", ex);
    }
    return count;
  }
Exemplo n.º 21
0
 /**
  * Enforce the list of applicable annotations, by firing an AuthorizationCheckEvent. The event is
  * then inspected to determine if access is allowed. Faces navigation is then re-routed to
  * the @LoginView if the user is not logged in, otherwise to the @AccessDenied view.
  *
  * @param context
  * @param viewRoot
  * @param annotations
  */
 private void enforce(
     FacesContext context, UIViewRoot viewRoot, List<? extends Annotation> annotations) {
   if (annotations == null || annotations.isEmpty()) {
     log.debug("Annotations is null/empty");
     return;
   }
   AuthorizationCheckEvent event = new AuthorizationCheckEvent(annotations);
   authorizationCheckEvent.fire(event);
   if (!event.isPassed()) {
     if (!identity.isLoggedIn()) {
       log.debug("Access denied - not logged in");
       redirectToLoginPage(context, viewRoot);
       return;
     } else {
       log.debug("Access denied - not authorized");
       redirectToAccessDeniedView(context, viewRoot);
       return;
     }
   } else {
     log.debug("Access granted");
   }
 }
Exemplo n.º 22
0
  /**
   * Authenticate jpa.
   *
   * @throws ClientException the client exception
   */
  protected void authenticateJPA() throws ClientException {
    User user = userDAO.getUserByLogin(credentials.getUsername());
    boolean hasNoError = true;

    hasNoError = authorizeUser(user);

    String password = null;
    if (hasNoError) {
      if (credentials != null && credentials.getCredential() instanceof PasswordCredential) {
        password = ((PasswordCredential) credentials.getCredential()).getValue();
      }
      if (password == null) {
        messages.error(new YoutestitMSG("error.login.password.require"));
        hasNoError = false;
      }
    }

    if (hasNoError) {
      final String cryptedPassword = Sha1Encryption.getInstance().encryptToSha1(password);

      if (user.getPassword().equals(cryptedPassword)) {
        loginEventSrc.fire(user);
        setUser(new SimpleUser(user.getLogin()));
        identity.getUser();
      } else {
        messages.error(new YoutestitMSG("error.login.password.wrong"));
        hasNoError = false;
      }
    }

    if (hasNoError) {
      setStatus(AuthenticationStatus.SUCCESS);
    } else {
      setStatus(AuthenticationStatus.FAILURE);
    }
  }
Exemplo n.º 23
0
  private void processDigestAuth(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    Context ctx = new SessionContext(new ServletRequestSessionMap(request));
    Identity identity = (Identity) ctx.get(Identity.class);

    if (identity == null) {
      throw new ServletException(
          "Identity not found - please ensure that the Identity component is created on startup.");
    }

    Credentials credentials = (Credentials) ctx.get(Credentials.class);

    boolean requireAuth = false;
    boolean nonceExpired = false;

    String header = request.getHeader("Authorization");
    if (header != null && header.startsWith("Digest ")) {
      String section212response = header.substring(7);

      String[] headerEntries = section212response.split(",");
      Map<String, String> headerMap = new HashMap<String, String>();
      for (String entry : headerEntries) {
        String[] vals = split(entry, "=");
        headerMap.put(vals[0].trim(), vals[1].replace("\"", "").trim());
      }

      DigestRequest digestRequest = new DigestRequest();
      digestRequest.setHttpMethod(request.getMethod());
      digestRequest.setSystemRealm(realm);
      digestRequest.setRealm(headerMap.get("realm"));
      digestRequest.setKey(key);
      digestRequest.setNonce(headerMap.get("nonce"));
      digestRequest.setUri(headerMap.get("uri"));
      digestRequest.setClientDigest(headerMap.get("response"));
      digestRequest.setQop(headerMap.get("qop"));
      digestRequest.setNonceCount(headerMap.get("nc"));
      digestRequest.setClientNonce(headerMap.get("cnonce"));

      try {
        digestRequest.validate();
        request.getSession().setAttribute(DigestRequest.DIGEST_REQUEST, digestRequest);
        authenticate(request, headerMap.get("username"));
      } catch (DigestValidationException ex) {
        log.warn(
            String.format(
                "Digest validation failed, header [%s]: %s", section212response, ex.getMessage()));
        requireAuth = true;

        if (ex.isNonceExpired()) nonceExpired = true;
      } catch (Exception ex) {
        log.warn("Error authenticating: " + ex.getMessage());
        requireAuth = true;
      }
    }

    if (!identity.isLoggedIn() && !credentials.isSet()) {
      requireAuth = true;
    }

    try {
      if (!requireAuth) {
        chain.doFilter(request, response);
        return;
      }
    } catch (NotLoggedInException ex) {
      requireAuth = true;
    }

    if ((requireAuth && !identity.isLoggedIn())) {
      long expiryTime = System.currentTimeMillis() + (nonceValiditySeconds * 1000);

      String signatureValue = DigestUtils.md5Hex(expiryTime + ":" + key);
      String nonceValue = expiryTime + ":" + signatureValue;
      String nonceValueBase64 = Base64.encodeBytes(nonceValue.getBytes());

      // qop is quality of protection, as defined by RFC 2617.
      // we do not use opaque due to IE violation of RFC 2617 in not
      // representing opaque on subsequent requests in same session.
      String authenticateHeader =
          "Digest realm=\"" + realm + "\", " + "qop=\"auth\", nonce=\"" + nonceValueBase64 + "\"";

      if (nonceExpired) authenticateHeader = authenticateHeader + ", stale=\"true\"";

      response.addHeader("WWW-Authenticate", authenticateHeader);
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
  }
Exemplo n.º 24
0
  /**
   * Role-based Authorization check: This method can be accessed if user has following permissions:
   * 1. The user has a Analyst role and this role has permission to access the category which the
   * asset belongs to. Or. 2. The user has a package.developer role or higher (i.e., package.admin)
   * and this role has permission to access the package which the asset belongs to.
   */
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public void changeState(String uuid, String newState) {
    AssetItem asset = getRulesRepository().loadAssetByUUID(uuid);

    // Verify if the user has permission to access the asset through
    // package based permission.
    // If failed, then verify if the user has permission to access the
    // asset through category
    // based permission
    if (Contexts.isSessionContextActive()) {
      boolean passed = false;

      try {
        Identity.instance()
            .checkPermission(
                new PackageUUIDType(asset.getPackage().getUUID()), RoleTypes.PACKAGE_DEVELOPER);
      } catch (RuntimeException e) {
        if (asset.getCategories().size() == 0) {
          Identity.instance().checkPermission(new CategoryPathType(null), RoleTypes.ANALYST);
        } else {
          RuntimeException exception = null;

          for (CategoryItem cat : asset.getCategories()) {
            try {
              Identity.instance()
                  .checkPermission(new CategoryPathType(cat.getName()), RoleTypes.ANALYST);
              passed = true;
            } catch (RuntimeException re) {
              exception = re;
            }
          }
          if (!passed) {
            throw exception;
          }
        }
      }
    }

    log.info(
        "USER:"******" CHANGING ASSET STATUS. Asset name, uuid: "
            + "["
            + asset.getName()
            + ", "
            + asset.getUUID()
            + "]"
            + " to ["
            + newState
            + "]");
    String oldState = asset.getStateDescription();
    asset.updateState(newState);

    push("statusChange", oldState);
    push("statusChange", newState);

    addToDiscussionForAsset(asset.getUUID(), oldState + " -> " + newState);

    getRulesRepository().save();
  }
Exemplo n.º 25
0
  @TransactionAttribute
  public String agregarPedido() {
    Date now = Calendar.getInstance().getTime();
    System.out.println("INGRESo a Guardar _________");
    String salida = null;
    boolean ning = false;
    for (ExamenLabClinico ex : listaExamenLab) {
      if (ex.isSelect()) {
        ning = true;
        break;
      }
    }
    try {
      if (!ning) {
        // save(getInstance());
        FacesMessage msg =
            new FacesMessage(FacesMessage.SEVERITY_WARN, "Debe seleccionar minimo un examen", null);
        FacesContext.getCurrentInstance().addMessage("", msg);
        // return null;
      } else {
        // this.listaPedidoExamenLabC = pickListExamenesLab.getTarget();
        pedido.setFichaOdontologica(fichaOdontolog);
        pedido.setPaciente(fichaOdontolog.getFichaMedica().getPaciente());
        pedido.setEstado("Nuevo");
        pedido.setResponsableEmision(profileS.getProfileByIdentityKey(identity.getUser().getKey()));
        pedido.setFechaPedido(now);
        create(pedido);
        save(pedido);
        update();
        // System.out.println("Guardo Con exito 0_________");
        ResultadoExamenLabClinico resultadoExa;
        List<Parametros> pl = null; //
        for (ExamenLabClinico ex : this.listaExamenLab) {
          if (ex.isSelect()) {
            resultadoExa = new ResultadoExamenLabClinico();
            resultadoExa.setExamenLab(ex);
            resultadoExa.setPedidoExamenLab(pedido);
            pl = examenLabService.getParametrosPorExamen(ex);
            resultadoExa.agregarValoresResultados(pl);
            save(resultadoExa);
            // update();
          }
        }

        FacesMessage msg =
            new FacesMessage(
                "Se agrego nuevo Pedido de Examenes: " + getInstance().getId() + " con éxito");
        FacesContext.getCurrentInstance().addMessage("", msg);
        pedido = new PedidoExamenLaboratorio();
        // hc = hcs.buscarPorFichaMedica(fms.getFichaMedicaPorId(fichaMedicaId));

        RequestContext.getCurrentInstance().update(":form:tabOpc:tablaPedidos :form:growl");
        RequestContext.getCurrentInstance().execute("pedidoDlg.hide();");
        salida =
            "/pages/depSalud/odontologia/consultaOdontologica.xhtml?faces-redirect=true"
                + "&fichaMedicaId="
                + getFichaMedicaId()
                + "&consultaOdontId="
                + getInstance().getId()
                + "&backView="
                + getBackView();
      }
    } catch (Exception e) {
      e.printStackTrace();
      FacesMessage msg = new FacesMessage("Error al guardar: " + getInstance().getId());
      FacesContext.getCurrentInstance().addMessage("", msg);
    }

    return salida;
  }
Exemplo n.º 26
0
 private void authenticate(HttpServletRequest request, final String username)
     throws ServletException, IOException, LoginException {
   Identity identity = Identity.instance();
   identity.getCredentials().setUsername(username);
   identity.authenticate();
 }
  @Test
  public void testLoginComponent() throws Exception {
    Identity identity = Identity.instance();

    assertFalse(identity.isLoggedIn());
    identity.setUsername("gavin");
    identity.setPassword("foobar");
    identity.login();

    User user = (User) Component.getInstance("user");
    assertEquals("Gavin King", user.getName());
    assertEquals("gavin", user.getUsername());
    assertEquals("foobar", user.getPassword());
    assertTrue(identity.isLoggedIn());
    identity.logout();
    assertFalse(identity.isLoggedIn());
    identity.setUsername("gavin");
    identity.setPassword("tiger");
    identity.login();
    assertFalse(identity.isLoggedIn());
  }
Exemplo n.º 28
0
 @BeforeClass
 void beforeClass() {
   Identity.setSecurityEnabled(false);
 }
Exemplo n.º 29
0
  private void doWork(HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (!Identity.instance().isLoggedIn()) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
      return;
    }

    Enumeration<?> e = request.getParameterNames();
    while (e.hasMoreElements()) {
      log.info("parameter: #0", e.nextElement());
    }

    EntityManager em = (EntityManager) Component.getInstance("entityManager");

    if (em != null) {
      Long tfId = saveParseLong(request.getParameter(PARAM_TFID));
      log.info("trying to serve up serialized version of trialform with id #0", tfId);
      try {
        if (tfId != null) {

          Transaction.instance().begin();
          TrialForm tf = em.find(TrialForm.class, tfId);

          if (tf == null) {
            log.warn("requested trialform was not found (id: #0)", tfId);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            Transaction.instance().commit();
            return;
          }

          Identity.instance().checkPermission(tf.getTrial(), SpicsPermissions.EXPORT_TRIAL_FORMS);

          String filename =
              ((tf.getName() == null || "".equals(tf.getName()))
                  ? "formular"
                  : tf.getName() + ".zip");

          response.setContentType("application/zip");
          response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
          /*
           * the following three header elements are needed in order
           * for the downloads to work properly under IE (at least
           * version 7)
           */
          response.addHeader("Pragma", "public");
          response.addDateHeader("Expires", 0);
          response.addHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");

          response.setStatus(HttpServletResponse.SC_OK);

          ServletOutputStream os = response.getOutputStream();
          IXMLImportExport xmlExport = new XMLImportExport();
          xmlExport.writeTrialFormToZip(tf, os);

          Transaction.instance().commit();
          os.flush();

        } else {
          // insufficient parameters specified
          log.warn("insufficient parameters specified!");
          response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
      } catch (AuthorizationException e2) {
        log.warn("AuthorizationException #0", e2.getMessage());
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
      } catch (Exception e1) {
        e1.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
    } else {
      log.error("injected entitymanager was null, could not proceed");
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }