psmlupdateaction.java

来自「jetspeed源代码」· Java 代码 · 共 1,411 行 · 第 1/4 页

JAVA
1,411
字号
        String copyFrom = null;

        try
        {
            copyFrom = rundata.getParameters().getString("CopyFrom");

            //
            // Collect all .psml files from the root specified
            //
            Vector files = new Vector();
            this.collectPsml(files, copyFrom);

            //
            // Process each file
            //
            for (Iterator it = files.iterator(); it.hasNext(); )
            {
                // If error occurs processing one entry, continue on with the others
                String path = null;
                try
                {
                    String psml = ((File) it.next()).getPath();
                    path = psml.substring(copyFrom.length() + 1);
                    ProfileLocator locator = this.mapFileToLocator(path);

                    PSMLDocument doc = this.loadDocument(psml);

                    //
                    // create a new profile
                    //
                    if(doc != null)
                    {
                        Portlets portlets = doc.getPortlets();
                        //
                        // Profiler does not provide update capability - must remove before replacing
                        //
                        if (PsmlManager.getDocument(locator) != null)
                        {
                            Profiler.removeProfile(locator);
                        }
                        Profiler.createProfile(locator, portlets);
                    }
                    else
                    {
                        throw new Exception("Failed to load PSML document [" + psml + "] from disk");
                    }
                    rundata.addMessage("Profile for [" + locator.getPath() + "] has been imported from file [" + psml + "]<br>");
                    setRefreshPsmlFlag(rundata, TRUE);
                }
                catch (Exception ouch)
                {
                    logger.error("Exception", ouch);
                    rundata.addMessage("ERROR importing file [" + path + "]: " + ouch.toString() + "<br>");
                }
            }

        }
        catch (Exception e)
        {
            // log the error msg
            logger.error("Exception", e);

            //
            // dup key found - display error message - bring back to same screen
            //
            JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
            DynamicURI duri = link.getPaneByName(PSML_UPDATE_PANE)
                                  .addPathInfo(SecurityConstants.PARAM_MODE,
                                               "import_all")
                                  .addPathInfo(SecurityConstants.PARAM_MSGID,
                                               SecurityConstants.MID_UPDATE_FAILED);
            JetspeedLinkFactory.putInstance(link);
            rundata.setRedirectURI(duri.toString());
        }
        // save values that user just entered so they don't have to re-enter
        if (copyFrom != null)
        {
            rundata.getUser().setTemp(COPY_FROM, copyFrom);
        }

    }

    /**
     * This method recursively collect all .psml documents starting at the given root
     *
     * @param v      Vector to put the file into
     * @param root   Root directory for import
     */
    private void collectPsml(Vector v, String root)
    {

        File dir = new File(root);
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++)
        {
            if (files[i].isDirectory())
            {
                collectPsml(v, files[i].getPath());
            }
            else if (files[i].isFile() && files[i].getPath().endsWith(".psml"))
            {
                v.add(files[i]);
            }
        }

    }

    /**
     * Creates profile locator from a given path in the format:
     *
     *   user/<name>/<mediaType>/<language>/<country>/<page>/
     *
     *   group/ ""
     *   role/  ""
     *
     * @param path The formatted profiler path string.
     * @param path   fully qualified .psml file name
     * @return profile locator
     */
    private ProfileLocator mapFileToLocator(String path)
    throws Exception
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("PsmlUpdateAction.createFromPath: processing path = " + path);
        }
        ProfileLocator result = Profiler.createLocator();

        // Tokenize the file path into elements
        StringTokenizer tok = new StringTokenizer(path, File.separator);

        // Load path elements into a vector for random access
        Vector tokens = new Vector();
        while (tok.hasMoreTokens())
        {
            tokens.add(tok.nextToken());
        }

        // Assume that 1st element is the profile type (user|role|group) and 2nd is the name
        if (tokens.size() > 1)
        {
            String type = (String) tokens.elementAt(0);
            String name = (String) tokens.elementAt(1);
            if (type.equals(Profiler.PARAM_USER))
            {
                result.setUser(JetspeedSecurity.getUser(name));
            }
            else if (type.equals(Profiler.PARAM_GROUP))
            {
                result.setGroup(JetspeedSecurity.getGroup(name));
            }
            else if (type.equals(Profiler.PARAM_ROLE))
            {
                result.setRole(JetspeedSecurity.getRole(name));
            }
        }

        // Assume that the last element is the page name
        if (tokens.size() > 0)
        {
            result.setName((String) tokens.lastElement());
        }

        // Based on the number of path elements set the other profile attributes
        switch (tokens.size())
        {
        case 3: // user|role|group/name/page.psml
            break;
        case 4: // user|role|group/name/media-type/page.psml
            result.setMediaType((String) tokens.elementAt(2));
            break;
        case 5: // user|role|group/name/media-type/language/page.psml
            result.setMediaType((String) tokens.elementAt(2));
            result.setLanguage((String) tokens.elementAt(3));
            break;
        case 6: // user|role|group/name/media-type/language/country/page.psml
            result.setMediaType((String) tokens.elementAt(2));
            result.setLanguage((String) tokens.elementAt(3));
            result.setCountry((String) tokens.elementAt(4));
            break;
        default:
            throw new Exception("Path must contain 3 to 6 elements: [" + path + "], and the size was: " + tokens.size());
        }

        return result;
    }

    /**
     * Maps a ProfileLocator to a file.
     *
     * @param locator The profile locator describing the PSML resource to be found.
     * @return the String path of the file.
     */
    private String mapLocatorToFile(ProfileLocator locator)
    {
        StringBuffer path = new StringBuffer();

        // move the base dir is either user or role is specified
        Role role = locator.getRole();
        Group group = locator.getGroup();
        JetspeedUser user = locator.getUser();

        if (user != null)
        {
            path.append(Profiler.PARAM_USER);
            String name = user.getUserName();
            if (null != name && name.length() > 0)
            {
                path.append(File.separator)
                    .append(name);
            }
        }
        else if (group != null)
        {
            path.append(Profiler.PARAM_GROUP);
            String name = group.getName();
            if (null != name && name.length() > 0)
            {
                path.append(File.separator)
                    .append(name);
            }
        }
        else if (null != role)
        {
            path.append(Profiler.PARAM_ROLE);
            String name = role.getName();
            if (null != name && name.length() > 0)
            {
                path.append(File.separator)
                    .append(name);
            }
        }

        // Media
        if (null != locator.getMediaType())
        {
            path.append(File.separator)
                .append(locator.getMediaType());
        }
        // Language
        if (null != locator.getLanguage())
        {
            path.append(File.separator)
                .append(locator.getLanguage());
        }
        // Country
        if (null != locator.getCountry())
        {
            path.append(File.separator)
                .append(locator.getCountry());
        }
        // Resource Name
        if (null != locator.getName())
        {
            if (!(locator.getName().endsWith(Profiler.DEFAULT_EXTENSION)))
            {
                path.append(File.separator)
                    .append(locator.getName()).append(Profiler.DEFAULT_EXTENSION);
            }
            else
            {
                path.append(File.separator)
                    .append(locator.getName());
            }
        }
        else
        {
            path.append(File.separator)
                .append(Profiler.FULL_DEFAULT_PROFILE);
        }

        return  path.toString();
    }

    /**
     * Load a PSMLDOcument from disk
     *
     * @param fileOrUrl a String representing either an absolute URL or an
     * absolute filepath
     */
    private PSMLDocument loadDocument(String fileOrUrl)
    {
        PSMLDocument doc = null;

        if (fileOrUrl != null)
        {

            // we'll assume the name is the the location of the file
            File f = null;

            f = new File(fileOrUrl);

            if (!f.exists())
            {
                return null;
            }

            doc = new BasePSMLDocument();
            doc.setName(fileOrUrl);

            // now that we have a file reference, try to load the serialized PSML
            Portlets portlets = null;
            FileReader reader = null;
            try
            {
                reader = new FileReader(f);

                Unmarshaller unmarshaller = new Unmarshaller(this.loadMapping());
                portlets = (Portlets) unmarshaller.unmarshal(reader);

                doc.setPortlets(portlets);

            }
            catch (IOException e)
            {
                logger.error("PSMLUpdateAction: Could not load the file " + f.getAbsolutePath(), e);
            }
            catch (MarshalException e)
            {
                logger.error("PSMLUpdateAction: Could not unmarshal the file " + f.getAbsolutePath(), e);
            }
            catch (MappingException e)
            {
                logger.error("PSMLUpdateAction: Could not unmarshal the file " + f.getAbsolutePath(), e);
            }
            catch (ValidationException e)
            {
                logger.error("PSMLUpdateAction: document " + f.getAbsolutePath() + " is not valid", e);
            }
            catch (Exception e)
            {
                logger.error("PSMLUpdateAction: Error while loading  " + f.getAbsolutePath(), e);
            }
            finally
            {
                try
                {
                    reader.close();
                }
                catch (IOException e)
                {
                }
            }
        }

        return doc;
    }

}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?