Exemplo n.º 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;
  }
 /**
  * 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);
   }
 }
Exemplo n.º 3
0
  /**
   * 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);
      }
    }
  }
Exemplo n.º 4
0
  private void handleCookie(String set_cookie, boolean cookie2, RoRequest req, Response resp)
      throws ProtocolException {
    Cookie[] cookies;
    if (cookie2) cookies = Cookie2.parse(set_cookie, req);
    else cookies = Cookie.parse(set_cookie, req);

    if (LOG.isDebugEnabled()) {
      LOG.debug("Received and parsed " + cookies.length + " cookies:");
      for (int idx = 0; idx < cookies.length; idx++)
        LOG.debug("Cookie " + idx + ": " + cookies[idx]);
    }

    Hashtable cookie_list = Util.getList(cookie_cntxt_list, req.getConnection().getContext());
    synchronized (cookie_list) {
      for (int idx = 0; idx < cookies.length; idx++) {
        Cookie cookie = (Cookie) cookie_list.get(cookies[idx]);
        if (cookie != null && cookies[idx].hasExpired()) {
          if (LOG.isDebugEnabled())
            LOG.debug("Cookie has expired and is " + "being removed: " + cookie);

          cookie_list.remove(cookie); // expired, so remove
        } else if (!cookies[idx].hasExpired()) // new or replaced
        {
          if (cookie_handler == null || cookie_handler.acceptCookie(cookies[idx], req, resp))
            cookie_list.put(cookies[idx], cookies[idx]);
        }
      }
    }
  }
Exemplo n.º 5
0
  private static void saveCookies() {
    if (cookie_jar != null
        && (!cookie_jar.exists() || cookie_jar.isFile() && cookie_jar.canWrite())) {
      Hashtable cookie_list = new Hashtable();
      Enumeration en =
          Util.getList(cookie_cntxt_list, HTTPConnection.getDefaultContext()).elements();

      // discard cookies which are not to be kept across sessions

      while (en.hasMoreElements()) {
        Cookie cookie = (Cookie) en.nextElement();
        if (!cookie.discard()) cookie_list.put(cookie, cookie);
      }

      // save any remaining cookies in jar
      if (cookie_list.size() > 0) {
        try {
          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(cookie_jar));
          oos.writeObject(cookie_list);
          oos.close();
        } catch (IOException t) {
          if (LOG.isTraceEnabled()) {
            LOG.trace("An exception occurred: " + t.getMessage());
          }
        }
      }
    }
  }
Exemplo n.º 6
0
  /** {@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();
  }
 public SoftwareRegistrationServiceImpl(
     ChromatticManager chromatticManager,
     NodeHierarchyCreator nodeHierarchyCreator,
     SettingService settingService,
     PlatformInformationRESTService platformInformationRESTService,
     InitParams initParams,
     UnlockService unlockService) {
   this.lifeCycle = chromatticManager.getLifeCycle(CHROMATTIC_LIFECYCLE_NAME);
   this.nodeHierarchyCreator = nodeHierarchyCreator;
   this.settingService = settingService;
   this.platformInformationRESTService = platformInformationRESTService;
   this.initParams = initParams;
   if (initParams != null && initParams.getValueParam(SOFTWARE_REGISTRATION_HOST) != null) {
     this.softwareRegistrationHost =
         initParams.getValueParam(SOFTWARE_REGISTRATION_HOST).getValue();
   }
   this.unlockService = unlockService;
   try {
     skipedNum =
         Integer.parseInt(initParams.getValueParam(SOFTWARE_REGISTRATION_SKIP_ALLOW).getValue());
   } catch (NumberFormatException nfe) {
     if (LOG.isWarnEnabled()) {
       LOG.warn("Skip allow configuration of PLF registration has been ignored!");
     }
   }
 }
  /** {@inheritDoc} */
  private boolean sendPlfInformation(String accessTokencode) {
    try {
      String url = softwareRegistrationHost + "/portal/rest/registerSoftware/register";
      HttpClient client = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);

      JsonPlatformInfo jsonPlatformInfo = platformInformationRESTService.getJsonPlatformInfo();
      JSONObject jsonObj = new JSONObject(jsonPlatformInfo);

      String input = jsonObj.toString();

      httpPost.setHeader("Accept", "application/json");
      httpPost.setHeader("Content-type", "application/json");
      httpPost.setHeader("Authorization", "Bearer " + accessTokencode);
      httpPost.setEntity(new StringEntity(input));

      HttpResponse response = client.execute(httpPost);

      if (response.getStatusLine().getStatusCode() != 200) {
        LOG.warn("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        return false;
      }
      return true;
    } catch (Exception e) {
      LOG.warn("Can not send Platform information to eXo community", e);
      return false;
    }
  }
 /**
  * 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;
 }
Exemplo n.º 10
0
  /**
   * 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);
    }
  }
Exemplo n.º 11
0
 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;
   }
 }
Exemplo n.º 12
0
  /** {@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);
  }
Exemplo n.º 13
0
  public boolean start() {
    try {
      prepareCache();

      ServerSocket serverSocket = null;
      int port = configuration.getCommandPort();
      // Trying to find a port available
      while (serverSocket == null) {
        try {
          serverSocket = new ServerSocket(port);
          LOG.info("FTPServer started on port '" + port + "'");
        } catch (BindException e) {
          LOG.warn(
              "Cannot launch the FTPServer on '" + (port++) + "', we try the next port number");
        }
      }

      dataChannelManager = new FtpDataChannelManagerImpl(configuration);

      acceptThread = new FtpAcceptThread(this, serverSocket);
      acceptThread.start();

      return true;
    } catch (Exception exc) {
      LOG.info("Unhandled exception. " + exc.getMessage(), exc);
    }

    return false;
  }
Exemplo n.º 14
0
  /** @see java.net.URLConnection#connect() */
  @Override
  public void connect() throws IOException {
    this.connected = true;
    String file = url.getFile();
    int index = file.indexOf("!/");
    if (index == -1) {
      // It is a direct file access
      this.directAccess = new File(file);
      if (!directAccess.exists())
        throw new FileNotFoundException("Cannot find the file at " + file);
      if (directAccess.isDirectory()) throw new IOException("A file was expected at " + file);
      return;
    }
    File f = new File(file.substring(0, index));
    if (!f.exists())
      throw new FileNotFoundException("Cannot find the file at " + f.getAbsolutePath());
    if (f.isDirectory()) throw new IOException("A zip file was expected at " + f.getAbsolutePath());
    this.zipFile = new ZipFile(f);
    try {
      int fromIndex = index + 2;
      index = file.indexOf("!/", fromIndex);
      String nameEntry;
      if (index == -1) nameEntry = file.substring(fromIndex);
      else nameEntry = file.substring(fromIndex, index);

      ZipEntry entry = zipFile.getEntry(nameEntry);
      if (entry == null)
        throw new FileNotFoundException(
            "Cannot find the file at " + file.substring(0, index == -1 ? file.length() : index));
      if (zipFile.getEntry(nameEntry + "/") != null)
        throw new IOException(
            "A "
                + (index == -1 ? "" : "zip")
                + " file was expected at "
                + file.substring(0, index == -1 ? file.length() : index));
      nameEntries = new ArrayList<String>();
      nameEntries.add(nameEntry);
      if (index == -1) {
        // there is no more entries
        return;
      }
      nameEntry = file.substring(index + 2);
      // We add it without checking if it exists to avoid reading twice the ZipInputStream
      nameEntries.add(nameEntry);
    } catch (IOException e) {
      try {
        zipFile.close();
      } catch (IOException e2) {
        LOG.debug("Could not close the zip file");
      }
      throw e;
    } catch (RuntimeException e) {
      try {
        zipFile.close();
      } catch (IOException e2) {
        LOG.debug("Could not close the zip file");
      }
      throw e;
    }
  }
Exemplo n.º 15
0
  public AbstractPageList<ResultNode> searchPageContents(
      SessionProvider sessionProvider,
      QueryCriteria queryCriteria,
      int pageSize,
      boolean isSearchContent)
      throws Exception {
    ManageableRepository currentRepository = repositoryService.getCurrentRepository();
    Session session = sessionProvider.getSession("portal-system", currentRepository);
    QueryManager queryManager = session.getWorkspace().getQueryManager();
    long startTime = System.currentTimeMillis();
    Query query = createSearchPageQuery(queryCriteria, queryManager);
    String suggestion = getSpellSuggestion(queryCriteria.getKeyword(), currentRepository);
    if (LOG.isDebugEnabled()) {
      LOG.debug("execute query: " + query.getStatement().toLowerCase());
    }
    AbstractPageList<ResultNode> pageList =
        PageListFactory.createPageList(
            query.getStatement(),
            session.getWorkspace().getName(),
            query.getLanguage(),
            true,
            new PageNodeFilter(),
            new PageDataCreator(),
            pageSize,
            0);

    long queryTime = System.currentTimeMillis() - startTime;
    pageList.setQueryTime(queryTime);
    pageList.setSpellSuggestion(suggestion);
    return pageList;
  }
Exemplo n.º 16
0
 @Managed
 @ManagedDescription("Clean all templates in Composer")
 public void cleanTemplates() throws Exception {
   this.templatesFilter = null;
   getTemplatesSQLFilter();
   if (LOG.isDebugEnabled()) LOG.debug("WCMComposer templates have been cleaned !");
 }
Exemplo n.º 17
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);
     }
   }
 }
Exemplo n.º 18
0
 private UIComponent addUIExtension(UIExtension extension, Map<String, Object> context)
     throws Exception {
   UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class);
   UIComponent component = manager.addUIExtension(extension, context, this);
   if (component == null) return null;
   synchronized (component) {
     if (component instanceof UIAbstractManagerComponent) {
       // You can access to the given extension and the extension is valid
       UIAbstractManagerComponent uiAbstractManagerComponent =
           (UIAbstractManagerComponent) component;
       uiAbstractManagerComponent.setUIExtensionName(extension.getName());
       uiAbstractManagerComponent.setUIExtensionCategory(extension.getCategory());
       return component;
     } else if (component != null) {
       // You can access to the given extension but the extension is not valid
       if (LOG.isWarnEnabled()) {
         LOG.warn(
             "All the extension '"
                 + extension.getName()
                 + "' of type '"
                 + EXTENSION_TYPE
                 + "' must be associated to a component of type "
                 + UIAbstractManagerComponent.class);
       }
       removeChild(component.getClass());
     }
   }
   return null;
 }
 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);
   }
 }
Exemplo n.º 20
0
  /*
   * (non-Javadoc)
   * @see
   * org.exoplatform.services.wcm.portal.artifacts.BasePortalArtifactsPlugin
   * #deployToPortal(java.lang.String,
   * org.exoplatform.services.jcr.ext.common.SessionProvider)
   */
  public void deployToPortal(SessionProvider sessionProvider, String portalName) throws Exception {
    try {
      NewsletterCategoryHandler categoryHandler = newsletterManagerService.getCategoryHandler();
      for (NewsletterCategoryConfig categoryConfig : categoryConfigs) {
        categoryHandler.add(sessionProvider, portalName, categoryConfig);
      }

      NewsletterSubscriptionHandler subscriptionHandler =
          newsletterManagerService.getSubscriptionHandler();
      for (NewsletterSubscriptionConfig subscriptionConfig : subscriptionConfigs) {
        subscriptionHandler.add(sessionProvider, portalName, subscriptionConfig);
      }

      Node portalNode = livePortalManagerService.getLivePortal(sessionProvider, portalName);
      String userFolderPath = NewsletterConstant.generateUserPath(portalName);
      ExtendedNode userFolderNode =
          (ExtendedNode) ((Node) portalNode.getSession().getItem(userFolderPath));
      if (userFolderNode.canAddMixin("exo:privilegeable"))
        userFolderNode.addMixin("exo:privilegeable");
      userFolderNode.setPermission("any", PermissionType.ALL);
    } catch (Exception e) {
      if (log.isInfoEnabled()) {
        log.info("InitialNewsletterPlugin fail because of ", e);
      }
    }
  }
Exemplo n.º 21
0
  public boolean isAllowedToOverride(String parameterName) {
    if (unmodifiableParameters.contains(parameterName)) {
      if (LOG.isWarnEnabled()) {
        LOG.warn(
            "Parameter "
                + parameterName
                + " is not overridden because it is set to 'unmodifiable' via system properties in the "
                + SystemParametersPersistenceConfigurator.class.getSimpleName());
      }
      return false;
    }

    if (beforeInitializeParameters.contains(parameterName)) {
      if (workspaceInitializer == null) {
        parametersToValidate.put(parameterName, new Exception());
        return true;
      } else {
        if (workspaceInitializer.isWorkspaceInitialized()) {
          if (LOG.isWarnEnabled()) {
            LOG.warn(
                "Parameter "
                    + parameterName
                    + " is not overridden because workspace is already initialized and parameter is set to 'before-initialize'"
                    + " via system properties in the "
                    + SystemParametersPersistenceConfigurator.class.getSimpleName());
          }
          return false;
        }
      }
    }

    return true;
  }
  /** {@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();
  }
Exemplo n.º 23
0
 /**
  * Gets the spell suggestion.
  *
  * @param checkingWord the checking word
  * @param manageableRepository the manageable repository
  * @return the spell suggestion
  * @throws Exception the exception
  */
 private String getSpellSuggestion(String checkingWord, ManageableRepository manageableRepository)
     throws Exception {
   // Retrieve spell suggestion in special way to avoid access denied exception
   String suggestion = null;
   Session session = null;
   try {
     session =
         manageableRepository.getSystemSession(
             manageableRepository.getConfiguration().getDefaultWorkspaceName());
     QueryManager queryManager = session.getWorkspace().getQueryManager();
     Query query =
         queryManager.createQuery(
             "SELECT rep:spellcheck() FROM nt:base WHERE jcr:path like '/' AND SPELLCHECK('"
                 + checkingWord
                 + "')",
             Query.SQL);
     RowIterator rows = query.execute().getRows();
     Value value = rows.nextRow().getValue("rep:spellcheck()");
     if (value != null) {
       suggestion = value.getString();
     }
   } catch (Exception e) {
     if (LOG.isWarnEnabled()) {
       LOG.warn(e.getMessage());
     }
   } finally {
     if (session != null) session.logout();
   }
   return suggestion;
 }
Exemplo n.º 24
0
 /** As getTemplatePath() but it will return value NULL in case of exception. */
 public String getTemplate() {
   try {
     return getTemplatePath();
   } catch (Exception e) {
     if (LOG.isDebugEnabled())
       LOG.debug("Catch an exception when getting template, return value NULL.\n Cause by: ", e);
     return null;
   }
 }
Exemplo n.º 25
0
 /** using for re-observer */
 public void start() {
   try {
     reInitObserver();
   } catch (Exception e) {
     if (LOG.isWarnEnabled()) {
       LOG.warn("==>>> Exeption when startd WatchDocumentSerice!!!!");
     }
   }
 }
Exemplo n.º 26
0
  private List<Node> getLastEditedNode(String noOfItem, String showGadgetWs) throws Exception {
    if (showGadgetWs != null && showGadgetWs.length() > 0) {
      show_gadget = Boolean.parseBoolean(showGadgetWs);
    }
    ArrayList<Node> lstNode = new ArrayList<Node>();
    StringBuffer bf = new StringBuffer(1024);
    List<String> lstNodeType = templateService.getDocumentTemplates();
    if (lstNodeType != null) {
      for (String nodeType : lstNodeType) {
        bf.append("(")
            .append(JCR_PRIMARYTYPE)
            .append("=")
            .append("'")
            .append(nodeType)
            .append("'")
            .append(")")
            .append(" OR ");
      }
    }

    if (bf.length() == 1) return null;
    bf.delete(bf.lastIndexOf("OR") - 1, bf.length());
    if (noOfItem == null || noOfItem.trim().length() == 0) noOfItem = String.valueOf(NO_PER_PAGE);
    String queryStatement = StringUtils.replace(QUERY_STATEMENT, "$0", NT_BASE);
    queryStatement = StringUtils.replace(queryStatement, "$1", bf.toString());
    queryStatement = StringUtils.replace(queryStatement, "$2", DATE_MODIFIED);
    ManageableRepository manageableRepository = repositoryService.getCurrentRepository();
    try {
      String[] workspaces = manageableRepository.getWorkspaceNames();
      List<String> lstWorkspace = new ArrayList<String>();
      // Arrays.asList() return fixed size list;
      lstWorkspace.addAll(Arrays.asList(workspaces));
      if (!show_gadget && lstWorkspace.contains(GADGET)) {
        lstWorkspace.remove(GADGET);
      }
      SessionProvider provider = WCMCoreUtils.createAnonimProvider();
      QueryImpl query = null;
      Session session = null;
      QueryResult queryResult = null;
      QueryManager queryManager = null;
      for (String workspace : lstWorkspace) {
        session = provider.getSession(workspace, manageableRepository);
        queryManager = session.getWorkspace().getQueryManager();
        query = (QueryImpl) queryManager.createQuery(queryStatement, Query.SQL);
        query.setLimit(Integer.parseInt(noOfItem));
        query.setOffset(0);
        queryResult = query.execute();
        puttoList(lstNode, queryResult.getNodes());
        session.logout();
      }
    } catch (RepositoryException e) {
      if (LOG.isErrorEnabled()) {
        LOG.error("Exception when execute SQL " + queryStatement, e);
      }
    }
    return lstNode;
  }
 public void activate() {
   try {
     getChild(UIPermissionInfoBase.class).updateGrid(1);
   } catch (Exception e) {
     if (LOG.isErrorEnabled()) {
       LOG.error("Unexpected error!", e.getMessage());
     }
   }
 }
Exemplo n.º 28
0
 /** @see java.net.URLConnection#getInputStream() */
 @Override
 public InputStream getInputStream() throws IOException {
   if (!connected) connect();
   if (directAccess != null) return new FileInputStream(directAccess);
   if (zipFile == null) throw new IOException("no zip file defined");
   try {
     if (nameEntries == null || nameEntries.isEmpty())
       throw new IOException("no entry name specified");
     ZipEntry entry = zipFile.getEntry(nameEntries.get(0));
     if (entry == null)
       throw new FileNotFoundException("The entry " + nameEntries.get(0) + " could not be found");
     if (nameEntries.size() == 1) {
       return new ArchiveInputStream(zipFile.getInputStream(entry));
     }
     String nameEntry = nameEntries.get(1);
     ZipInputStream zis = new ZipInputStream(zipFile.getInputStream(entry));
     boolean closeZis = true;
     try {
       ZipEntry subZP;
       ZipEntry found = null;
       while ((subZP = zis.getNextEntry()) != null) {
         if (subZP.getName().equals(nameEntry) || subZP.getName().equals(nameEntry + "/")) {
           found = subZP;
           break;
         }
       }
       if (found == null)
         throw new FileNotFoundException("Cannot find the file at " + url.getFile());
       if (found.isDirectory()) throw new IOException("A file was expected at " + url.getFile());
       closeZis = false;
       return new ArchiveInputStream(zis);
     } finally {
       if (closeZis) {
         try {
           zis.close();
         } catch (IOException e) {
           LOG.debug("Could not close the zip input stream");
         }
       }
     }
   } catch (IOException e) {
     try {
       zipFile.close();
     } catch (IOException e2) {
       LOG.debug("Could not close the zip file");
     }
     throw e;
   } catch (RuntimeException e) {
     try {
       zipFile.close();
     } catch (IOException e2) {
       LOG.debug("Could not close the zip file");
     }
     throw e;
   }
 }
Exemplo n.º 29
0
  private void initPrivateCalendar() throws Exception {
    log.info("Inject private datas ....");
    // save setting
    try {
      setting = calService.getCalendarSetting(currentUser);
      log.info(String.format("Save calendar setting for user %s ....", currentUser));
    } catch (Exception e) {
      setting = newCalendarSetting();
      calService.saveCalendarSetting(currentUser, setting);
    }
    long t = System.currentTimeMillis(), t1 = t;

    t = System.currentTimeMillis();
    // save EventCategoy
    List<EventCategory> eventCategories = findEventCategorys();
    for (EventCategory evCat : eventCategories) {
      calService.saveEventCategory(currentUser, evCat, true);
      eventCategory.add(evCat);
      eventCategorys.add(evCat.getId());
    }
    log.info(
        String.format(
            "Saved %s eventCategories in %sms",
            eventCategories.size(), (System.currentTimeMillis() - t)));
    // save calendar
    List<Calendar> calendars = findCalendars(false);
    List<CalendarEvent> events;
    int index = 0, size = calendars.size(), evsCal, evs = 0, tas = 0;
    for (Calendar calendar : calendars) {
      t = System.currentTimeMillis();
      calService.saveUserCalendar(currentUser, calendar, true);
      privateCalendar.add(calendar.getId());
      // save Event
      events = findCalendarEvent(calendar.getId(), "0", CalendarEvent.TYPE_EVENT, false);
      for (CalendarEvent event : events) {
        calService.saveUserEvent(currentUser, calendar.getId(), event, true);
      }
      evsCal = events.size();
      evs += evsCal;
      // save Task
      events = findCalendarEvent(calendar.getId(), "0", CalendarEvent.TYPE_TASK, false);
      tas += events.size();
      for (CalendarEvent event : events) {
        calService.saveUserEvent(currentUser, calendar.getId(), event, true);
      }
      log.info(
          String.format(
              "Saved Calendar %s/%s with %s Events and %s Tasks in %sms",
              (++index), size, evsCal, events.size(), (System.currentTimeMillis()) - t));
    }
    log.info(
        String.format(
            "INITIALIZED EventCategorys=%s / Calendars=%s / Events=%s / Tasks=%s in %sms",
            eventCategories.size(), calendars.size(), evs, tas, (System.currentTimeMillis() - t1)));
    saveHistoryInject();
  }
Exemplo n.º 30
0
 public static boolean isUserExisted(OrganizationService orgSevice, String value) {
   try {
     return (!isEmpty(value) && orgSevice.getUserHandler().findUserByName(value) != null);
   } catch (Exception e) {
     if (log.isDebugEnabled()) {
       log.debug("Fail to check if user exist", e);
     }
     return false;
   }
 }