psmlupdateaction.java

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

JAVA
1,411
字号
                        copyToFile.append(profile.getRoleName());
                        copyToFile.append(File.separator);
                    }
                    else if (profile.getUserName() != null)
                    {
                        copyToFile.append("user");
                        copyToFile.append(File.separator);
                        copyToFile.append(profile.getUserName());
                        copyToFile.append(File.separator);
                    }
                    if (profile.getMediaType() != null)
                    {
                        copyToFile.append(profile.getMediaType());
                        copyToFile.append(File.separator);
                    }
                    if (profile.getLanguage() != null)
                    {
                        copyToFile.append(profile.getLanguage());
                        copyToFile.append(File.separator);
                    }
                    if (profile.getCountry() != null)
                    {
                        copyToFile.append(profile.getCountry());
                        copyToFile.append(File.separator);
                    }
                    copyToFile.append(profile.getName());

                    if (!this.saveDocument(copyToFile.toString(), doc)) {
                        logger.error("Failed to save PSML document for [" + profile.getPath());
                    } else {
                        String msg = "Profile [" + profile.getPath() + "] has been saved to disk in [" + copyToFile.toString() + "]<br>";
                        logger.info(msg);
                        rundata.addMessage(msg);
                    }
                }
            }

        }
        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,
                                               "export_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 (copyTo != null) {
            rundata.getUser().setTemp(COPY_TO, copyTo);
        }

        logger.info("PsmlUpdateAction: Ending export all operation");
    }

    /** Save the PSML document on disk to the specififed fileOrUrl
     *
     * @param fileOrUrl a String representing either an absolute URL
     * or an absolute filepath
     * @param doc the document to save
     */
    private boolean saveDocument(String fileOrUrl, PSMLDocument doc)
    {
        boolean success = false;

        if (doc == null) return false;
        File f = new File(fileOrUrl);
        File d = new File(f.getParent());
        d.mkdirs();

        FileWriter writer = null;

        try
        {
            writer = new FileWriter(f);
            // create the serializer output format
            OutputFormat format = new OutputFormat();
            format.setIndenting(true);
            format.setIndent(4);
            Serializer serializer = new XMLSerializer(writer,format);
            Marshaller marshaller = new Marshaller(serializer.asDocumentHandler());
            marshaller.setMapping(this.loadMapping());
            marshaller.marshal(doc.getPortlets());

            success = true;
        }
        catch (MarshalException e)
        {
            logger.error("PSMLUpdateAction: Could not marshal the file " + f.getAbsolutePath(), e);
        }
        catch (MappingException e)
        {
            logger.error("PSMLUpdateAction: Could not marshal the file " + f.getAbsolutePath(), e);
        }
        catch (ValidationException e)
        {
            logger.error("PSMLUpdateAction: document "+f.getAbsolutePath() + " is not valid", e);
        }
        catch (IOException e)
        {
            logger.error("PSMLUpdateAction: Could not save the file " + f.getAbsolutePath(), e);
        }
        catch (Exception e)
        {
            logger.error("PSMLUpdateAction: Error while saving  " + f.getAbsolutePath(), e);
        }
        finally
        {
            try
            {
                writer.close();
            }
            catch (IOException e)
            {
            }
        }

        return success;
    }

    /**
     * Loads psml mapping file
     *
     * @exception Exception
     */
    private Mapping loadMapping()
        throws Exception
    {
        // get configuration parameters from Jetspeed Resources
        ResourceService serviceConf = ((TurbineServices)TurbineServices.getInstance())
                                                     .getResources(PsmlManagerService.SERVICE_NAME);

        // test the mapping file and create the mapping object
        Mapping mapping = null;
        String mapFile = serviceConf.getString("mapping","${webappRoot}/WEB-INF/conf/psml-mapping.xml");
        mapFile = TurbineServlet.getRealPath( mapFile );
        if (mapFile != null)
        {
            File map = new File(mapFile);
            if ( logger.isDebugEnabled() )
            {
                logger.debug( "Loading psml mapping file " + mapFile );
            }
            if (map.exists() && map.isFile() && map.canRead())
            {
                try
                {
                    mapping = new Mapping();
                    InputSource is = new InputSource( new FileReader(map) );
                    is.setSystemId( mapFile );
                    mapping.loadMapping( is );
                }
                catch (Exception e)
                {
                    logger.error("Error in psml mapping creation", e);
                    throw new Exception("Error in mapping");
                }
            }
            else
            {
                throw new Exception("PSML Mapping not found or not a file or unreadable: " + mapFile);
            }
        }

        return mapping;
    }

    /**
     * File Import Action for Psml.
     *
     * TODO: Implement file upload.
     *
     * @param rundata The turbine rundata context for this request.
     * @param context The velocity context for this request.
     */
    public void doImport(RunData rundata, Context context)
        throws Exception
    {
        Profile profile = null;
        ProfileLocator locator = null;
        String categoryName = null;
        String categoryValue = null;
        String copyFrom = null;
        String name = null;

        try
        {
            categoryName = rundata.getParameters().getString("CategoryName");
            categoryValue = rundata.getParameters().getString("CategoryValue");
            copyFrom = rundata.getParameters().getString("CopyFrom");
            name = rundata.getParameters().getString("name");
            //
            //create a new locator and set its values according to users input
            //
            locator = Profiler.createLocator();
            if (categoryName.equalsIgnoreCase(Profiler.PARAM_GROUP))
            {
                locator.setGroupByName(categoryValue);
            }
            else if (categoryName.equalsIgnoreCase(Profiler.PARAM_ROLE))
            {
                locator.setRoleByName(categoryValue);
            }
            else if (categoryName.equalsIgnoreCase(Profiler.PARAM_USER))
            {
                locator.setUser(JetspeedSecurity.getUser(categoryValue));
            }
            else
            {
                locator.setAnonymous(true);
            }

            String tempVar = rundata.getParameters().getString("psml_mediatype");
            if (tempVar != null && tempVar.trim().length() > 0)
            {
                locator.setMediaType(tempVar);
            }

            tempVar = rundata.getParameters().getString("psml_language");
            if (tempVar != null && tempVar.trim().length() > 0)
            {
                locator.setLanguage(tempVar);
            }

            tempVar = rundata.getParameters().getString("psml_country");
            if (tempVar != null && tempVar.trim().length() > 0)
            {
                locator.setCountry(tempVar);
            }

            locator.setName(name);

            //
            // validate that its not an 'blank' profile -- not allowed
            //
            if (name == null || name.trim().length() == 0)
            {
                JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
                DynamicURI duri = link.getPaneByName(PSML_UPDATE_PANE)
                                      .addPathInfo(SecurityConstants.PARAM_MODE,
                                                   "import")
                                      .addPathInfo(SecurityConstants.PARAM_MSGID,
                                                   SecurityConstants.MID_INVALID_ENTITY_NAME);
                JetspeedLinkFactory.putInstance(link);
                rundata.setRedirectURI(duri.toString());

                //save user entered values
                if (locator != null)
                {
                    rundata.getUser().setTemp(TEMP_LOCATOR, locator);
                }
                if (categoryName != null)
                {
                    rundata.getUser().setTemp(CATEGORY_NAME, categoryName);
                }
                if (categoryValue != null)
                {
                    rundata.getUser().setTemp(CATEGORY_VALUE, categoryValue);
                }
                if (copyFrom != null)
                {
                    rundata.getUser().setTemp(COPY_FROM, copyFrom);
                }
                return;
            }

            //
            // Retrieve the document to import
            //
            PSMLDocument doc = this.loadDocument(copyFrom);

            //
            // 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);
                }
                
                Portlets clonedPortlets = (Portlets) SerializationUtils.clone(portlets);
                org.apache.jetspeed.util.PortletUtils.regenerateIds(clonedPortlets);
                
                profile = Profiler.createProfile(locator, clonedPortlets);
            }
            else
            {
                throw new Exception("Failed to load PSML document from disk");
            }
            rundata.addMessage("Profile for [" + locator.getPath() + "] has been imported from file [" + copyFrom + "]<br>");
            setRefreshPsmlFlag(rundata, TRUE);

        }
        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")
                                  .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 (locator != null)
        {
           rundata.getUser().setTemp(TEMP_LOCATOR, locator);
        }
        if (categoryName != null)
        {
            rundata.getUser().setTemp(CATEGORY_NAME, categoryName);
        }
        if (categoryValue != null)
        {
            rundata.getUser().setTemp(CATEGORY_VALUE, categoryValue);
        }
        if (copyFrom != null)
        {
            rundata.getUser().setTemp(COPY_FROM, copyFrom);
        }

    }

    /**
     * File Import All Action for Psml.
     *
     *
     * @param rundata The turbine rundata context for this request.
     * @param context The velocity context for this request.
     */
    public void doImportall(RunData rundata, Context context)
        throws Exception
    {

⌨️ 快捷键说明

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