public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String name = request.getParameter("name");
    String date = request.getParameter("date");
    String price = request.getParameter("price");
    String l_id = request.getParameter("l_id");
    String description = request.getParameter("description");

    OracleJDBC.connectToDB();
    boolean b = OracleJDBC.createEvent(name, date, l_id, description, price);
    OracleJDBC.closeDB();

    PrintWriter out = response.getWriter();

    String results = "";
    StringTemplateGroup templates = new StringTemplateGroup("mygroup", "templates");
    StringTemplate st = templates.getInstanceOf("CreateEventResponse");

    if (b) {
      st.setAttribute(
          "results",
          "<img src=\"https://www.cs.usfca.edu/~blu2/images/Yes_check.png\" style=\"width:200px;height:200px;\"></img>");
    } else {
      st.setAttribute(
          "results",
          "<img src=\"https://www.cs.usfca.edu/~blu2/images/Red_cross_tick.png\" style=\"width:200px;height:200px;\"></img>");
    }

    out.println(st.toString());
  }
  @InitSecurityDatabase
  public Right[] findRightsForGroup(final String[] pids, final String action, final Role group) {
    for (int i = 0; i < pids.length; i++) {
      if (!pids[i].startsWith("uuid:")) {
        pids[i] = "uuid:" + pids[i];
      }
    }
    StringTemplate template = SecurityDatabaseUtils.stGroup().getInstanceOf("findRightsForGroup");
    template.setAttribute("pids", pids);
    template.setAttribute("groups", new int[] {group.getId()});
    template.setAttribute("action", action);

    String sql = template.toString();

    List<Right> rights =
        new JDBCQueryTemplate<Right>(this.provider.get()) {
          @Override
          public boolean handleRow(ResultSet rs, List<Right> returnsList) throws SQLException {
            int userId = rs.getInt("user_id");
            int groupId = rs.getInt("group_id");
            AbstractUser dbUser = null;
            if (userId > 0) {
              dbUser = userManager.findUser(userId);
            } else {
              dbUser = userManager.findRole(groupId);
            }
            returnsList.add(RightsDBUtils.createRight(rs, dbUser, criteriumWrapperFactory));
            return true;
          }
        }.executeQuery(sql);
    return ((rights != null) && (!rights.isEmpty()))
        ? (Right[]) rights.toArray(new Right[rights.size()])
        : new Right[0];
  }
 @Override
 public void doCommand() {
   try {
     User user = this.userProvider.get();
     String prefix = this.requestProvider.get().getParameter("prefix");
     if (prefix == null) prefix = "";
     int[] grps = getUserGroups(user);
     Role[] groups = null;
     if (hasCurrentUserHasSuperAdminRole(user)) {
       groups = userManager.findAllRoles(prefix);
     } else {
       groups = userManager.findAllRoles(grps, prefix);
     }
     StringTemplate template = ServletUsersCommand.stFormsGroup().getInstanceOf("allGroupsTable");
     template.setAttribute("groups", groups);
     template.setAttribute(
         "bundle", this.resourceBundleService.getResourceBundle("labels", localesProvider.get()));
     String content = template.toString();
     responseProvider.get().getOutputStream().write(content.getBytes("UTF-8"));
   } catch (UnsupportedEncodingException e) {
     LOGGER.log(Level.SEVERE, e.getMessage(), e);
   } catch (IOException e) {
     LOGGER.log(Level.SEVERE, e.getMessage(), e);
   }
 }
示例#4
0
 @Override
 public String avalia() {
   final StringTemplate stringTemplate = new StringTemplate(TemplatePDDL.And);
   stringTemplate.setAttribute("atributo1", atributo1.avalia());
   stringTemplate.setAttribute("atributo2", atributo2.avalia());
   return stringTemplate.toString();
 }
 public void deleteRightCriteriumImpl(Connection con, int id) throws SQLException {
   StringTemplate template = SecurityDatabaseUtils.stGroup().getInstanceOf("deleteRightCriterium");
   JDBCUpdateTemplate jdbcTemplate = new JDBCUpdateTemplate(con, false);
   String sql = template.toString();
   LOGGER.fine(sql);
   jdbcTemplate.executeUpdate(sql, id);
 }
  @Override
  @InitSecurityDatabase
  public Right[] findAllRights(String[] pids, String action) {
    StringTemplate template =
        SecurityDatabaseUtils.stGroup().getInstanceOf("findAllRightsFromWithGroups");
    template.setAttribute("pids", pids);
    template.setAttribute("action", action);

    String sql = template.toString();

    List<Right> rights =
        new JDBCQueryTemplate<Right>(this.provider.get()) {
          @Override
          public boolean handleRow(ResultSet rs, List<Right> returnsList) throws SQLException {
            int userId = rs.getInt("user_id");
            int groupId = rs.getInt("group_id");
            AbstractUser dbUser = null;
            if (userId > 0) {
              dbUser = userManager.findUser(userId);
            } else {
              dbUser = userManager.findRole(groupId);
            }
            returnsList.add(RightsDBUtils.createRight(rs, dbUser, criteriumWrapperFactory));
            return true;
          }
        }.executeQuery(sql);
    return ((rights != null) && (!rights.isEmpty()))
        ? (Right[]) rights.toArray(new Right[rights.size()])
        : new Right[0];
  }
示例#7
0
  public void setAttribute(String attribute, Object obj1) {
    Set<Entry<String, StringTemplate>> set = m_templates.entrySet();
    Iterator<Entry<String, StringTemplate>> it = set.iterator();

    while (it.hasNext()) {
      Map.Entry<String, StringTemplate> m = (Map.Entry<String, StringTemplate>) it.next();

      // Call setAttribute
      Log.printDebug(
          "setting attribute (obj1) to template group "
              + m.getKey()
              + " to "
              + m.getValue().getName());
      StringTemplate template = m.getValue();
      template.setAttribute(attribute, obj1);
      // Update extensions
      List<StringTemplate> extensions =
          m_extensionstemplates.get(m.getKey() + "_" + template.getName());
      if (extensions != null) {
        for (StringTemplate extension : extensions) {
          extension.setAttribute(attribute, obj1);
        }
      }
    }
  }
  @Override
  @InitSecurityDatabase
  public RightCriteriumParams[] findAllParams() {

    StringTemplate template =
        SecurityDatabaseUtils.stGroup().getInstanceOf("findAllCriteriumParams");

    List<RightCriteriumParams> crits =
        new JDBCQueryTemplate<RightCriteriumParams>(this.provider.get()) {

          @Override
          public boolean handleRow(ResultSet rs, List<RightCriteriumParams> returnsList)
              throws SQLException {

            String shortDesc = rs.getString("short_desc");
            String longDesc = rs.getString("long_desc");
            int critParamId = rs.getInt("crit_param_id");
            String vals = rs.getString("vals");

            RightCriteriumParamsImpl params = new RightCriteriumParamsImpl(critParamId);
            params.setLongDescription(longDesc);
            params.setShortDescription(shortDesc);
            params.setObjects(RightsDBUtils.valsFromString(vals));

            returnsList.add(params);

            return true;
          }
        }.executeQuery(template.toString());

    return (RightCriteriumParams[]) crits.toArray(new RightCriteriumParams[crits.size()]);
  }
 public void updateRightCriteriumImpl(Connection con, RightCriteriumWrapper criteriumWrapper)
     throws SQLException {
   StringTemplate template = SecurityDatabaseUtils.stGroup().getInstanceOf("updateRightCriterium");
   template.setAttribute("criteriumWrapper", criteriumWrapper);
   JDBCUpdateTemplate jdbcTemplate = new JDBCUpdateTemplate(con, false);
   String sql = template.toString();
   LOGGER.fine(sql);
   jdbcTemplate.executeUpdate(sql);
 }
示例#10
0
  protected StringTemplate getNodeST(TreeAdaptor adaptor, Object t) {
    String text = adaptor.getText(t);
    StringTemplate nodeST = _nodeST.getInstanceOf();
    String uniqueName = "n" + getNodeNumber(t);
    nodeST.setAttribute("name", uniqueName);

    nodeST.setAttribute("text", fixString(text));
    return nodeST;
  }
示例#11
0
 /**
  * Generate a Java file from the standard DTL template class generator <code>
  * The DTLContext must have the following keys
  * 	name 							String
  * 	className 						String
  *  superClassName (Optional)		String
  *  chunks (Optional)				List<Map<String,String>>
  *  	Map has keys :
  *  	name						String
  *  	value						String
  *  variables (Optional)			List<String>
  *  blocks	(Optional)				List<Map<String,Object>>
  *  	Map has keys:
  *  	name						String
  *  	statements					List<Map<String, Object>>
  *  		Map has keys :
  *  		type					String (chunkstatement, forstatement,
  *  									blockstatement, variablestatement)
  *  		collection				String (for forstatement)
  *  		id						String (for forstatement)
  *  		id						String (for variablestatement)
  *  		id						String (for chunkstatement)
  *  		id						String (for blockstatement)
  *  mainstatements					List<Map<String, Object>>
  *  	Map has keys the same as statements attribute of blocks above .
  *
  *  </code>
  *
  * @param w
  * @param dtlContext
  * @throws IOException
  */
 public void generate(Writer w, Map<String, Object> dtlContext) throws IOException {
   InputStream is = TemplateClassGenerator.class.getResourceAsStream("rstljavatemplate.stg");
   BufferedReader r = new BufferedReader(new InputStreamReader(is));
   // Reader r = new FileReader(stgTemplateUrl.getFile());
   StringTemplateGroup group = new StringTemplateGroup(r);
   StringTemplate t = group.getInstanceOf("javaclass");
   t.setAttribute("ctxt", dtlContext);
   w.append(t.toString(80));
 }
 @InitSecurityDatabase
 public int insertRightCriteriumImpl(Connection con, RightCriteriumWrapper criterium)
     throws SQLException {
   StringTemplate template = SecurityDatabaseUtils.stGroup().getInstanceOf("insertRightCriterium");
   template.setAttribute("criteriumWrapper", criterium);
   template.setAttribute("type", criterium.getCriteriumType().getVal());
   JDBCUpdateTemplate jdbcTemplate = new JDBCUpdateTemplate(con, false);
   String sql = template.toString();
   LOGGER.fine(sql);
   return jdbcTemplate.executeUpdate(sql);
 }
 @InitSecurityDatabase
 public int insertRightCriteriumParamsImpl(Connection con, RightCriteriumParams criteriumParams)
     throws SQLException {
   StringTemplate template =
       SecurityDatabaseUtils.stGroup().getInstanceOf("insertRightCriteriumParams");
   template.setAttribute("params", criteriumParams);
   JDBCUpdateTemplate jdbcTemplate = new JDBCUpdateTemplate(con, false);
   String sql = template.toString();
   LOGGER.fine(sql);
   return jdbcTemplate.executeUpdate(sql);
 }
 /**
  * Generates version file based on the version number received from the doc calls. This version
  * file is used while making the API calls to make sure Client and back end are compatible.
  *
  * @param version
  */
 private void generateVersionHelper(String version, StringTemplateGroup templateGroup) {
   StringTemplate template = templateGroup.getInstanceOf(VERSION_OBJECT_TEMPLATE);
   template.setAttribute("apiVersion", version);
   template.setAttribute(PACKAGE_NAME, config.getApiPackageName());
   File aFile =
       new File(
           languageConfig.getResourceClassLocation()
               + this.getNameGenerator().getVersionCheckerClassName()
               + languageConfig.getClassFileExtension());
   writeFile(aFile, template.toString(), "Version checker class");
 }
示例#15
0
  public void saveNewPatient(PatientDTO dto, HttpServletRequest request) throws Exception {
    Patient patient = dto.getPatient();

    if (dto.isUpdatePassword()) {
      if (testPassword(patient.getCred().getPassword()) == false) {
        dto.setResult(false);
        dto.setErrorMsg("Insufficient Password");
        dto.setReturnCode(RETURN_CODE_INVALID_PASSWORD);
        return;
      }
      String salt = UUID.randomUUID().toString();
      patient.getCred().setSalt(salt);
      String encodedPassword =
          OneWayPasswordEncoder.getInstance().encode(patient.getCred().getPassword(), salt);
      patient.getCred().setPassword(encodedPassword);
    }

    if (dto.isUpdateEmail()) {
      if (appDAO.checkEmail(DataEncryptor.encrypt(patient.getCred().getEmail())) == false) {
        dto.setResult(false);
        dto.setErrorMsg("Email already in system");
        dto.setReturnCode(RETURN_CODE_DUP_EMAIL);
        return;
      }
    }

    Demographics demo = patient.getDemo();
    demo.setEthnicity(appDAO.findEthnicityById(demo.getEthnicity().getId()));
    demo.setMaritalStatus(appDAO.findMaritalStatusById(demo.getMaritalStatus().getId()));
    if (demo.getUsState() != null) {
      demo.setUsState(appDAO.findUSStateById(demo.getUsState().getId()));
    }
    demo.setRace(appDAO.findRaceById(demo.getRace().getId()));
    appDAO.update(patient);
    decrypt(patient);
    String patientFullName =
        patient.getCred().getFirstName() + " " + patient.getCred().getLastName();
    String title = patientFullName + ", welcome to the Pleasantville Medical Patient Portal";
    String templatePath = context.getRealPath("/WEB-INF/email_templates");
    StringTemplateGroup group =
        new StringTemplateGroup("underwebinf", templatePath, DefaultTemplateLexer.class);
    StringTemplate st = group.getInstanceOf("portal_signup_confirmation");
    String from = Core.mailFrom;
    st.setAttribute("patient", patientFullName);
    st.setAttribute("email", patient.getCred().getEmail());
    st.setAttribute("phone", patient.getDemo().getPrimaryPhone());

    MailHandler handler = new MailHandler();
    boolean isHtml = true;
    String stString = st.toString();
    activityLogService.logViewPatient(patient.getId(), null, patient.getId(), "SaveNewPatient");
    handler.sendMimeMessage(patient.getCred().getEmail(), from, stString, title, isHtml);
  }
 @InitSecurityDatabase
 public int insertRightImpl(Connection con, Right right) throws SQLException {
   StringTemplate template = SecurityDatabaseUtils.stGroup().getInstanceOf("insertRight");
   template.setAttribute("association", right.getUser() instanceof Role ? "group_id" : "user_id");
   template.setAttribute("right", right);
   template.setAttribute(
       "priority", right.getFixedPriority() == 0 ? "NULL" : "" + right.getFixedPriority());
   JDBCUpdateTemplate jdbcTemplate = new JDBCUpdateTemplate(con, false);
   String sql = template.toString();
   LOGGER.fine(sql);
   return jdbcTemplate.executeUpdate(sql);
 }
示例#17
0
 public static String getSQLString(List<String> templateNames, Collection<SQLMapping> collection) {
   StringBuffer result = new StringBuffer();
   for (String templateName : templateNames) {
     StringTemplate t = sql.getInstanceOf(templateName);
     if (collection != null) {
       for (SQLMapping m : collection) {
         if (t.getFormalArgument(m.getName()) != null) {
           t.setAttribute(m.getName(), m.getValues());
         }
       }
     }
     result.append(t.toString());
   }
   return result.toString();
 }
示例#18
0
  @Override
  public void writeTo(
      AggregatorRegistry registry,
      Class<?> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream entityStream)
      throws IOException, WebApplicationException {
    PrintWriter pw = new PrintWriter(entityStream);

    StringTemplate st = StringTemplates.getTemplate("htmlOpen");
    st.setAttribute("header", "Event Aggregator Endpoint");
    st.setAttribute("msg", "click on a link to view Aggregator details");
    pw.println(st.toString());

    pw.println("Other Aggregators :");

    for (ServiceDescriptor sd : chooser.getAllServiceDescriptors()) {
      String host = sd.getProperties().get("host");
      String port = sd.getProperties().get("jetty.port");
      pw.printf(
          "[<a href=\"http://%s:%s/xn/rest/1.0/event/aggregator\"> %s:%s </a>]  ",
          host, port, host, port);
    }

    pw.println("<br><br>");

    pw.println(StringTemplates.getTemplate("aggJS"));
    pw.println(StringTemplates.getTemplate("formOpen"));

    pw.println(StringTemplates.getTemplate("tableOpen"));

    for (String name : registry.getAggregatorNames()) {
      pw.printf(
          "<tr> <td> <a href=\"/xn/rest/1.0/event/aggregator/%s\"> %s </a> </td>\n", name, name);
      pw.printf(
          "<td> %s </td> <tr>\n",
          StringTemplates.getTemplate("deleteButton", "label", "destroy", "name", name));
    }

    pw.println(StringTemplates.getTemplate("tableClose"));

    pw.println(StringTemplates.getTemplate("formClose"));

    pw.println(StringTemplates.getTemplate("htmlClose").toString());
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    PrintWriter out = response.getWriter();

    HashMap<String, String> hm = SearchingFilters.defaultLocation(25);
    StringBuffer results = new StringBuffer();

    for (String s : hm.keySet()) {
      results.append("<option value=\"" + hm.get(s) + "\">" + s + "</option>");
    }

    StringTemplateGroup templates = new StringTemplateGroup("mygroup", "templates");
    StringTemplate st = templates.getInstanceOf("CreateEvent");
    st.setAttribute("results", results);
    out.println(st.toString());
  }
示例#20
0
  protected void toDOTDefineEdges(Object tree, TreeAdaptor adaptor, StringTemplate treeST) {
    if (tree == null) {
      return;
    }
    int n = adaptor.getChildCount(tree);
    if (n == 0) {
      // must have already dumped as child from previous
      // invocation; do nothing
      return;
    }

    String parentName = "n" + getNodeNumber(tree);

    // for each child, do a parent -> child edge using unique node names
    String parentText = adaptor.getText(tree);
    for (int i = 0; i < n; i++) {
      Object child = adaptor.getChild(tree, i);
      String childText = adaptor.getText(child);
      String childName = "n" + getNodeNumber(child);
      StringTemplate edgeST = _edgeST.getInstanceOf();
      edgeST.setAttribute("parent", parentName);
      edgeST.setAttribute("child", childName);
      edgeST.setAttribute("parentText", fixString(parentText));
      edgeST.setAttribute("childText", fixString(childText));
      treeST.setAttribute("edges", edgeST);
      toDOTDefineEdges(child, adaptor, treeST);
    }
  }
示例#21
0
  public StringTemplate getTemplate(String groupname) {
    StringTemplate template = m_templates.get(groupname);

    // If there is extensiones, add them before return the template.
    if (m_extensionstemplates.containsKey(groupname + "_" + template.getName())) {
      List<StringTemplate> extemplates = new ArrayList<StringTemplate>();
      List<StringTemplate> extensions =
          m_extensionstemplates.get(groupname + "_" + template.getName());

      for (StringTemplate extension : extensions) {
        extemplates.add(extension);
      }

      template.setAttribute("extensions", extemplates);
    }

    return template;
  }
  @Override
  public RightCriteriumWrapper findRightCriteriumById(int critId) {
    StringTemplate template = SecurityDatabaseUtils.stGroup().getInstanceOf("findCriteriumById");
    List<RightCriteriumWrapper> crits =
        new JDBCQueryTemplate<RightCriteriumWrapper>(this.provider.get()) {

          @Override
          public boolean handleRow(ResultSet rs, List<RightCriteriumWrapper> returnsList)
              throws SQLException {
            RightCriteriumWrapper wrapper =
                RightsDBUtils.createCriteriumWrapper(criteriumWrapperFactory, rs);
            returnsList.add(wrapper);
            return true;
          }
        }.executeQuery(template.toString(), critId);

    return !crits.isEmpty() ? crits.get(0) : null;
  }
  /**
   * Generates assembler classes if the API returns more than one object.
   *
   * @param resources
   * @param templateGroup
   */
  private void generateModelClassesForInput(
      List<Resource> resources, StringTemplateGroup templateGroup) {
    List<String> generatedClasses = new ArrayList<String>();
    for (Resource resource : resources) {
      if (resource.getEndPoints() != null) {
        for (Endpoint endpoint : resource.getEndPoints()) {
          if (endpoint.getOperations() != null) {
            for (EndpointOperation operation : endpoint.getOperations()) {
              ResourceMethod method =
                  operation.generateMethod(
                      endpoint, resource, dataTypeMappingProvider, nameGenerator);
              if (method.getInputModel() != null) {
                Model model = method.getInputModel();
                if (model != null) {
                  if (!generatedClasses.contains(model.getName())) {
                    List<String> imports = new ArrayList<String>();
                    imports.addAll(this.config.getDefaultModelImports());
                    for (ModelField param : model.getFields()) {
                      param.setName(reservedWordMapper.translate(param.getName()));
                      for (String importDef :
                          param
                              .getFieldDefinition(
                                  this.getDataTypeMappingProvider(), config, nameGenerator)
                              .getImportDefinitions()) {
                        if (!imports.contains(importDef)) {
                          imports.add(importDef);
                        }
                      }
                    }
                    StringTemplate template = templateGroup.getInstanceOf(MODEL_OBJECT_TEMPLATE);

                    template.setAttribute("fields", model.getFields());
                    template.setAttribute("imports", imports);
                    template.setAttribute("extends", config.getDefaultModelBaseClass());
                    template.setAttribute(
                        "annotationPackageName", languageConfig.getAnnotationPackageName());
                    template.setAttribute("className", model.getGenratedClassName());
                    template.setAttribute(PACKAGE_NAME, config.getModelPackageName());
                    File aFile =
                        new File(
                            languageConfig.getModelClassLocation()
                                + model.getGenratedClassName()
                                + languageConfig.getClassFileExtension());
                    writeFile(aFile, template.toString(), "Input model class");
                    generatedClasses.add(model.getName());
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  /**
   * Generates one API class for each resource and each end point in the resource is translated as
   * method.
   *
   * @param resources
   * @param templateGroup
   */
  private void generateAPIClasses(List<Resource> resources, StringTemplateGroup templateGroup) {

    for (Resource resource : resources) {
      try {
        List<ResourceMethod> methods = new ArrayList<ResourceMethod>();
        List<String> imports = new ArrayList<String>();
        imports.addAll(this.config.getDefaultServiceImports());
        methods =
            resource.generateMethods(
                resource, dataTypeMappingProvider, nameGenerator, languageConfig);
        StringTemplate template = templateGroup.getInstanceOf(API_OBJECT_TEMPLATE);
        String className = resource.generateClassName(nameGenerator);

        if (className != null) {
          List<ResourceMethod> filteredMethods = new ArrayList<ResourceMethod>();
          for (ResourceMethod method : methods) {
            if (!this.getCodeGenRulesProvider().isMethodIgnored(className, method.getName())) {
              filteredMethods.add(method);
            }
          }
          template.setAttribute("imports", imports);
          template.setAttribute(PACKAGE_NAME, config.getApiPackageName());
          template.setAttribute("annotationPackageName", languageConfig.getAnnotationPackageName());
          template.setAttribute("modelPackageName", config.getModelPackageName());
          template.setAttribute("exceptionPackageName", languageConfig.getExceptionPackageName());
          template.setAttribute("resource", className);
          template.setAttribute("methods", filteredMethods);
          template.setAttribute("extends", config.getServiceBaseClass(className));

          File aFile =
              new File(
                  languageConfig.getResourceClassLocation()
                      + resource.generateClassName(nameGenerator)
                      + languageConfig.getClassFileExtension());
          writeFile(aFile, template.toString(), "API Classes");
        }
      } catch (RuntimeException t) {
        System.out.println(
            "Failed generating api class for the resource : " + resource.getResourcePath());
        throw t;
      }
    }
  }
  @Override
  @InitSecurityDatabase
  public RightCriteriumParams findParamById(int paramId) {
    StringTemplate template =
        SecurityDatabaseUtils.stGroup().getInstanceOf("findCriteriumParamsById");
    List<RightCriteriumParams> crits =
        new JDBCQueryTemplate<RightCriteriumParams>(this.provider.get()) {

          @Override
          public boolean handleRow(ResultSet rs, List<RightCriteriumParams> returnsList)
              throws SQLException {
            RightCriteriumParams params = RightsDBUtils.createCriteriumParams(rs);
            returnsList.add(params);
            return true;
          }
        }.executeQuery(template.toString(), paramId);

    return !crits.isEmpty() ? crits.get(0) : null;
  }
  @Override
  public Right[] findRights(
      final String[] ids, final String[] pids, final String[] actions, final String[] rnames) {
    Map<String, List<String>> map = new HashMap<String, List<String>>();
    if (ids.length > 0) {
      map.put("id", Arrays.asList(ids));
    }
    if (pids.length > 0) {
      map.put("uuid", Arrays.asList(pids));
    }
    if (actions.length > 0) {
      map.put("action", Arrays.asList(actions));
    }
    if (rnames.length > 0) {
      map.put("gname", Arrays.asList(rnames));
    }

    StringTemplate template = SecurityDatabaseUtils.stGroup().getInstanceOf("findAllRights");
    template.setAttribute("params", map);

    String sql = template.toString();
    List<Right> rights =
        new JDBCQueryTemplate<Right>(this.provider.get()) {
          @Override
          public boolean handleRow(ResultSet rs, List<Right> returnsList) throws SQLException {
            int userId = rs.getInt("user_id");
            int groupId = rs.getInt("group_id");
            AbstractUser dbUser = null;
            if (userId > 0) {
              dbUser = userManager.findUser(userId);
            } else {
              dbUser = userManager.findRole(groupId);
            }
            returnsList.add(RightsDBUtils.createRight(rs, dbUser, criteriumWrapperFactory));
            return true;
          }
        }.executeQuery(sql);

    return ((rights != null) && (!rights.isEmpty()))
        ? (Right[]) rights.toArray(new Right[rights.size()])
        : new Right[0];
  }
 public String generateSummaryMail(
     List<BlogPost> posts,
     List<Blog> blogsAddedSinceLastNewsletter,
     int numberOfDaysBackInThePast) {
   try {
     BufferedReader bufferedReader =
         new BufferedReader(new InputStreamReader(blogsSummaryTemplate.getInputStream(), "UTF-8"));
     String templateContent =
         Joiner.on("\n").join(bufferedReader.lines().collect(Collectors.toList()));
     StringTemplate template = new StringTemplate(templateContent);
     template.setAttribute("days", numberOfDaysBackInThePast);
     template.setAttribute(
         "newPosts", posts.stream().map(BlogPostForMailItem::new).collect(Collectors.toList()));
     template.setAttribute(
         "personToBlogHomepage", getPersonToBlogHomepage(blogsAddedSinceLastNewsletter));
     return template.toString();
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
  @Override
  public int[] findUsedRoleIDs() {
    StringTemplate template = SecurityDatabaseUtils.stGroup().getInstanceOf("findUsedRoles");
    List<Integer> ids =
        new JDBCQueryTemplate<Integer>(this.provider.get()) {
          @Override
          public boolean handleRow(ResultSet rs, List<Integer> returnsList) throws SQLException {
            int val = rs.getInt("group_id");
            if (val > 0) {
              returnsList.add(val);
            }
            return true;
          }
        }.executeQuery(template.toString());

    int[] retArray = new int[ids.size()];
    for (int i = 0; i < retArray.length; i++) {
      retArray[i] = ids.get(i);
    }
    return retArray;
  }
 @Override
 public Right findRightById(int id) {
   StringTemplate template = SecurityDatabaseUtils.stGroup().getInstanceOf("findRightById");
   String sql = template.toString();
   List<Right> rights =
       new JDBCQueryTemplate<Right>(this.provider.get()) {
         @Override
         public boolean handleRow(ResultSet rs, List<Right> returnsList) throws SQLException {
           int userId = rs.getInt("user_id");
           int groupId = rs.getInt("group_id");
           AbstractUser dbUser = null;
           if (userId > 0) {
             dbUser = userManager.findUser(userId);
           } else {
             dbUser = userManager.findRole(groupId);
           }
           returnsList.add(RightsDBUtils.createRight(rs, dbUser, criteriumWrapperFactory));
           return true;
         }
       }.executeQuery(sql, id);
   return ((rights != null) && (!rights.isEmpty())) ? rights.get(0) : null;
 }
  @Override
  public List<Map<String, String>> findObjectUsingParams(int paramId) {

    StringTemplate template =
        SecurityDatabaseUtils.stGroup().getInstanceOf("select_object_using_param");
    List<Map<String, String>> vals =
        new JDBCQueryTemplate<Map<String, String>>(this.provider.get()) {
          @Override
          public boolean handleRow(ResultSet rs, List<Map<String, String>> returnsList)
              throws SQLException {
            String pid = rs.getString("pid");
            String action = rs.getString("action");
            Map<String, String> map = new HashMap<String, String>();
            {
              map.put("pid", pid);
              map.put("action", action);
            }
            returnsList.add(map);
            return true;
          }
        }.executeQuery(template.toString(), new Integer(paramId));
    return vals;
  }