/**
   * This method deletes the TerminationReasons record from database based on TerminationReasons
   * record Id
   *
   * @param resourceRequest
   * @param resourceResponse
   * @throws IOException
   * @throws PortletException
   * @throws SystemException
   * @throws PortalException
   * @throws NumberFormatException
   */
  public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
      throws IOException {
    if (resourceRequest.getResourceID().equals("deleteTerminationReasons")) {
      System.out.println("deleting thes TerminationReasons");

      String[] idsArray = ParamUtil.getParameterValues(resourceRequest, "terminationreasonsIds");
      System.out.println(idsArray.length);

      for (int i = 0; i <= idsArray.length - 1; i++) {

        try {
          try {
            TerminationReasonsLocalServiceUtil.deleteTerminationReasons(
                Long.parseLong(idsArray[i]));
          } catch (PortalException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (SystemException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        } catch (NumberFormatException e) {
        }
      }
    }
  }
 public DLFileEntry getFileEntry(long fileId) {
   try {
     return fileService.getDLFileEntry(fileId);
   } catch (PortalException ex) {
     ex.printStackTrace();
     return null;
   } catch (SystemException ex) {
     ex.printStackTrace();
     return null;
   }
 }
 public DLFileEntry getFileEntry(String processUUID, String title) {
   try {
     return fileService.getFileEntryByTitle(
         processBaseGroup.getGroupId(), getFolder(processUUID).getFolderId(), title);
   } catch (PortalException ex) {
     ex.printStackTrace();
     return null;
   } catch (SystemException ex) {
     ex.printStackTrace();
     return null;
   }
 }
Esempio n. 4
0
 @Override
 protected University returnedModelObject(String value) {
   try {
     return UniversityLocalServiceUtil.getUniversity(Long.valueOf(value));
   } catch (NumberFormatException e) {
     e.printStackTrace();
   } catch (PortalException e) {
     e.printStackTrace();
   } catch (SystemException e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 5
0
 /**
  * Entfernt einen Favoriten aus der DB
  *
  * @param event
  */
 public void deleteFavorite(ActionEvent event) {
   try {
     FavoriteLocalServiceUtil.deleteFavorite(Long.valueOf(currentFav));
   } catch (NumberFormatException e) {
     System.out.println("Beim lšschen eines Favoriten " + "ist ein Fehler aufgetreten!");
     e.printStackTrace();
   } catch (PortalException e) {
     System.out.println("Beim lšschen eines Favoriten " + "ist ein Fehler aufgetreten!");
     e.printStackTrace();
   } catch (SystemException e) {
     System.out.println("Beim lšschen eines Favoriten " + "ist ein Fehler aufgetreten!");
     e.printStackTrace();
   }
   moveToFavoriteSelection(event);
 }
Esempio n. 6
0
 /**
  * Verfolgt Aenderungen in der Favoriten-Auswahl Fuer die aktuelle Auswahl wird eine Vorschau
  * angezeigt
  *
  * @param vcEvent
  */
 public void favoritePreviewListener(ValueChangeEvent vcEvent) {
   try {
     slideBackingBean.showPreview(
         SlideLocalServiceUtil.getSlide(
                 FavoriteLocalServiceUtil.getFavorite(
                         Long.valueOf(vcEvent.getNewValue().toString()))
                     .getSlideId())
             .getIndex());
   } catch (NumberFormatException e) {
     e.printStackTrace();
   } catch (PortalException e) {
     e.printStackTrace();
   } catch (SystemException e) {
     e.printStackTrace();
   }
 }
Esempio n. 7
0
 /**
  * Zeigt den aktuellen Favoriten als Folie im slideViewer an
  *
  * @param event
  */
 public void moveToFavorite(ActionEvent event) {
   navigationBackingBean.setFavoriteSelectionStatus(false);
   navigationBackingBean.setSlideViewerStatus(true);
   try {
     slideBackingBean.showSlide(
         "" + FavoriteLocalServiceUtil.getFavorite(Long.valueOf(currentFav)).getSlideId());
   } catch (NumberFormatException e) {
     System.out.println("Beim navigieren zu einem Favoriten " + "ist ein Fehler aufgetreten!");
     e.printStackTrace();
   } catch (PortalException e) {
     System.out.println("Beim navigieren zu einem Favoriten " + "ist ein Fehler aufgetreten!");
     e.printStackTrace();
   } catch (SystemException e) {
     System.out.println("Beim navigieren zu einem Favoriten " + "ist ein Fehler aufgetreten!");
     e.printStackTrace();
   }
 }
Esempio n. 8
0
 /**
  * Laedt ein einzelnes Modul aus der Datenbank und belegt die ModuleModelBean
  *
  * @param moduleId
  */
 public void fetchModule(long moduleId) {
   try {
     Module module = ModuleLocalServiceUtil.getModule(moduleId);
     moduleModelBean.setLecturerUserId(module.getLecturerUserId());
     moduleModelBean.setModuleTitle(module.getModuleTitle());
     moduleModelBean.setDate(module.getCreateDate());
     moduleModelBean.setAdditionalInfo(module.getAdditionalInfo());
   } catch (NumberFormatException e) {
     System.out.println("Beim fetchen eines Moduls " + "ist ein Fehler aufgetreten!");
     e.printStackTrace();
   } catch (PortalException e) {
     System.out.println("Beim fetchen eines Moduls " + "ist ein Fehler aufgetreten!");
     e.printStackTrace();
   } catch (SystemException e) {
     System.out.println("Beim fetchen eines Moduls " + "ist ein Fehler aufgetreten!");
     e.printStackTrace();
   }
 }
  /**
   * This method updates the TerminationReason record based on TerminationReason recordId
   *
   * @param actionRequest
   * @param actionResponse
   * @throws IOException
   * @throws PortletException
   * @throws SystemException
   */
  public void updateTerminationReasons(ActionRequest actionRequest, ActionResponse actionResponse)
      throws IOException, PortletException, SystemException {
    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    String id = ParamUtil.getString(actionRequest, "terminationreasonsId");
    String name = ParamUtil.getString(actionRequest, "terminationreasonsName");
    System.out.println("id == " + id);
    TerminationReasons terminationReasons;

    try {
      String terminationReason = name.trim();
      if (terminationReason.equals("") || terminationReason == null) {

        System.out.println("Empty value in TerminationReason...");
        TerminationReasons terminationReasons2 =
            TerminationReasonsLocalServiceUtil.getTerminationReasons(Long.parseLong(id));

        actionRequest.setAttribute("editTerminationReasons", terminationReasons2);

        SessionMessages.add(actionRequest.getPortletSession(), "termination-form-error");
        actionResponse.setRenderParameter("mvcPath", "/html/terminationreasons/edit.jsp");
      } else {

        terminationReasons =
            TerminationReasonsLocalServiceUtil.getTerminationReasons(Long.parseLong(id));
        terminationReasons.setCreateDate(date);
        terminationReasons.setModifiedDate(date);
        terminationReasons.setCompanyId(themeDisplay.getCompanyId());
        terminationReasons.setGroupId(themeDisplay.getCompanyGroupId());
        terminationReasons.setUserId(themeDisplay.getUserId());
        terminationReasons.setTerminationreasonsName(name);
        terminationReasons =
            TerminationReasonsLocalServiceUtil.updateTerminationReasons(terminationReasons);
      }
    } catch (NumberFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (PortalException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Esempio n. 10
0
  /**
   * The search redirection.
   *
   * @return an empty string.
   */
  public String search() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    Object responseObject = facesContext.getExternalContext().getResponse();

    if (responseObject != null && responseObject instanceof ActionResponse) {
      ActionResponse actionResponse = (ActionResponse) responseObject;

      Query query = new Query();
      query.getTags().add(selectedTag);
      actionResponse.setEvent(
          new QName("http://fokus.fraunhofer.de/odplatform", "querydatasets"), query);

      String location = LiferayFacesContext.getInstance().getThemeDisplay().getPortalURL();
      Layout layout = LiferayFacesContext.getInstance().getThemeDisplay().getLayout();

      try {
        if (layout.isPublicLayout()) {
          location +=
              LiferayFacesContext.getInstance().getThemeDisplay().getPathFriendlyURLPublic();
        }

        location +=
            layout.hasScopeGroup()
                ? layout.getScopeGroup().getFriendlyURL()
                : layout.getGroup().getFriendlyURL();
        location += "/suchen";
      } catch (PortalException e) {
        e.printStackTrace();
      } catch (SystemException e) {
        e.printStackTrace();
      }

      try {
        facesContext.getExternalContext().redirect(location);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return "";
  }
 public byte[] getFileBody(String processUUID, long fileId) {
   byte[] result = null;
   try {
     DLFileEntry file = getFileEntry(fileId);
     result = new byte[Long.valueOf(file.getSize()).intValue()];
     InputStream is =
         fileService.getFileAsStream(
             currentUser.getCompanyId(),
             currentUser.getUserId(),
             processBaseGroup.getGroupId(),
             getFolder(processUUID).getFolderId(),
             file.getName());
     is.read(result);
   } catch (PortalException ex) {
     ex.printStackTrace();
   } catch (SystemException ex) {
     ex.printStackTrace();
   } catch (IOException ex) {
     ex.printStackTrace();
   }
   return result;
 }
Esempio n. 12
0
  public void render(RenderRequest renderRequest, RenderResponse renderResponse)
      throws IOException, PortletException {
    if (!_processed) {
      ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
      PortletConfig portletConfig =
          (PortletConfig) renderRequest.getAttribute("javax.portlet.config");
      _portletName = portletConfig.getPortletName();
      PortletURL pURL =
          PortletURLFactoryUtil.create(
              renderRequest,
              _portletName + "_WAR_" + _portletName + "portlet",
              themeDisplay.getPlid(),
              PortletRequest.ACTION_PHASE);
      pURL.setParameter(ActionRequest.ACTION_NAME, ProxyConstant.ACTION_LINK);
      _portletURL = pURL.toString();
      // read portlet config;
      PortletPreferences preferences = renderRequest.getPreferences();
      String portletResource = ParamUtil.getString(renderRequest, "portletResource");

      if (Validator.isNotNull(portletResource)) {
        try {
          preferences =
              PortletPreferencesFactoryUtil.getPortletSetup(renderRequest, portletResource);
        } catch (PortalException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (SystemException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      _proxyURL = preferences.getValue("url", "");
      log.info("proxyurl=" + _proxyURL);

      defaultProxyRequest();
      renderResponse.getWriter().print(_result);
    } else renderResponse.getWriter().print("processed");
  }
Esempio n. 13
0
  private void getPortletInfo(ActionRequest actionRequest) {
    log.info("getPortletInfo");
    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    PortletConfig portletConfig =
        (PortletConfig) actionRequest.getAttribute("javax.portlet.config");
    _portletName = portletConfig.getPortletName();
    PortletURL pURL =
        PortletURLFactoryUtil.create(
            actionRequest,
            _portletName + "_WAR_" + _portletName + "portlet",
            themeDisplay.getPlid(),
            PortletRequest.ACTION_PHASE);
    /*try {
    	pURL.setWindowState(WindowState.NORMAL );
    } catch (WindowStateException e1) {
    	// TODO Auto-generated catch block
    	e1.printStackTrace();
    }*/
    pURL.setParameter(ActionRequest.ACTION_NAME, ProxyConstant.ACTION_LINK);
    _portletURL = pURL.toString();

    // read portlet config;
    PortletPreferences preferences = actionRequest.getPreferences();
    String portletResource = ParamUtil.getString(actionRequest, "portletResource");

    if (Validator.isNotNull(portletResource)) {
      try {
        preferences = PortletPreferencesFactoryUtil.getPortletSetup(actionRequest, portletResource);
      } catch (PortalException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (SystemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    _proxyURL = preferences.getValue("url", "");
  } /*
Esempio n. 14
0
  public void run(String[] arg0) throws ActionException {

    File file = new File("old-users.csv");

    _log.debug("file ==> " + file.getAbsolutePath());

    InputStream inputStream = null;
    try {
      inputStream = new FileInputStream(file);
    } catch (FileNotFoundException e) {
      _log.debug("File not found...Existing....");
      return;
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

    long companyId = PortalUtil.getDefaultCompanyId();
    long creatorUserId = 0l;
    try {
      creatorUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
    } catch (PortalException e) {
      e.printStackTrace();
    } catch (SystemException e) {
      e.printStackTrace();
    }

    try {
      String line = StringPool.BLANK;
      while (Validator.isNotNull(line = br.readLine())) {
        insertOldUser(companyId, creatorUserId, line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    file.delete();
  }
  public void deleteBooks(Books book, long companyId) {

    try {
      resourceLocalService.deleteResource(
          companyId,
          Books.class.getName(),
          ResourceConstants.SCOPE_INDIVIDUAL,
          book.getPrimaryKey());
      assetEntryLocalService.deleteEntry(Books.class.getName(), book.getBookId());

    } catch (PortalException e) {
      e.printStackTrace();
      return;
    } catch (SystemException e) {
      e.printStackTrace();
      return;
    }
    try {
      booksPersistence.remove(book);
    } catch (SystemException e) {
      e.printStackTrace();
      return;
    }
  }
 public DLFolder getFolder(String folderName) {
   DLFolder result = null;
   try {
     result = folderService.getFolder(processBaseGroup.getGroupId(), 0, folderName);
   } catch (Exception nsfex) {
     if (result == null) {
       try {
         result =
             folderService.addFolder(
                 currentUser.getUserId(),
                 processBaseGroup.getGroupId(),
                 0,
                 folderName,
                 folderName,
                 new ServiceContext());
       } catch (PortalException ex) {
         ex.printStackTrace();
       } catch (SystemException ex) {
         ex.printStackTrace();
       }
     }
   }
   return result;
 }
  @Override
  public boolean updateCourse(Course course, long userId) throws SystemException {

    CourseResult courseResult =
        CourseResultLocalServiceUtil.getByUserAndCourse(course.getCourseId(), userId);
    // .fetchByuc(mresult.getUserId(), course.getCourseId());
    if (courseResult == null) {
      courseResult = CourseResultLocalServiceUtil.create(course.getCourseId(), userId);
    }

    if (courseResult.getStartDate() == null) {
      courseResult.setStartDate(new Date());
    }

    try {
      java.util.Map<Long, Long> weights = PonderatedCourseEval.getActivitiesWeight(course);
      long score = PonderatedCourseEval.getScore(course);

      boolean passed = true;
      long result = 0;
      long weight = 0;
      List<LearningActivity> learningActivities =
          LearningActivityLocalServiceUtil.getMandatoryLearningActivitiesOfGroup(
              course.getGroupCreatedId());

      // Guardo los resultados de las actividades del usuario en el curso en un hashmap para no
      // tener que acceder a bbdd por cada uno de ellos
      List<LearningActivityResult> lresult =
          LearningActivityResultLocalServiceUtil.getMandatoryByGroupIdUserId(
              course.getGroupCreatedId(), userId);
      HashMap<Long, LearningActivityResult> results = new HashMap<Long, LearningActivityResult>();
      for (LearningActivityResult ar : lresult) {
        results.put(ar.getActId(), ar);
      }

      boolean isFailed = false;
      LearningActivityResult learningActivityResult = null;

      for (LearningActivity act : learningActivities) {

        if (!weights.containsKey(
            act
                .getActId())) { // Solo se tienen en cuenta las actividades obligatorias que tienen
                                // peso definido
          continue;
        }

        if (results.containsKey(act.getActId())) {
          learningActivityResult = results.get(act.getActId());
        } else {
          learningActivityResult = null;
        }

        if (learningActivityResult != null) {
          if (learningActivityResult.getEndDate() != null) {
            if (!learningActivityResult.isPassed()) {
              passed = false;
              if (act.getTries() > 0) {
                long userTries =
                    LearningActivityTryLocalServiceUtil.getLearningActivityTryByActUserCount(
                        act.getActId(), userId);
                if (userTries >= act.getTries()) {
                  isFailed = true;
                }
              }
            }
            result = result + (learningActivityResult.getResult() * weights.get(act.getActId()));

          } else {
            passed = false;
          }
        } else {
          passed = false;
        }
        weight += weights.get(act.getActId());
      }

      if (result > 0 && weight > 0) {
        result = result / weight;
      }

      if (result < score) {
        passed = false;
      }

      // Si el usuario se ha marcado como isFailed es porque lo tiene suspenso. Se le asigna un
      // passed a false y se marca la fecha de finalización del curso (passedDate).
      courseResult.setPassed(passed && !isFailed);
      // Se almacena el result del resultado del usuario en el curso.
      courseResult.setResult(result);
      if ((passed || isFailed) && courseResult.getPassedDate() == null) {
        courseResult.setPassedDate(new Date());
      }
      CourseResultLocalServiceUtil.update(courseResult);
      return true;

    } catch (PortalException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (DocumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return true;
  }
Esempio n. 18
0
  private void insertOldUser(long companyId, long creatorUserId, String line) {

    String parts[] = line.split(StringPool.COMMA);

    boolean autoPassword = false;
    String password = parts[2];
    boolean autoScreenName = true;
    String screenName = StringPool.BLANK;
    String emailAddress = parts[1];
    long facebookId = 0l;
    String openId = StringPool.BLANK;
    String firstName = parts[3];
    String middleName = StringPool.BLANK;
    String lastName = StringPool.BLANK;
    int prefixId = 0;
    int suffixId = 0;
    boolean male = parts[6].equalsIgnoreCase("1");
    int birthdayMonth = 1;
    int birthdayDay = 1;
    int birthdayYear = 2000;
    String jobTitle = StringPool.BLANK;
    long[] groupIds = null;
    long[] organizationIds = null;
    long[] roleIds = null;
    long[] userGroupIds = null;
    boolean sendEmail = false;

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy hh:mm");

    try {
      User user =
          UserLocalServiceUtil.addUser(
              creatorUserId,
              companyId,
              autoPassword,
              password,
              password,
              autoScreenName,
              screenName,
              emailAddress,
              facebookId,
              openId,
              Locale.US,
              firstName,
              middleName,
              lastName,
              prefixId,
              suffixId,
              male,
              birthdayMonth,
              birthdayDay,
              birthdayYear,
              jobTitle,
              groupIds,
              organizationIds,
              roleIds,
              userGroupIds,
              sendEmail,
              serviceContext);

      String createDate = parts[0];
      if (Validator.isNotNull(createDate)) {
        try {
          user.setCreateDate(dateFormat.parse(createDate));
        } catch (ParseException e) {
          e.printStackTrace();
        }
      }

      String lastLoginDate = parts[5];
      if (Validator.isNotNull(lastLoginDate)) {
        try {
          user.setLastLoginDate(dateFormat.parse(lastLoginDate));
        } catch (ParseException e) {
          e.printStackTrace();
        }
      }

      user.setLastName(parts[2]);
      user.setPasswordReset(false);
      user.setOpenId("no-invitation-check");
      user.setJobTitle("mail-not-sent");

      user = UserLocalServiceUtil.updateUser(user);

      _log.debug("User successfully created ==> " + user);

      String mobile = parts[4];

      if (Validator.isNotNull(mobile) && mobile.startsWith("091")) {
        String[] tokens = mobile.split(StringPool.DASH);
        if (tokens.length == 2 && tokens[1].length() == 10) {
          BridgeLocalServiceUtil.addPhone(
              user.getUserId(), User.class.getName(), user.getUserId(), tokens[1], "91", true);
        }
      }

    } catch (PortalException e) {
      _log.error(e.getMessage());
    } catch (SystemException e) {
      _log.error(e.getMessage());
    }
  }
Esempio n. 19
0
  public Orange(HashMap values) {

    super(values);
    this.setDoctype(Global.ORANGE);

    if (values.containsKey("uid")) {
      this.setId((String) values.get("uid"));
    }
    if (values.containsKey("PID")) {
      this.setPid((String) values.get("PID"));
    }
    if (values.containsKey("mods.title")) {
      this.setModsTitle((String) values.get("mods.title"));
    }
    if (values.containsKey("mods.author")) {
      this.setModsAuthor((String) values.get("mods.author"));
    }
    if (values.containsKey("mods.host.title")) {
      this.setModsHostTitle((String) values.get("mods.host.title"));
    }
    if (values.containsKey("mods.publication.date")) {
      this.setModsPublicationDate((String) values.get("mods.publication.date"));
    }
    if (values.containsKey("mods.ext.volume")) {
      this.setModsExtVolume((String) values.get("mods.ext.volume"));
    }
    if (values.containsKey("mods.ext.part")) {
      this.setModsExtPart((String) values.get("mods.ext.part"));
    }
    if (values.containsKey("mods.ext.pages")) {
      this.setModsExtPages((String) values.get("mods.ext.pages"));
    }

    if (values.containsKey("mods.host.author")) {
      this.setModsHostAuthor((String) values.get("mods.host.author"));
    }

    if (values.containsKey("mods.publisher")) {
      this.setModsPublisher((String) values.get("mods.publisher"));
    }

    if (values.containsKey("mods.publisher.location")) {
      this.setModsPublisherLocation((String) values.get("mods.publisher.location"));
    }

    if (values.containsKey("mods.shelfmark")) {
      this.setModsShelfmark((String) values.get("mods.shelfmark"));
    }

    if (values.containsKey("mods.reviewer.roleTerm")) {
      this.setReviewerRoleterm((String) values.get("mods.reviewer.roleTerm"));
    }

    if (values.containsKey("lastModifiedDate")) {
      String date = (String) values.get("lastModifiedDate");
      String day = date.substring(0, 10);
      String time = date.substring(11, 23);
      String formattedDate = day + "</br>" + time;
      this.setLastModifiedDate(formattedDate);
    }

    if (values.containsKey("roleIds")) {
      // parse to remove administrator
      String[] roleIds = ((String) values.get("roleIds")).split(",");
      String roleId = "";
      for (String thisRole : roleIds) {
        if (!thisRole.equals("administrator")) {
          roleId = thisRole.replaceAll("[^0-9]", "");
        }
      }
      User user;
      try {
        user = UserLocalServiceUtil.getUserById(Integer.parseInt(roleId));
        this.setUploader(user.getFullName());
        this.setUploaderScreenName(user.getScreenName());

      } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (PortalException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (SystemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    this.setStatus("Dataset is in the Orange Category");
    this.setStatusImgURL("/resources/images/orange.png");
    this.setMakeDatasetPublicText("Make Dataset publicly available");

    this.setDatasetdisplayURL(formatDatasetDisplayURL());
  }
  @Override
  public List<Group> getUserSitesGroups() throws PortalException {
    try {
      User user = getUser();

      List<Group> groups = new ArrayList<>();

      LinkedHashMap<String, Object> groupParams = new LinkedHashMap<>();

      groupParams.put("active", true);
      groupParams.put("usersGroups", user.getUserId());

      List<Group> userSiteGroups =
          groupLocalService.search(
              user.getCompanyId(), null, groupParams, QueryUtil.ALL_POS, QueryUtil.ALL_POS);

      for (Group userSiteGroup : userSiteGroups) {
        if (SyncUtil.isSyncEnabled(userSiteGroup)) {
          userSiteGroup.setName(userSiteGroup.getDescriptiveName());

          groups.add(userSiteGroup);
        }
      }

      List<Organization> organizations =
          organizationLocalService.getOrganizations(
              user.getUserId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);

      for (Organization organization : organizations) {
        Group userOrganizationGroup = organization.getGroup();

        if (SyncUtil.isSyncEnabled(userOrganizationGroup)) {
          groups.add(userOrganizationGroup);
        }

        if (!GetterUtil.getBoolean(PropsUtil.get(PropsKeys.ORGANIZATIONS_MEMBERSHIP_STRICT))) {

          for (Organization ancestorOrganization : organization.getAncestors()) {

            Group userAncestorOrganizationGroup = ancestorOrganization.getGroup();

            if (SyncUtil.isSyncEnabled(userAncestorOrganizationGroup)) {

              groups.add(userAncestorOrganizationGroup);
            }
          }
        }
      }

      if (PrefsPropsUtil.getBoolean(
          user.getCompanyId(),
          PortletPropsKeys.SYNC_ALLOW_USER_PERSONAL_SITES,
          PortletPropsValues.SYNC_ALLOW_USER_PERSONAL_SITES)) {

        groups.add(user.getGroup());
      }

      Collections.sort(groups, new GroupNameComparator());

      return ListUtil.unique(groups);
    } catch (PortalException pe) {
      throw new PortalException(pe.getClass().getName(), pe);
    }
  }
  public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
      throws IOException, PortletException {
    ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
    try {

      log.debug(":: VIEW STUDENT SEARCH " + this.viewJSP);

      PortletPreferences preferences = renderRequest.getPreferences();
      boolean showSearcher =
          GetterUtil.getBoolean(preferences.getValue("showSearcher", StringPool.TRUE));
      boolean showScreenName =
          GetterUtil.getBoolean(preferences.getValue("showScreenName", StringPool.TRUE));
      boolean showEmail =
          GetterUtil.getBoolean(preferences.getValue("showEmail", StringPool.FALSE));

      long teamId = ParamUtil.getLong(renderRequest, "team", 0);

      List<Team> teams = TeamLocalServiceUtil.getGroupTeams(themeDisplay.getScopeGroupId());

      renderRequest.setAttribute("showSearcher", showSearcher);
      renderRequest.setAttribute("showScreenName", showScreenName);
      renderRequest.setAttribute("showEmail", showEmail);

      PortletURL iteratorURL = renderResponse.createRenderURL();
      iteratorURL.setParameter("team", String.valueOf(teamId));

      /*iteratorURL.setParameter("showSearcher" ,  String.valueOf(showSearcher));
      iteratorURL.setParameter("showScreenName" , String.valueOf(showScreenName));
      iteratorURL.setParameter("showEmail" ,  String.valueOf(showEmail));*/

      UserSearchContainer userSearchContainer = new UserSearchContainer(renderRequest, iteratorURL);
      UserDisplayTerms displayTerms = (UserDisplayTerms) userSearchContainer.getDisplayTerms();
      LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
      params.put("usersGroups", new Long(themeDisplay.getScopeGroupId()));

      Course course = CourseLocalServiceUtil.fetchByGroupCreatedId(themeDisplay.getScopeGroupId());

      if (log.isDebugEnabled()) {
        log.debug("NAME " + displayTerms.getFirstName());
        log.debug("SURNAME " + displayTerms.getLastName());
        log.debug("SCREEN NAME " + displayTerms.getScreenName());
        log.debug("EMAIL ADDRESS " + displayTerms.getEmailAddress());
        log.debug("KEYWORDS " + displayTerms.getKeywords());
        log.debug("START " + userSearchContainer.getStart());
        log.debug("END  " + userSearchContainer.getEnd());

        log.debug("ADVANCED SEARCH " + displayTerms.isAdvancedSearch());
        log.debug("AND OPERATOR " + displayTerms.isAndOperator());
        log.debug("TEAM " + teamId);
      }

      if (log.isDebugEnabled()) {
        log.debug("NAME " + ParamUtil.getString(renderRequest, "firstName"));
      }

      if (course != null) {
        try {
          if (displayTerms.isAdvancedSearch()) {
            userSearchContainer.setResults(
                CourseLocalServiceUtil.getStudentsFromCourse(
                    themeDisplay.getCompanyId(),
                    themeDisplay.getScopeGroupId(),
                    userSearchContainer.getStart(),
                    userSearchContainer.getEnd(),
                    teamId,
                    displayTerms.getFirstName(),
                    displayTerms.getLastName(),
                    displayTerms.getScreenName(),
                    displayTerms.getEmailAddress(),
                    displayTerms.isAndOperator()));

            userSearchContainer.setTotal(
                CourseLocalServiceUtil.getStudentsFromCourseCount(
                    course.getCourseId(),
                    teamId,
                    displayTerms.getFirstName(),
                    displayTerms.getLastName(),
                    displayTerms.getScreenName(),
                    displayTerms.getEmailAddress(),
                    displayTerms.isAndOperator()));

          } else {
            userSearchContainer.setResults(
                CourseLocalServiceUtil.getStudentsFromCourse(
                    themeDisplay.getCompanyId(),
                    themeDisplay.getScopeGroupId(),
                    userSearchContainer.getStart(),
                    userSearchContainer.getEnd(),
                    teamId,
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    true));

            userSearchContainer.setTotal(
                CourseLocalServiceUtil.getStudentsFromCourseCount(
                    course.getCourseId(),
                    teamId,
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    true));
          }

        } catch (SystemException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if (log.isDebugEnabled()) {
        log.debug(" -- TOTAL: " + userSearchContainer.getTotal());
        log.debug(" -- SIZE: " + userSearchContainer.getResults().size());
      }

      renderRequest.setAttribute("searchContainer", userSearchContainer);
      renderRequest.setAttribute("team", teamId);
      renderRequest.setAttribute("teams", teams);

    } catch (SystemException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (PortalException e) {
      // TODO: handle exception
      e.printStackTrace();
    }

    this.include(this.viewJSP, renderRequest, renderResponse);
  }
  public void loadCategoriesFromCsv(ActionRequest actionRequest, ActionResponse actionResponse)
      throws IOException, PortletException, PortalException, SystemException {

    LOGGER.info("Begin  AssetCategoriesImporter");
    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);
    ThemeDisplay themeDisplay =
        (ThemeDisplay) uploadPortletRequest.getAttribute(WebKeys.THEME_DISPLAY);
    Map<String, FileItem[]> multipartParameterMap = uploadPortletRequest.getMultipartParameterMap();

    File file = null;
    BufferedReader bufferedReader = null;
    AssetVocabulary assetVocabulary = null;
    long userId = themeDisplay.getUserId();
    long groupId = themeDisplay.getScopeGroupId();

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(AssetCategory.class.getName(), uploadPortletRequest);

    // create vocabulary
    try {

      assetVocabulary =
          AssetVocabularyLocalServiceUtil.addVocabulary(
              userId,
              "Announcements",
              ServiceContextFactory.getInstance(
                  AssetVocabulary.class.getName(), uploadPortletRequest));
    } catch (DuplicateVocabularyException dve) {
      try {
        assetVocabulary =
            AssetVocabularyLocalServiceUtil.getGroupVocabulary(groupId, "Announcements");
      } catch (PortalException e) {
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug(e);
        }
        LOGGER.error(e.getMessage());
      } catch (SystemException e) {
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug(e);
        }
        LOGGER.error(e.getMessage());
      }
    }

    if (multipartParameterMap.keySet().contains("fileCategory")
        && Validator.isNotNull(assetVocabulary)) {
      try {
        file = uploadPortletRequest.getFile("fileCategory");
        bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath()));
        String line = StringPool.BLANK;
        long vocabularyId = assetVocabulary.getVocabularyId();

        String parentCategoryName = StringPool.BLANK;
        AssetCategory parentCategory = null;

        while ((line = bufferedReader.readLine()) != null) {

          // use comma as separator
          String[] categories = line.split(StringPool.SEMICOLON);

          if (categories.length == 4) {
            String parentCategoryCode = categories[0];

            if (Validator.isNull(parentCategory) || !parentCategoryName.equals(categories[1])) {
              parentCategoryName = categories[1];
              try {
                parentCategory =
                    AssetCategoryLocalServiceUtil.addCategory(
                        userId, parentCategoryName, vocabularyId, serviceContext);
                AssetCategoryPropertyLocalServiceUtil.addCategoryProperty(
                    userId, parentCategory.getCategoryId(), "Code", parentCategoryCode);
              } catch (Exception e) {
                if (LOGGER.isDebugEnabled()) {
                  LOGGER.debug(e);
                }
                LOGGER.error(e.getMessage());
              }
            }

            Map<Locale, String> titles = new HashMap<Locale, String>();
            Map<Locale, String> descriptionMap = new HashMap<Locale, String>();

            titles.put(LocaleUtil.fromLanguageId("fr_FR"), categories[3]);
            titles.put(LocaleUtil.fromLanguageId("en_US"), categories[3]);

            try {
              AssetCategory child =
                  AssetCategoryLocalServiceUtil.addCategory(
                      userId,
                      parentCategory.getCategoryId(),
                      titles,
                      descriptionMap,
                      vocabularyId,
                      null,
                      serviceContext);
              AssetCategoryPropertyLocalServiceUtil.addCategoryProperty(
                  userId, child.getCategoryId(), "Code", categories[2]);
            } catch (Exception e) {
              if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(e);
              }
              LOGGER.error(e.getMessage());
            }
          }
        }
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (bufferedReader != null) {
          try {
            bufferedReader.close();
          } catch (IOException e) {
            if (LOGGER.isDebugEnabled()) {
              LOGGER.debug(e);
            }
            LOGGER.error(e.getMessage());
          }
        }
      }
    }
    LOGGER.info("End  AssetCategoriesImporter");
  }
  public sample.lrdev05.database.model.Books addBooks(
      Books booksParam, long userId, ServiceContext serviceContext) {
    sample.lrdev05.database.model.Books booksVar;

    try {
      booksVar = booksPersistence.create(counterLocalService.increment(Books.class.toString()));
    } catch (SystemException e) {
      e.printStackTrace();
      return booksVar = null;
    }

    booksVar.setTitle(booksParam.getTitle());
    booksVar.setAuthor(booksParam.getAuthor());
    booksVar.setIsbn(booksParam.getIsbn());
    booksVar.setSummary(booksParam.getSummary());
    booksVar.setCompanyId(booksParam.getCompanyId());
    booksVar.setGroupId(booksParam.getGroupId());
    booksVar.setTitle(booksParam.getTitle());
    booksVar.setStatus(WorkflowConstants.STATUS_DRAFT);

    try {
      resourceLocalService.addResources(
          booksParam.getCompanyId(),
          booksParam.getGroupId(),
          userId,
          Books.class.getName(),
          booksParam.getPrimaryKey(),
          false,
          true,
          true);
      assetEntryLocalService.updateEntry(
          userId,
          booksVar.getGroupId(),
          Books.class.getName(),
          booksVar.getBookId(),
          serviceContext.getAssetCategoryIds(),
          serviceContext.getAssetTagNames());
      // Workflow
      WorkflowHandlerRegistryUtil.startWorkflowInstance(
          booksVar.getCompanyId(),
          booksVar.getGroupId(),
          userId,
          Books.class.getName(),
          booksVar.getPrimaryKey(),
          booksVar,
          serviceContext);

      sendMessage(booksVar, serviceContext);

    } catch (PortalException e) {
      e.printStackTrace();
      return booksVar = null;
    } catch (SystemException e) {
      e.printStackTrace();
      return booksVar = null;
    }

    try {
      return booksPersistence.update(booksVar, false);
    } catch (SystemException e) {
      e.printStackTrace();
      return booksVar = null;
    }
  }
  public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
      throws IOException, PortletException {

    ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
    HashMap<Date, ArrayList<HashMap<String, Object>>> resultado =
        new HashMap<Date, ArrayList<HashMap<String, Object>>>();
    List<TimeLinePopUp> listaPopUps = new ArrayList<TimeLinePopUp>();

    PortletPreferences prefs = renderRequest.getPreferences();
    String showInMain = prefs.getValue("showInMain", "true");
    String showItems = prefs.getValue("showItems", "true");
    String showAlerts = prefs.getValue("showAlerts", "true");

    // *********************
    // 1) Sites de LIFERAY
    // *********************
    List<Group> offices = new ArrayList<Group>();

    // Si el portlet se muestra en la pagina ppal, recorremos todas las oficianas a partir de un
    // sitio padre leido desde properties
    if (showInMain.equals("true")) {
      String mainSiteGroupId = com.liferay.util.portlet.PortletProps.get("lfvo.main.site.group.id");
      if (mainSiteGroupId != null && !"".equals(mainSiteGroupId)) {
        try {
          offices =
              GroupLocalServiceUtil.getGroups(
                  themeDisplay.getCompanyId(), Long.parseLong(mainSiteGroupId), true);

        } catch (NumberFormatException e) {
          e.printStackTrace();
          offices = GroupLocalServiceUtil.getGroups(themeDisplay.getCompanyId(), 0, true);
        }
      } else {
        offices = GroupLocalServiceUtil.getGroups(themeDisplay.getCompanyId(), 0, true);
      }
      // Si el portlet no se muestra en la pagina ppal, cogemos la oficina del sitio
    } else {
      offices.add(themeDisplay.getScopeGroup());
    }

    // *********************
    // 2) Sites de FIREBASE
    // *********************
    HashMap<String, Object> officesMap = new HashMap<String, Object>();
    try {
      DatabaseReference ref = FirebaseDatabase.getInstance().getReference("/offices/");
      Firebase firebase = new Firebase(ref.toString());
      FirebaseResponse response = firebase.get();
      officesMap = (HashMap<String, Object>) response.getBody();

    } catch (FirebaseException e2) {
      e2.printStackTrace();
    }

    if (officesMap != null) {
      for (Group office : offices) {

        HashMap<String, Object> officeBD =
            (HashMap<String, Object>)
                officesMap.get(
                    String.valueOf(office.getGroupId())); // Site Firebase <> Site Liferay
        if (officeBD != null) {

          try {
            List<Item> items = ItemLocalServiceUtil.getItems(office.getGroupId(), -1, -1);
            for (Item item : items) {

              // Si s�lo mostramos ITEMS y no ALERTS...
              if (showItems.equals("true") & showAlerts.equals("false")) {
                if (!"".equals(item.getType())
                    & !item.getType()
                        .equals("office")) { // Si tiene tipo, pero no es 'office' descartamos
                  continue;
                }
              }

              // Si s�lo mostramos ALERTS y no ITEMS...
              if (showItems.equals("false") & showAlerts.equals("true")) {
                if ("".equals(item.getType())
                    || item.getType()
                        .equals("office")) { // Si es vacio o es 'office' descartamos							
                  continue;
                }
              }

              // Si no mostramos nada...
              if (showItems.equals("false") & showAlerts.equals("false")) {
                continue;
              }

              HashMap<String, Object> miItem = new HashMap<String, Object>();

              // Creamos una fecha con formato simple
              Date createDate = item.getCreateDate();
              String fechaFormat = "";
              String fechaFormatEus = "";
              SimpleDateFormat dt1 = new SimpleDateFormat("dd/MM/yyyy");
              SimpleDateFormat dt2 = new SimpleDateFormat("yyyy/MM/dd");
              if (createDate != null) {
                fechaFormat = dt1.format(item.getCreateDate());
                fechaFormatEus = dt2.format(item.getCreateDate());
              } else {
                fechaFormat = dt1.format(item.getModifiedDate());
                fechaFormatEus = dt2.format(item.getModifiedDate());
              }

              // Quitamos la hora y minutos de la fecha original
              SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
              Date b = new Date();
              try {
                b = formatter.parse(fechaFormat);
              } catch (ParseException e) {

              }

              // PopUp - Mapa Street
              TimeLinePopUp miPopUp = new TimeLinePopUp();
              miPopUp.setDate_es(fechaFormat);
              miPopUp.setDate_eu(fechaFormatEus);
              miPopUp.setName(item.getName());
              miPopUp.setImage(this.obtenerImagenItem(item.getItemId()));
              miPopUp.setLat(String.valueOf(item.getLat()));
              miPopUp.setLng(String.valueOf(item.getLng()));

              listaPopUps.add(miPopUp);

              // HashMaps - Timeline
              miItem.put("image", this.obtenerImagenItem(item.getItemId()));
              miItem.put("name", item.getName());
              miItem.put("desc", item.getDescription());
              miItem.put("lat", item.getLat());
              miItem.put("lng", item.getLng());
              miItem.put("type", item.getType());

              if (resultado.get(b) == null) {
                resultado.put(b, new ArrayList<HashMap<String, Object>>());
              }
              resultado.get(b).add(miItem);
            }
          } catch (PortalException e) {
            e.printStackTrace();
          }
        }
      }
    }

    // Lista de PopUps
    Type listType = new TypeToken<List<TimeLinePopUp>>() {}.getType();
    Gson gson = new Gson();
    String json = gson.toJson(listaPopUps, listType);

    renderRequest.setAttribute("popUps", json);

    // En vez de ordenar el hashmap, ordenamos las keys
    ArrayList<Date> miArray = new ArrayList<Date>();
    for (Date date : resultado.keySet()) {
      miArray.add(date);
    }
    Collections.sort(miArray);

    renderRequest.setAttribute("resultado", resultado);
    renderRequest.setAttribute("orderedKeys", miArray);

    super.doView(renderRequest, renderResponse);
  }