コード例 #1
1
  private org.exoplatform.calendar.model.Calendar persist(
      org.exoplatform.calendar.model.Calendar cal, boolean isNew) {
    Calendar o;
    if (cal instanceof Calendar) {
      o = (Calendar) cal;
    } else {
      o = Calendar.build(cal);
    }

    int type = o.getCalType();

    if (type == Calendar.Type.PERSONAL.type()) {
      try {
        dataStorage.saveUserCalendar(o.getCalendarOwner(), o, isNew);
      } catch (Exception ex) {
        LOG.error(ex);
      }
    } else if (type == Calendar.Type.GROUP.type()) {
      try {
        dataStorage.savePublicCalendar(o, isNew, null);
      } catch (Exception ex) {
        LOG.error(ex);
      }
    } else {
      throw new UnsupportedOperationException(
          "Save calendar with type '" + type + "' is not supported");
    }

    return cal;
  }
コード例 #2
1
  @GET
  @Path("join/{spaceName}")
  public Response join(
      @PathParam("spaceName") String spaceName,
      @Context SecurityContext sc,
      @Context UriInfo uriInfo) {

    try {

      String userId = getUserId(sc, uriInfo);
      if (userId == null) {
        return Response.status(HTTPStatus.INTERNAL_ERROR).cacheControl(cacheControl).build();
      }

      SpaceService spaceService =
          (SpaceService)
              ExoContainerContext.getCurrentContainer()
                  .getComponentInstanceOfType(SpaceService.class);
      if (spaceService.getSpaceById(spaceName).getRegistration().equals("open"))
        spaceService.addMember(spaceService.getSpaceById(spaceName), userId);

      return Response.ok("{}", MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
    } catch (Exception e) {
      log.error("Error in space deny rest service: " + e.getMessage(), e);
      return Response.ok("error").cacheControl(cacheControl).build();
    }
  }
コード例 #3
1
 /**
  * delete the event activity
  *
  * @param event
  * @param calendarId
  * @param eventType
  */
 private void deleteActivity(CalendarEvent event, String calendarId, String eventType) {
   try {
     Class.forName("org.exoplatform.social.core.space.spi.SpaceService");
   } catch (ClassNotFoundException e) {
     if (LOG.isDebugEnabled()) {
       LOG.debug("eXo Social components not found!", e);
     }
     return;
   }
   if (calendarId == null
       || calendarId.indexOf(CalendarDataInitialize.SPACE_CALENDAR_ID_SUFFIX) < 0) {
     return;
   }
   try {
     ActivityManager activityM =
         (ActivityManager)
             PortalContainer.getInstance().getComponentInstanceOfType(ActivityManager.class);
     SpaceService spaceService =
         (SpaceService)
             PortalContainer.getInstance().getComponentInstanceOfType(SpaceService.class);
     String spaceGroupId = Utils.getSpaceGroupIdFromCalendarId(calendarId);
     Space space = spaceService.getSpaceByGroupId(spaceGroupId);
     if (space != null && event.getActivityId() != null) {
       activityM.deleteActivity(event.getActivityId());
     }
   } catch (ExoSocialException e) {
     if (LOG.isDebugEnabled())
       LOG.error("Can not delete Activity for space when event deleted ", e);
   }
 }
コード例 #4
0
ファイル: FullBackupJob.java プロジェクト: pkdevbox/jcr
  /** {@inheritDoc} */
  public void run() {
    notifyListeners();

    try {
      repository.getWorkspaceContainer(workspaceName).setState(ManageableRepository.SUSPENDED);

      List<Backupable> backupableComponents =
          repository
              .getWorkspaceContainer(workspaceName)
              .getComponentInstancesOfType(Backupable.class);

      // backup all components
      for (Backupable component : backupableComponents) {
        component.backup(new File(getStorageURL().getFile()));
      }
    } catch (BackupException e) {
      LOG.error("Full backup failed " + getStorageURL().getPath(), e);
      notifyError("Full backup failed", e);
    } catch (RepositoryException e) {
      LOG.error("Full backup failed " + getStorageURL().getPath(), e);
      notifyError("Full backup failed", e);
    } finally {
      try {
        repository.getWorkspaceContainer(workspaceName).setState(ManageableRepository.ONLINE);
      } catch (RepositoryException e) {
        LOG.error("Full backup failed " + getStorageURL().getPath(), e);
        notifyError("Full backup failed", e);
      }
    }

    state = FINISHED;
    notifyListeners();
  }
コード例 #5
0
 /**
  * Check existed software registration node
  *
  * @return
  */
 private boolean hasSoftwareRegistration() {
   SessionProvider sessionProvider = null;
   try {
     if (hasSoftwareRegisteredNode) {
       return hasSoftwareRegisteredNode;
     } else {
       try {
         sessionProvider = SessionProvider.createSystemProvider();
         Node publicApplicationNode =
             nodeHierarchyCreator.getPublicApplicationNode(sessionProvider);
         if (publicApplicationNode.hasNode(SW_NODE_NAME)) {
           hasSoftwareRegisteredNode = true;
         } else {
           hasSoftwareRegisteredNode = false;
         }
       } catch (Exception e) {
         LOG.error("Software Registration: cannot get node", e);
         hasSoftwareRegisteredNode = false;
       } finally {
         sessionProvider.close();
       }
       return hasSoftwareRegisteredNode;
     }
   } catch (Exception e) {
     LOG.error("Software Registration: cannot check node", e);
   }
   return hasSoftwareRegisteredNode;
 }
コード例 #6
0
 private void saveToNewDataFormat(ExoSocialActivity activity) {
   try {
     final JSONObject jsonObject = new JSONObject(activity.getTitle());
     final String docActivityTitle =
         "<a href=\"${" + UIDocActivity.DOCLINK + "}\">" + "${" + UIDocActivity.DOCNAME + "}</a>";
     //
     activity.setTitle(docActivityTitle);
     //
     Map<String, String> activityParams = new HashMap<String, String>();
     activityParams.put(UIDocActivity.DOCNAME, jsonObject.getString(UIDocActivity.DOCNAME));
     activityParams.put(UIDocActivity.DOCLINK, jsonObject.getString(UIDocActivity.DOCLINK));
     activityParams.put(UIDocActivity.DOCPATH, jsonObject.getString(UIDocActivity.DOCPATH));
     activityParams.put(UIDocActivity.REPOSITORY, jsonObject.getString(UIDocActivity.REPOSITORY));
     activityParams.put(UIDocActivity.WORKSPACE, jsonObject.getString(UIDocActivity.WORKSPACE));
     activityParams.put(UIDocActivity.MESSAGE, jsonObject.getString(UIDocActivity.MESSAGE));
     activity.setTemplateParams(activityParams);
     //
     ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class);
     //
     activityManager.saveActivityNoReturn(activity);
     activity = activityManager.getActivity(activity.getId());
   } catch (JSONException je) {
     LOG.error("Error with activity's title data");
   } catch (ActivityStorageException ase) {
     LOG.error("Could not save new data format for document activity.", ase);
   } catch (Exception e) {
     LOG.error("Unknown error  to save document activity.", e);
   }
 }
コード例 #7
0
  /** {@inheritDoc} */
  public void start() {
    configuredTemplates_ = new HashMap<String, Set<String>>();
    RepositoryEntry repositoryEntry = null;
    try {
      repositoryEntry = repositoryService.getCurrentRepository().getConfiguration();
    } catch (RepositoryException e) {
      if (LOG.isErrorEnabled()) {
        LOG.error(e.getMessage(), e);
      }
    }

    String repoName = repositoryEntry.getName();
    String workspaceName = repositoryEntry.getSystemWorkspaceName();
    storedWorkspaces.put(repoName, workspaceName);
    basedApplicationTemplatesPath = hierarchyCreator.getJcrPath(BasePath.CMS_VIEWTEMPLATES_PATH);

    SessionProvider sessionProvider = SessionProvider.createSystemProvider();
    for (Iterator<String> repositories = storedWorkspaces.keySet().iterator();
        repositories.hasNext(); ) {
      String repository = repositories.next();
      try {
        Node storedTemplateHome = getBasedApplicationTemplatesHome(sessionProvider);
        importPredefinedTemplateToDB(storedTemplateHome);
      } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
          LOG.error(
              "Exception when import predefine application template into repository: " + repository,
              e);
        }
      }
    }
    sessionProvider.close();
  }
コード例 #8
0
ファイル: RESTRegistryService.java プロジェクト: nttuyen/jcr
  /**
   * Creates an entry in the group. In a case the group does not exist already it will be
   * automatically created.
   *
   * @param entryStream the input stream corresponding to the content of the registry entry
   * @param groupName the relative path to the group
   * @request {code} "entryStream" : the input stream corresponding to the content of the registry
   *     entry {code} Example : {code:xml} <registry
   *     xlinks:href="http://localhost:8080/portal/rest/registry/"> <GroovyScript2RestLoader
   *     xlinks:href="http://localhost:8080/portal/rest/registry/exo:services/GroovyScript2RestLoader"/>
   *     <Audit xlinks:href="http://localhost:8080/portal/rest/registry/exo:services/Audit"/>
   *     </registry> {code} @LevelAPI Experimental
   */
  @POST
  @Path("/{groupName:.+}")
  @Consumes(MediaType.APPLICATION_XML)
  public Response createEntry(
      InputStream entryStream, @PathParam("groupName") String groupName, @Context UriInfo uriInfo) {

    SessionProvider sessionProvider = sessionProviderService.getSessionProvider(null);
    try {
      RegistryEntry entry = RegistryEntry.parse(entryStream);
      regService.createEntry(sessionProvider, normalizePath(groupName), entry);
      URI location = uriInfo.getRequestUriBuilder().path(entry.getName()).build();
      return Response.created(location).build();
    } catch (IllegalArgumentException e) {
      LOG.error("Create registry entry failed", e);
      throw new WebApplicationException(e);
    } catch (IOException e) {
      LOG.error("Create registry entry failed", e);
      throw new WebApplicationException(e);
    } catch (SAXException e) {
      LOG.error("Create registry entry failed", e);
      throw new WebApplicationException(e);
    } catch (ParserConfigurationException e) {
      LOG.error("Create registry entry failed", e);
      throw new WebApplicationException(e);
    } catch (RepositoryException e) {
      LOG.error("Create registry entry failed", e);
      throw new WebApplicationException(e);
    }
  }
コード例 #9
0
 /**
  * This method will re-observer all nodes that have been ever observed with all repositories.
  *
  * @throws Exception
  */
 private void reInitObserver() throws Exception {
   RepositoryEntry repo = repoService_.getCurrentRepository().getConfiguration();
   ManageableRepository repository = repoService_.getCurrentRepository();
   String[] workspaceNames = repository.getWorkspaceNames();
   for (String workspace : workspaceNames) {
     Session session = repository.getSystemSession(workspace);
     QueryManager queryManager = null;
     try {
       queryManager = session.getWorkspace().getQueryManager();
     } catch (Exception e) {
       if (LOG.isErrorEnabled()) {
         LOG.error("Unexpected error", e);
       }
     }
     if (queryManager == null) {
       session.logout();
       continue;
     }
     try {
       Query query = queryManager.createQuery(WATCHABLE_MIXIN_QUERY, Query.XPATH);
       QueryResult queryResult = query.execute();
       for (NodeIterator iter = queryResult.getNodes(); iter.hasNext(); ) {
         Node observedNode = iter.nextNode();
         EmailNotifyListener emailNotifyListener = new EmailNotifyListener(observedNode);
         ObservationManager manager = session.getWorkspace().getObservationManager();
         List<String> list = getDocumentNodeTypes(observedNode);
         String[] observedNodeTypeNames = list.toArray(new String[list.size()]);
         manager.addEventListener(
             emailNotifyListener,
             Event.PROPERTY_CHANGED,
             observedNode.getPath(),
             true,
             null,
             observedNodeTypeNames,
             false);
       }
       session.logout();
     } catch (Exception e) {
       if (LOG.isWarnEnabled()) {
         LOG.warn(
             "==>>> Cannot init observer for node: "
                 + e.getLocalizedMessage()
                 + " in '"
                 + repo.getName()
                 + "' repository");
       }
       if (LOG.isErrorEnabled()) {
         LOG.error("Unexpected error", e);
       }
     }
   }
 }
コード例 #10
0
 /**
  * get user by name in range with sql statement
  *
  * @param username
  */
 public User getUserByNameLimtSQL(String username) {
   username.replaceAll("\"", "\\\"").replaceAll("-", StringUtils.EMPTY);
   username = username.trim();
   SessionProvider sProvider = SessionProvider.createSystemProvider();
   StringBuffer queryString = new StringBuffer("Select * from " + BookNodeTypes.EXO_USER);
   queryString.append(" where " + BookNodeTypes.EXO_USER_NAME + " = '" + username + "'");
   try {
     QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager();
     QueryImpl query = (QueryImpl) queryManager.createQuery(queryString.toString(), Query.SQL);
     query.setOffset(0L);
     query.setLimit(3L);
     QueryResult result = query.execute();
     NodeIterator nodes = result.getNodes();
     if (nodes.getSize() > 0) {
       Node node = nodes.nextNode();
       return createUserByNode(node);
     }
     return null;
   } catch (RepositoryException re) {
     log.error("Can not get user by name", re);
     return null;
   } finally {
     sProvider.close();
   }
 }
コード例 #11
0
 /**
  * get user by name with xpath
  *
  * @param username
  * @return
  */
 public User getUserByNameXPath(String username) {
   username.replaceAll("\"", "\\\"").replaceAll("-", StringUtils.EMPTY);
   username = username.trim();
   SessionProvider sProvider = SessionProvider.createSystemProvider();
   StringBuffer queryString =
       new StringBuffer(
           "//element(*, "
               + BookNodeTypes.EXO_USER
               + ")[(jcr:like(@"
               + BookNodeTypes.EXO_USER_NAME
               + ",'%"
               + username
               + "%'"
               + ") and @"
               + BookNodeTypes.EXO_USER_ADDRESS
               + "='Hanoi'"
               + ")]");
   try {
     QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager();
     Query query = queryManager.createQuery(queryString.toString(), Query.XPATH);
     QueryResult result = query.execute();
     NodeIterator nodes = result.getNodes();
     if (nodes.getSize() > 0) {
       Node node = nodes.nextNode();
       PropertyReader reader = new PropertyReader(node);
       return createUserByNode(node);
     }
     return null;
   } catch (RepositoryException re) {
     log.error("Can not get user by name(XPath)", re);
     return null;
   } finally {
     sProvider.close();
   }
 }
コード例 #12
0
 /**
  * add new user
  *
  * @param user
  * @param nodes
  * @return
  * @throws DuplicateBookException
  */
 public Node addUser(User user, List<String> nodes) throws DuplicateBookException {
   SessionProvider sProvider = SessionProvider.createSystemProvider();
   if (isExistUserName(user.getUsername(), sProvider)) {
     throw new DuplicateBookException(String.format("User %s is existed", user.getUsername()));
   }
   user.setUserId(Utils.userId++);
   try {
     Node parentNode = getNodeByPath(DEFAULT_PARENT_PATH + DEFAULT_PARENT_USER_PATH, sProvider);
     Node userNode = parentNode.addNode("" + user.getUserId(), BookNodeTypes.EXO_USER);
     userNode.setProperty(BookNodeTypes.EXO_USER_NAME, user.getUsername());
     userNode.setProperty(BookNodeTypes.EXO_USER_PASSWORD, user.getPassword());
     userNode.setProperty(BookNodeTypes.EXO_USER_FULLNAME, user.getFullname());
     userNode.setProperty(BookNodeTypes.EXO_USER_ADDRESS, user.getAddress());
     userNode.setProperty(BookNodeTypes.EXO_USER_PHONE, user.getPhone());
     List<Value> values = new ArrayList<Value>();
     for (String string : nodes) {
       Value val =
           parentNode.getSession().getValueFactory().createValue(getNodeByPath(string, sProvider));
       values.add(val);
     }
     userNode.setProperty(BookNodeTypes.EXO_BOOK, values.toArray(new Value[values.size()]));
     parentNode.getSession().save();
     return userNode;
   } catch (RepositoryException re) {
     log.error("Failed to add user", re);
     return null;
   } finally {
     sProvider.close();
   }
 }
コード例 #13
0
  // ============================================================================
  // ==
  public static String generateUUID(Object o) {
    StringBuffer tmpBuffer = new StringBuffer(16);
    if (hexServerIP_ == null) {
      InetAddress localInetAddress = null;
      try {
        // get the inet address
        localInetAddress = InetAddress.getLocalHost();
      } catch (java.net.UnknownHostException uhe) {
        // System .err .println(
        // "ContentSetUtil: Could not get the local IP address using InetAddress.getLocalHost()!"
        // );
        // todo: find better way to get around this...
        LOG.error(uhe.getLocalizedMessage(), uhe);
        return null;
      }
      byte serverIP[] = localInetAddress.getAddress();
      hexServerIP_ = hexFormat(getInt(serverIP), 8);
    }
    String hashcode = hexFormat(System.identityHashCode(o), 8);
    tmpBuffer.append(hexServerIP_);
    tmpBuffer.append(hashcode);

    long timeNow = System.currentTimeMillis();
    int timeLow = (int) timeNow & 0xFFFFFFFF;
    int node = seeder_.nextInt();

    StringBuffer guid = new StringBuffer(32);
    guid.append(hexFormat(timeLow, 8));
    guid.append(tmpBuffer.toString());
    guid.append(hexFormat(node, 8));
    return guid.toString();
  }
コード例 #14
0
 public void updateFolderAllowed(String path) {
   UIFormSelectBox sltWorkspace = getChildById(UIDriveInputSet.FIELD_WORKSPACE);
   String strWorkspace = sltWorkspace.getSelectedValues()[0];
   SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider();
   try {
     Session session =
         sessionProvider.getSession(
             strWorkspace,
             getApplicationComponent(RepositoryService.class).getCurrentRepository());
     Node rootNode = (Node) session.getItem(path);
     List<SelectItemOption<String>> foldertypeOptions = new ArrayList<SelectItemOption<String>>();
     RequestContext context = RequestContext.getCurrentInstance();
     ResourceBundle res = context.getApplicationResourceBundle();
     for (String foldertype : setFoldertypes) {
       if (isChildNodePrimaryTypeAllowed(rootNode, foldertype)) {
         try {
           foldertypeOptions.add(
               new SelectItemOption<String>(
                   res.getString(getId() + ".label." + foldertype.replace(":", "_")), foldertype));
         } catch (MissingResourceException mre) {
           foldertypeOptions.add(new SelectItemOption<String>(foldertype, foldertype));
         }
       }
     }
     Collections.sort(foldertypeOptions, new ItemOptionNameComparator());
     getUIFormSelectBox(FIELD_ALLOW_CREATE_FOLDERS).setOptions(foldertypeOptions);
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Unexpected problem occurs while updating", e);
     }
   }
 }
コード例 #15
0
ファイル: DBCleanService.java プロジェクト: pkdevbox/jcr
  /**
   * Cleans repository data from database.
   *
   * @param rEntry the repository configuration
   * @throws DBCleanException
   */
  public static void cleanRepositoryData(RepositoryEntry rEntry) throws DBCleanException {
    SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);

    WorkspaceEntry wsEntry = rEntry.getWorkspaceEntries().get(0);

    boolean multiDB = getMultiDbParameter(wsEntry);
    if (multiDB) {
      for (WorkspaceEntry entry : rEntry.getWorkspaceEntries()) {
        cleanWorkspaceData(entry);
      }
    } else {
      Connection jdbcConn = getConnection(wsEntry);
      String dialect = resolveDialect(jdbcConn, wsEntry);
      boolean autoCommit = dialect.startsWith(DialectConstants.DB_DIALECT_SYBASE);

      try {
        jdbcConn.setAutoCommit(autoCommit);

        DBCleanerTool dbCleaner = getRepositoryDBCleaner(jdbcConn, rEntry);
        doClean(dbCleaner);
      } catch (SQLException e) {
        throw new DBCleanException(e);
      } finally {
        try {
          jdbcConn.close();
        } catch (SQLException e) {
          LOG.error("Can not close connection", e);
        }
      }
    }
  }
コード例 #16
0
 /**
  * search book by name with like condition(using SQL)
  *
  * @param name The name of book
  * @return List<Book>
  */
 public List<Book> searchBookByNameLikeSQL(String name) {
   /* replace "" sign and - sign */
   name.replaceAll("\"", "\\\"").replaceAll("-", StringUtils.EMPTY);
   /* create query string */
   StringBuffer sb = new StringBuffer("Select * from " + BookNodeTypes.EXO_BOOK);
   sb.append(" where " + BookNodeTypes.EXO_BOOK_NAME + " like '%" + name + "%'");
   SessionProvider sProvider = SessionProvider.createSystemProvider();
   try {
     /* create QueryManager from session */
     QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager();
     /* create Query object */
     Query query = queryManager.createQuery(sb.toString(), Query.SQL);
     /* execute query and return result to QueryResult */
     QueryResult result = query.execute();
     /* transfer data to NodeIterator */
     NodeIterator nodes = result.getNodes();
     List<Book> books = new ArrayList<Book>();
     while (nodes.hasNext()) {
       Node node = nodes.nextNode();
       books.add(createBookByNode(node));
     }
     return books;
   } catch (RepositoryException re) {
     log.error("Can not find book", re);
     return null;
   } finally {
     sProvider.close();
   }
 }
コード例 #17
0
ファイル: SpaceServiceImpl.java プロジェクト: bangnv/social
  /** {@inheritDoc} */
  public void deleteSpace(Space space) {
    try {

      // remove memberships of users with deleted space.
      SpaceUtils.removeMembershipFromGroup(space);

      spaceStorage.deleteSpace(space.getId());

      OrganizationService orgService = getOrgService();
      UserACL acl = getUserACL();
      GroupHandler groupHandler = orgService.getGroupHandler();
      Group deletedGroup = groupHandler.findGroupById(space.getGroupId());
      List<String> mandatories = acl.getMandatoryGroups();
      if (deletedGroup != null) {
        if (!isMandatory(groupHandler, deletedGroup, mandatories)) {
          SpaceUtils.removeGroup(space);
        }
      } else {
        LOG.warn("deletedGroup is null");
      }

      // remove pages and group navigation of space
      SpaceUtils.removePagesAndGroupNavigation(space);

    } catch (Exception e) {
      LOG.error("Unable delete space", e);
    }
    spaceLifeCycle.spaceRemoved(space, null);
  }
コード例 #18
0
  public String getEditModeContent() {
    StringBuilder portletContent = new StringBuilder();
    try {
      PortalRequestContext prcontext =
          (PortalRequestContext) WebuiRequestContext.getCurrentInstance();
      prcontext.ignoreAJAXUpdateOnPortlets(true);
      StatefulPortletContext portletContext = uiPortlet_.getPortletContext();

      ExoPortletInvocationContext portletInvocationContext =
          new ExoPortletInvocationContext(prcontext, uiPortlet_);

      List<Cookie> requestCookies =
          new ArrayList<Cookie>(Arrays.asList(prcontext.getRequest().getCookies()));

      PortletInvocation portletInvocation = uiPortlet_.create(RenderInvocation.class, prcontext);
      RenderInvocation renderInvocation = (RenderInvocation) portletInvocation;
      // make sure we are in the EDIT mode, and not whatever the current portlet mode is for the
      // Portlet
      renderInvocation.setMode(Mode.create(PortletMode.EDIT.toString()));

      PortletInvocationResponse portletResponse = uiPortlet_.invoke(renderInvocation);
      portletContent.append(uiPortlet_.generateRenderMarkup(portletResponse, prcontext).toString());
    } catch (Throwable ex) {
      WebuiRequestContext webuiRequest = WebuiRequestContext.getCurrentInstance();
      portletContent.append(
          webuiRequest.getApplicationResourceBundle().getString("UIPortlet.message.RuntimeError"));
      log.error(
          "The portlet "
              + uiPortlet_.getName()
              + " could not be loaded. Check if properly deployed.",
          ExceptionUtil.getRootCause(ex));
    }
    return portletContent.toString();
  }
コード例 #19
0
ファイル: FAQUtils.java プロジェクト: phuonglm/forum
 public static void savePortletPreference(
     FAQSetting setting, String emailAddNewQuestion, String emailEditResponseQuestion) {
   try {
     PortletRequestContext pcontext =
         (PortletRequestContext) WebuiRequestContext.getCurrentInstance();
     PortletPreferences portletPref = pcontext.getRequest().getPreferences();
     portletPref.setValue("display", setting.getDisplayMode());
     portletPref.setValue("orderBy", setting.getOrderBy());
     portletPref.setValue("orderType", setting.getOrderType());
     portletPref.setValue("isDiscussForum", String.valueOf(setting.getIsDiscussForum()));
     portletPref.setValue("idNameCategoryForum", setting.getIdNameCategoryForum());
     portletPref.setValue("enableAutomaticRSS", setting.isEnableAutomaticRSS() + "");
     portletPref.setValue("enableViewAvatar", setting.isEnableViewAvatar() + "");
     portletPref.setValue("enanbleVotesAndComments", setting.isEnanbleVotesAndComments() + "");
     portletPref.setValue(
         "enableAnonymousSubmitQuestion", setting.isEnableAnonymousSubmitQuestion() + "");
     portletPref.setValue("SendMailAddNewQuestion", emailAddNewQuestion);
     portletPref.setValue("SendMailEditResponseQuestion", emailEditResponseQuestion);
     portletPref.setValue("emailMoveQuestion", setting.getEmailMoveQuestion());
     portletPref.setValue(
         "isPostQuestionInRootCategory", setting.isPostQuestionInRootCategory() + "");
     portletPref.store();
   } catch (Exception e) {
     log.error("Fail to save portlet preferences: ", e);
   }
 }
コード例 #20
0
ファイル: DBCleanerTool.java プロジェクト: pkdevbox/jcr
 protected void executeQuery(final Statement statement, final String sql) throws SQLException {
   try {
     long start = 0;
     if (LOG.isDebugEnabled()) {
       start = System.currentTimeMillis();
       LOG.debug("Execute script: \n[" + sql + "]");
     }
     SecurityHelper.doPrivilegedSQLExceptionAction(
         new PrivilegedExceptionAction<Object>() {
           public Object run() throws Exception {
             statement.executeUpdate(sql);
             return null;
           }
         });
     if (LOG.isDebugEnabled()) {
       LOG.debug(
           "Script "
               + sql
               + " executed in "
               + ((System.currentTimeMillis() - start) / 1000d)
               + " sec");
     }
   } catch (SQLException e) {
     LOG.error("Query execution \"" + sql + "\" failed: " + JDBCUtils.getFullMessage(e), e);
     throw e;
   }
 }
コード例 #21
0
ファイル: DBCleanerTool.java プロジェクト: pkdevbox/jcr
  /**
   * Execute script on database. Set auto commit mode if needed.
   *
   * @param scripts the scripts for execution
   * @throws SQLException
   */
  protected void execute(List<String> scripts) throws SQLException {
    SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);

    // set needed auto commit mode
    boolean autoCommit = connection.getAutoCommit();
    if (autoCommit != this.autoCommit) {
      connection.setAutoCommit(this.autoCommit);
    }

    Statement st = connection.createStatement();
    try {
      for (String scr : scripts) {
        String sql = JDBCUtils.cleanWhitespaces(scr.trim());
        if (!sql.isEmpty()) {
          if (LOG.isDebugEnabled()) {
            LOG.debug("Execute script: \n[" + sql + "]");
          }

          executeQuery(st, sql);
        }
      }
    } finally {
      try {
        st.close();
      } catch (SQLException e) {
        LOG.error("Can't close the Statement." + e.getMessage());
      }

      // restore previous auto commit mode
      if (autoCommit != this.autoCommit) {
        connection.setAutoCommit(autoCommit);
      }
    }
  }
コード例 #22
0
 /**
  * get all book in workspace
  *
  * @return List<Book>
  */
 public List<Book> getAllBook() {
   /* create query string */
   StringBuffer sb = new StringBuffer("Select * from " + BookNodeTypes.EXO_BOOK);
   SessionProvider sProvider = SessionProvider.createSystemProvider();
   try {
     /* create QueryManager from session */
     QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager();
     /* create Query object */
     Query query = queryManager.createQuery(sb.toString(), Query.SQL);
     /* execute query and return result to QueryResult */
     QueryResult result = query.execute();
     /* transfer data to NodeIterator */
     NodeIterator nodes = result.getNodes();
     List<Book> books = new ArrayList<Book>();
     while (nodes.hasNext()) {
       Node node = nodes.nextNode();
       books.add(createBookByNode(node));
     }
     return books;
   } catch (RepositoryException re) {
     log.error("Can not find book", re);
     return null;
   } finally {
     sProvider.close();
   }
 }
コード例 #23
0
 /**
  * search book by name with limit of result(using SQL)
  *
  * @param name The name of book
  * @return List<Book>
  */
 public List<Book> searchBookByNameLimitSQL(String name) {
   /* replace "" sign and - sign */
   name = name.replaceAll("\"", "\\\"").replaceAll("-", StringUtils.EMPTY);
   /* create query string */
   StringBuffer sb = new StringBuffer("Select * from " + BookNodeTypes.EXO_BOOK);
   SessionProvider sProvider = SessionProvider.createSystemProvider();
   try {
     /* create QueryManager from session */
     QueryManager queryManager = getSession(sProvider).getWorkspace().getQueryManager();
     /* create QueryImpl object */
     QueryImpl query = (QueryImpl) queryManager.createQuery(sb.toString(), QueryImpl.SQL);
     /* set offset(which first record will be get) */
     query.setOffset(2);
     /* set limit(how many record will be get after offset) */
     query.setLimit(3);
     /* execute query and return result to QueryResult */
     QueryResult result = query.execute();
     /* transfer data to NodeIterator */
     NodeIterator nodes = result.getNodes();
     List<Book> books = new ArrayList<Book>();
     while (nodes.hasNext()) {
       Node node = nodes.nextNode();
       books.add(createBookByNode(node));
     }
     return books;
   } catch (RepositoryException re) {
     log.error("Can not find book", re);
     return null;
   } finally {
     sProvider.close();
   }
 }
コード例 #24
0
ファイル: RepositoryContainer.java プロジェクト: ppalaga/jcr
  /** {@inheritDoc} */
  @Override
  public void start() {

    try {
      init();
      load();
    } catch (RepositoryException e) {
      log.error("Repository error", e);
      throw new RuntimeException(e);
    } catch (RepositoryConfigurationException e) {
      log.error("Configuration error", e);
      throw new RuntimeException(e);
    }

    super.start();
  }
コード例 #25
0
 @GET
 @Path("/all/{repoName}")
 public Response getCategory(@PathParam("repoName") String repoName) {
   List<CategoryNode> listCategoryNode = new ArrayList<CategoryNode>();
   if (repoName == null || repoName.trim().isEmpty()) {
     return Response.status(HTTPStatus.NOT_FOUND)
         .entity(new RepositoryException("Can't find repository"))
         .build();
   }
   // Get all category
   try {
     if (documentTypes.isEmpty())
       documentTypes = templateService_.getAllDocumentNodeTypes(repoName);
     List<Node> categoryNodes = taxonomyService_.getAllTaxonomyTrees(repoName);
     for (Node rootCategoryNode : categoryNodes) {
       getTaxnomyNodeRescursive(rootCategoryNode, rootCategoryNode, listCategoryNode);
     }
   } catch (Exception e) {
     LOG.error(e);
     return Response.serverError().build();
   }
   ListResultNode listResultNode = new ListResultNode();
   listResultNode.setLstNode(listCategoryNode);
   return Response.ok(listResultNode, new MediaType("application", "json")).build();
 }
コード例 #26
0
  public String getHomePageLogoURI() {
    SessionProvider sProvider = SessionProvider.createSystemProvider();
    Node rootNode = null;
    Node publicApplicationNode = null;
    String pathImageNode = null;
    Node ImageNode = null;
    Session session = null;
    try {
      publicApplicationNode = nodeCreator.getPublicApplicationNode(sProvider);
      session = publicApplicationNode.getSession();
      rootNode = session.getRootNode();
      Node logosNode = rootNode.getNode(path);
      if (logosNode.hasNode(logo_name)) {
        ImageNode = logosNode.getNode(logo_name);
        pathImageNode = ImageNode.getPath() + "?" + System.currentTimeMillis();
      }
    } catch (Exception e) {
      LOG.error("Can not get path of Logo : default LOGO will be used" + e.getMessage(), e);
      return null;
    } finally {
      if (session != null) session.logout();

      if (sProvider != null) sProvider.close();
    }

    return pathImageNode;
  }
コード例 #27
0
  @Override
  public void save(NotificationInfo message) throws Exception {
    boolean created = NotificationSessionManager.createSystemProvider();
    SessionProvider sProvider = NotificationSessionManager.getSessionProvider();
    final ReentrantLock localLock = lock;
    try {
      localLock.lock();
      Node messageHomeNode =
          getOrCreateMessageParent(sProvider, workspace, message.getKey().getId());
      Node messageNode = messageHomeNode.addNode(message.getId(), NTF_MESSAGE);
      messageNode.setProperty(NTF_FROM, message.getFrom());
      messageNode.setProperty(NTF_ORDER, message.getOrder());
      messageNode.setProperty(NTF_PROVIDER_TYPE, message.getKey().getId());
      messageNode.setProperty(NTF_OWNER_PARAMETER, message.getArrayOwnerParameter());
      messageNode.setProperty(NTF_SEND_TO_DAILY, message.getSendToDaily());
      messageNode.setProperty(NTF_SEND_TO_WEEKLY, message.getSendToWeekly());
      messageHomeNode.getSession().save();

      // record statistics insert entity
      if (NotificationContextFactory.getInstance().getStatistics().isStatisticsEnabled()) {
        NotificationContextFactory.getInstance().getStatisticsCollector().insertEntity(NTF_MESSAGE);
      }

    } catch (Exception e) {
      LOG.error("Failed to save the NotificationMessage", e);
    } finally {
      NotificationSessionManager.closeSessionProvider(created);
      localLock.unlock();
    }
  }
コード例 #28
0
  /**
   * add new book to workspace
   *
   * @param book The new book which want to add
   * @return Book
   * @throws DuplicateBookException
   */
  public Node addBook(Book book, String nodePath) throws DuplicateBookException {
    SessionProvider sProvider = SessionProvider.createSystemProvider();

    /* Check exist of book */
    if (isExistBookName(book.getName(), sProvider)) {
      throw new DuplicateBookException(String.format("Book %s is existed", book.getName()));
    }

    /* get id and set to new book */
    book.setBookId(Utils.bookId++);

    try {
      /* execute set data to node and save to workspace */
      Node parentNode = getNodeByPath(DEFAULT_PARENT_PATH + DEFAULT_PARENT_BOOK_PATH, sProvider);
      Node bookNode = parentNode.addNode("" + book.getBookId(), BookNodeTypes.EXO_BOOK);
      bookNode.setProperty(BookNodeTypes.EXO_BOOK_NAME, book.getName());
      bookNode.setProperty(
          BookNodeTypes.EXO_BOOK_CATEGORY, Utils.bookCategoryEnumToString(book.getCategory()));
      bookNode.setProperty(BookNodeTypes.EXO_BOOK_CONTENT, book.getContent());
      bookNode.setProperty(BookNodeTypes.EXO_BOOK_AUTHOR, getNodeByPath(nodePath, sProvider));
      parentNode.getSession().save();
      return bookNode;
    } catch (RepositoryException e) {
      log.error("Failed to add book", e);
      return null;
    } finally {
      sProvider.close();
    }
  }
コード例 #29
0
  /** {@inheritDoc} */
  public void onEvent(EventIterator eventIterator) {
    // waiting for Event.PROPERTY_ADDED, Event.PROPERTY_REMOVED,
    // Event.PROPERTY_CHANGED
    Session session = null;
    try {
      while (eventIterator.hasNext()) {
        Event event = eventIterator.nextEvent();
        String path = event.getPath();

        if (path.endsWith("/jcr:data")) {
          // jcr:data removed 'exo:groovyResourceContainer' then unbind resource
          if (event.getType() == Event.PROPERTY_REMOVED) {
            unloadScript(path.substring(0, path.lastIndexOf('/')));
          } else if (event.getType() == Event.PROPERTY_ADDED
              || event.getType() == Event.PROPERTY_CHANGED) {
            if (session == null) {
              session = repository.getSystemSession(workspaceName);
            }

            Node node = session.getItem(path).getParent();
            if (node.getProperty("exo:autoload").getBoolean()) loadScript(node);
          }
        }
      }
    } catch (Exception e) {
      LOG.error("Process event failed. ", e);
    } finally {
      if (session != null) {
        session.logout();
      }
    }
  }
コード例 #30
0
  public Book addBook(Book book) throws DuplicateBookException {
    SessionProvider sProvider = SessionProvider.createSystemProvider();

    String nodeId = IdGenerator.generate();
    book.setId(nodeId);

    try {
      Node parentNode = getNodeByPath(DEFAULT_PARENT_PATH, sProvider);
      Node bookNode = parentNode.addNode(nodeId, BookNodeTypes.EXO_BOOK);
      bookNode.setProperty(BookNodeTypes.EXP_BOOK_NAME, book.getName());
      bookNode.setProperty(
          BookNodeTypes.EXP_BOOK_CATEGORY, Utils.bookCategoryEnumToString(book.getCategory()));
      bookNode.setProperty(BookNodeTypes.EXP_BOOK_CONTENT, book.getContent());

      parentNode.getSession().save();
      return book;
    } catch (PathNotFoundException e) {
      return null;
    } catch (Exception e) {
      log.error("Failed to add book", e);
      return null;
    } finally {
      sProvider.close();
    }
  }