Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2009 eXo Platform SAS.
    *
    * This is free software; you can redistribute it and/or modify it
    * under the terms of the GNU Lesser General Public License as
    * published by the Free Software Foundation; either version 2.1 of
    * the License, or (at your option) any later version.
    *
    * This software is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
   * License along with this software; if not, write to the Free
   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
   */
  package org.exoplatform.services.jcr.ext.backup;
  
  import  org.jibx.runtime.BindingDirectory;
  import  org.jibx.runtime.IBindingFactory;
  import  org.jibx.runtime.IMarshallingContext;
  import  org.jibx.runtime.IUnmarshallingContext;
  import  org.jibx.runtime.JiBXException;
  
  import java.io.File;
  import java.net.URL;
  import java.util.HashMap;
  import java.util.List;
  
Created by The eXo Platform SARL .

Author(s):
Gennady Azarenkov
Version:
$Id: $
  
  public class BackupChainLog
  {

   
Start for 1.1 version log will be stored relative paths.
  
     protected static String VERSION_LOG_1_1 = "1.1";
  
     protected static Log logger = ExoLogger.getLogger("exo.jcr.component.ext.BackupChainLog");
  
     public static final String PREFIX = "backup-";
  
     private static final String SUFFIX = ".xml";
  
     private File log;
  
     private String configInfo;
  
     private final List<JobEntryInfojobEntries;
  
     private LogWriter logWriter;
  
     private LogReader logReader;
  
     private BackupConfig config;
  
     private String backupId;
  
     private Calendar startedTime;
 
    private Calendar finishedTime;
 
    private boolean finalized;
 
 
    private final String versionLog;
 
    private File rootDir;
 
    private String fullBackupType;
 
    private String incrementalBackupType;

   
BackupChainLog constructor.

Parameters:
logDir File, the directory to logs
config BackupConfig, the backup config
fullBackupType Sting, FQN for full backup
incrementalBackupType Sting, FQN for incremental backup
backupId String, the identifier of backup
wEntry original workspace config
Throws:
BackupOperationException will be generate the exception BackupOperationException
 
    public BackupChainLog(File logDirBackupConfig configString fullBackupTypeString incrementalBackupType,
             String backupIdRepositoryServiceConfiguration repositoryServiceConfigurationFile rootDir)
             throws BackupOperationException
    {
       try
       {
          this. = false;
          this. = ;
          this. =
                   new File(PrivilegedFileHelper.getCanonicalPath(logDir) + .
                            + ( + backupId + ));
          PrivilegedFileHelper.createNewFile(this.);
          this. = rootDir;
          this. = backupId;
          this. = fullBackupType;
          this. = incrementalBackupType;
          this. = config;
          this. = new ArrayList<JobEntryInfo>();
 
          this. = getWorkspaceEntry(configrepositoryServiceConfiguration);
 
          // write config info here
           = new LogWriter();
          .write(configfullBackupTypeincrementalBackupType);
          .writeWorkspaceEntry(repositoryServiceConfiguration);
       }
       catch (IOException e)
       {
          throw new BackupOperationException(e);
       }
       catch (XMLStreamException e)
       {
          throw new BackupOperationException(e);
       }
       catch (FactoryConfigurationError e)
       {
          throw new BackupOperationException(e);
       }
       catch (JiBXException e)
       {
          throw new BackupOperationException(e);
       }
       catch (RepositoryException e)
       {
          throw new BackupOperationException(e);
       }
       catch (RepositoryConfigurationException e)
       {
          throw new BackupOperationException(e);
       }
    }
 
             RepositoryServiceConfiguration repositoryServiceConfigurationthrows BackupOperationException
    {
       RepositoryEntry repository = null;
       try
       {
          repository = repositoryServiceConfiguration.getRepositoryConfiguration(config.getRepository());
       }
       catch (RepositoryConfigurationException e)
       {
          throw new BackupOperationException("Can not get repository \"" + config.getRepository() + "\""e);
       }
 
       WorkspaceEntry wEntry = null;
 
       for (WorkspaceEntry entry : repository.getWorkspaceEntries())
       {
          if (entry.getName().equals(config.getWorkspace()))
          {
             wEntry = entry;
             break;
          }
       }
 
       if (wEntry == null)
       {
          throw new BackupOperationException("Worksapce \"" + config.getWorkspace()
                   + "\" was not exsisted in repository \"" + repository.getName() + "\".");
       }
 
       return wEntry;
    }

   
BackupChainLog constructor.

Parameters:
log File, the backup log
Throws:
BackupOperationException will be generate the BackupOperationException
 
    public BackupChainLog(File logthrows BackupOperationException
    {
       this. = log;
       this. = log.getName().replaceAll("").replaceAll("");
 
       try
       {
           = new LogReader(log);
          .readLogFile();
          .jobEntrysNormalize();
 
          this. = .getVersionLog();
          this. = .getBackupConfig();
          this. = .getBeginTime();
          this. = .getEndTime();
          this. = .getJobEntryInfoNormalizeList();
          this. = .getFullBackupType();
 
          for (JobEntryInfo info : )
          {
             if (info.getType() == .)
             {
                .setBackupType(.);
                break;
             }
          }
       }
       catch (FileNotFoundException e)
       {
          throw new BackupOperationException(e);
       }
       catch (XMLStreamException e)
       {
          throw new BackupOperationException(e);
       }
       catch (FactoryConfigurationError e)
       {
          throw new BackupOperationException(e);
       }
       catch (MalformedURLException e)
       {
          throw new BackupOperationException(e);
       }
       catch (ValueFormatException e)
       {
          throw new BackupOperationException(e);
       }
       catch (Exception e)
       {
          throw new BackupOperationException(e);
       }
    }

   
Adding the the backup job.

Parameters:
job BackupJob, the backup job
 
    public void addJobEntry(BackupJob job)
    {
       // jobEntries
       try
       {
          JobEntryInfo info = new JobEntryInfo();
          info.setDate(Calendar.getInstance());
          info.setType(job.getType());
          info.setState(job.getState());
          info.setURL(job.getStorageURL());
 
          .write(info);
       }
       catch (IOException e)
       {
          .error("Can't add job"e);
       }
       catch (XMLStreamException e)
       {
          .error("Can't add job"e);
       }
       catch (BackupOperationException e)
       {
          .error("Can't add job"e);
       }
    }

   
Getting the backup id.

Returns:
int return the backup id
 
    public String getBackupId()
    {
       return ;
    }

   
Getting the config info.

Returns:
String return the config info
 
    public String getConfigInfo()
    {
       return ;
    }

   
Getting the job informations.

Returns:
List return the job informations.
 
    {
       return ;
    }

   
Finalize log.
 
    public void endLog()
    {
        = true;
       .writeEndLog();
 
       //copy backup chain log file in into Backupset files itself for portability (e.g. on another server)
       try
       {
          InputStream in = PrivilegedFileHelper.fileInputStream();
 
          File dest = new File(.getBackupDir() + . + .getName());
          if (!PrivilegedFileHelper.exists(dest))
          {
             OutputStream out = PrivilegedFileHelper.fileOutputStream(dest);
 
             byte[] buf = new byte[(int) (PrivilegedFileHelper.length())];
             in.read(buf);
 
             String sConfig = new String(buf.);
             sConfig = sConfig.replaceAll("<backup-dir>.+</backup-dir>""<backup-dir>.</backup-dir>");
 
             out.write(sConfig.getBytes(.));
             in.close();
             out.close();
          }
       }
 
       catch (FileNotFoundException e)
       {
          .error("Can't write log"e);
       }
       catch (UnsupportedEncodingException e)
       {
          .error("Can't write log"e);
       }
       catch (IOException e)
       {
          .error("Can't write log"e);
       }
    }

   
Getting the states for jobs.

Returns:
Collection return the collection of states for jobs
 
    {
       HashMap<IntegerJobEntryInfoinfos = new HashMap<IntegerJobEntryInfo>();
       for (JobEntryInfo jobEntry : )
       {
          infos.put(jobEntry.getID(), jobEntry);
       }
       return infos.values();
    }

   
Getting backup config.

Returns:
BackupConfig return the backup config
 
    public BackupConfig getBackupConfig()
    {
       return ;
    }

   
Getting log file path.

Returns:
String return the path to backup log
 
    public String getLogFilePath()
    {
       return PrivilegedFileHelper.getAbsolutePath();
    }

   
Getting the started time.

Returns:
Calendar return the started time
 
    public Calendar getStartedTime()
    {
       return ;
    }

   
Getting the finished time.

Returns:
Calendar return the finished time
 
    public Calendar getFinishedTime()
    {
       return ;
    }

   
Getting original workspace configuration

Returns:
WorkspaceEntry return the original workspace configuration
 
    {
       return ;
    }
 
    private class LogReader
    {
       protected Log logger = ExoLogger.getLogger("exo.jcr.component.ext.LogReader");
 
       private File logFile;
 
       private XMLStreamReader reader;
 
       private BackupConfig config;
 
       private List<JobEntryInfojobEntries;
 
       private List<JobEntryInfojobEntriesNormalize;
 
       private WorkspaceEntry originalWorkspaceEntry;
 
       private String version;
 
       private String iBackupType;
 
       private String fBackupType;
 
       {
          this. = logFile;
           = new ArrayList<JobEntryInfo>();
 
           =
                   XMLInputFactory.newInstance().createXMLStreamReader(
                            PrivilegedFileHelper.fileInputStream(this.), .);
       }
 
       public String getIncrementalBackupType()
       {
          return ;
       }
 
       public String getFullBackupType()
       {
          return ;
       }
 
       public String getVersionLog()
       {
          return ;
       }
 
       {
          return ;
       }
 
       public BackupConfig getBackupConfig()
       {
          return ;
       }
 
       public List<JobEntryInfogetJobEntryInfoList()
       {
          return ;
       }
 
       {
          return ;
       }
 
       public Calendar getBeginTime()
       {
          return .get(0).getDate();
       }
 
       public Calendar getEndTime()
       {
          return .get(.size() - 1).getDate();
       }
 
       public void readLogFile() throws Exception
       {
          boolean endDocument = false;
 
          while (!endDocument)
          {
             int eventCode = .next();
             switch (eventCode)
             {
 
                case . :
                   String name = .getLocalName();
 
                   if (name.equals("backup-config"))
                       = readBackupConfig();
 
                   if (name.equals("job-entry-info"))
                      .add(readJobEntryInfo());
 
                   if (name.equals("original-workspace-config"))
                      this. = readWorkspaceEntry();
 
                   if (name.equals("version-log"))
                   {
                      this. = readContent();
                   }
 
                   break;
 
                case . :
                   endDocument = true;
                   break;
             }
          }
       }
 
       private WorkspaceEntry readWorkspaceEntry() throws Exception
       {
          String configName = readContent();
 
          File configFile =
                   new File(PrivilegedFileHelper.getCanonicalPath(getBackupConfig().getBackupDir()) + .
                            + configName);
 
          if (!PrivilegedFileHelper.exists(configFile))
          {
             throw new WorkspaceRestoreExeption("The backup set is not contains original workspace configuration : "
                      + PrivilegedFileHelper.getCanonicalPath(getBackupConfig().getBackupDir()));
          }
 
          IBindingFactory factory;
          try
          {
             factory = SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction<IBindingFactory>()
             {
                public IBindingFactory run() throws Exception
                {
                   return BindingDirectory.getFactory(RepositoryServiceConfiguration.class);
                }
             });
          }
          catch (PrivilegedActionException pae)
          {
             Throwable cause = pae.getCause();
             if (cause instanceof JiBXException)
             {
                throw (JiBXException)cause;
             }
             else if (cause instanceof RuntimeException)
             {
                throw (RuntimeException)cause;
             }
             else
             {
                throw new RuntimeException(cause);
             }
          }
 
          IUnmarshallingContext uctx = factory.createUnmarshallingContext();
          RepositoryServiceConfiguration conf =
                   (RepositoryServiceConfigurationuctx.unmarshalDocument(PrivilegedFileHelper
                            .fileInputStream(configFile), null);
 
          RepositoryEntry repositoryEntry = conf.getRepositoryConfiguration(getBackupConfig().getRepository());
 
          if (repositoryEntry.getWorkspaceEntries().size() != 1)
          {
             throw new WorkspaceRestoreExeption(
                      "The oririginal configuration should be contains only one workspace entry :"
                      + PrivilegedFileHelper.getCanonicalPath(configFile));
          }
 
          if (!repositoryEntry.getWorkspaceEntries().get(0).getName().equals(getBackupConfig().getWorkspace()))
          {
             throw new WorkspaceRestoreExeption(
                      "The oririginal configuration should be contains only one workspace entry with name \""
                               + getBackupConfig().getWorkspace() + "\" :"
                               + PrivilegedFileHelper.getCanonicalPath(configFile));
          }
 
          return repositoryEntry.getWorkspaceEntries().get(0);
       }
 
       {
          JobEntryInfo info = new JobEntryInfo();
 
          boolean endJobEntryInfo = false;
 
          while (!endJobEntryInfo)
          {
             int eventCode = .next();
             switch (eventCode)
             {
 
                case . :
                   String name = .getLocalName();
 
                   if (name.equals("type"))
                      info.setType(getType(readContent()));
 
                   if (name.equals("state"))
                      info.setState(getState(readContent()));
 
                   if (name.equals("url"))
                   {
                      if ( != null && .equals())
                      {
                         String path =
                                  readContent().replace(
                                           "file:",
                                           "file:" + PrivilegedFileHelper.getCanonicalPath(.getBackupDir())
                                                    + .);
 
                         info.setURL(new URL(path));
                      }
                      else
                      {
                         info.setURL(new URL(readContent()));
                      }
                   }
 
                   if (name.equals("date"))
                      info.setDate(JCRDateFormat.parse(readContent()));
 
                   break;
 
                case . :
                   String tagName = .getLocalName();
 
                   if (tagName.equals("job-entry-info"))
                      endJobEntryInfo = true;
                   break;
             }
          }
 
          return info;
       }
 
       private int getState(String content)
       {
          int state = -1;
 
          if (content.equals("FINISHED"))
             state = .;
 
          if (content.equals("STARTING"))
             state = .;
 
          if (content.equals("WAITING"))
             state = .;
 
          if (content.equals("WORKING"))
             state = .;
 
          return state;
       }
 
       private int getType(String content)
       {
          int type = -1;
 
          if (content.equals("FULL"))
             type = .;
 
          if (content.equals("INCREMENTAL"))
             type = .;
 
          return type;
       }
 
       private BackupConfig readBackupConfig() throws XMLStreamExceptionIOException
       {
          BackupConfig conf = new BackupConfig();
 
          boolean endBackupConfig = false;
 
          while (!endBackupConfig)
          {
             int eventCode = .next();
             switch (eventCode)
             {
 
                case . :
                   String name = .getLocalName();
 
                   if (name.equals("backup-dir"))
                   {
                      if ( != null && .equals())
                      {
                         String dir = readContent();
                         if (dir.equals("."))
                         {
                            String path = PrivilegedFileHelper.getCanonicalPath(.getParentFile());
                            conf.setBackupDir(new File(path));
                         }
                         else
                         {
                            conf.setBackupDir(new File(dir));
                         }
                      }
                      else
                      {
                         conf.setBackupDir(new File(readContent()));
                      }
                   }
 
                   if (name.equals("repository"))
                      conf.setRepository(readContent());
 
                   if (name.equals("workspace"))
                      conf.setWorkspace(readContent());
 
                   if (name.equals("incremental-job-period"))
                      conf.setIncrementalJobPeriod(Long.valueOf(readContent()).longValue());
 
                   if (name.equals("incremental-job-number"))
                      conf.setIncrementalJobNumber(Integer.valueOf(readContent()).intValue());
 
                   if (name.equals("full-backup-type"))
                      this. = readContent();
 
                   if (name.equals("incremental-backup-type"))
                      this. = readContent();
 
                   break;
 
                case . :
                   String tagName = .getLocalName();
 
                   if (tagName.equals("backup-config"))
                      endBackupConfig = true;
                   break;
             }
          }
 
          return conf;
       }
 
       private String readContent() throws XMLStreamException
       {
          String content = null;
 
          int eventCode = .next();
 
          if (eventCode == .)
             content = .getText();
 
          return content;
       }
 
       public void jobEntrysNormalize()
       {
           = new ArrayList<JobEntryInfo>();
 
          for (int i = 0; i < .size(); i++)
          {
             JobEntryInfo entryInfo = .get(i);
 
             boolean alreadyExist = false;
 
             for (int j = 0; j < .size(); j++)
                if (.get(j).getURL().toString().equals(entryInfo.getURL().toString()))
                   alreadyExist = true;
 
             if (!alreadyExist)
                .add(entryInfo);
          }
       }
    }
 
    private class LogWriter
    {
 
       protected Log logger = ExoLogger.getLogger("exo.jcr.component.ext.LogWriter");
 
       private File logFile;
 
       XMLStreamWriter writer;
 
       {
          this. = file;
 
          try
          {
              = SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction<XMLStreamWriter>()
             {
                public XMLStreamWriter run() throws Exception
                {
                   return XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(),
                            .);
                }
             });
          }
          catch (PrivilegedActionException pae)
          {
             Throwable cause = pae.getCause();
             if (cause instanceof FileNotFoundException)
             {
                throw (FileNotFoundExceptioncause;
             }
             else if (cause instanceof XMLStreamException)
             {
                throw (XMLStreamExceptioncause;
             }
             else if (cause instanceof FactoryConfigurationError)
             {
                throw (FactoryConfigurationErrorcause;
             }
             else if (cause instanceof RuntimeException)
             {
                throw (RuntimeExceptioncause;
             }
             else
             {
                throw new RuntimeException(cause);
             }
          };
 
          .writeStartDocument();
          .writeStartElement("backup-chain-log");
 
          .writeStartElement("version-log");
          .writeCharacters();
          .writeEndElement();
 
          .flush();
       }
 
       public void writeWorkspaceEntry(WorkspaceEntry originalWorkspaceEntry,
                RepositoryServiceConfiguration serviceConfigurationthrows XMLStreamExceptionIOException,
                JiBXException, RepositoryExceptionRepositoryConfigurationException
       {
          File config =
                   new File(PrivilegedFileHelper.getCanonicalPath(BackupChainLog.this..getBackupDir())
                            + . + "original-workspace-config.xml");
          PrivilegedFileHelper.createNewFile(config);
          OutputStream saveStream = PrivilegedFileHelper.fileOutputStream(config);
 
          RepositoryEntry baseRepositoryEntry =
                   serviceConfiguration.getRepositoryConfiguration(BackupChainLog.this..getRepository());
 
          RepositoryEntry repositoryEntry = new RepositoryEntry();
          repositoryEntry.addWorkspace(originalWorkspaceEntry);
          repositoryEntry.setSystemWorkspaceName(baseRepositoryEntry.getSystemWorkspaceName());
          repositoryEntry.setAccessControl(baseRepositoryEntry.getAccessControl());
          repositoryEntry.setAuthenticationPolicy(baseRepositoryEntry.getAuthenticationPolicy());
          repositoryEntry.setDefaultWorkspaceName(baseRepositoryEntry.getDefaultWorkspaceName());
          repositoryEntry.setName(baseRepositoryEntry.getName());
          repositoryEntry.setSecurityDomain(baseRepositoryEntry.getSecurityDomain());
          repositoryEntry.setSessionTimeOut(baseRepositoryEntry.getSessionTimeOut());
 
          ArrayList<RepositoryEntryrepositoryEntries = new ArrayList<RepositoryEntry>();
          repositoryEntries.add(repositoryEntry);
 
          RepositoryServiceConfiguration newRepositoryServiceConfiguration =
                   new RepositoryServiceConfiguration(serviceConfiguration.getDefaultRepositoryName(), repositoryEntries);
 
          IBindingFactory bfact;
          try
          {
             bfact = SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction<IBindingFactory>()
             {
                public IBindingFactory run() throws Exception
                {
                   return BindingDirectory.getFactory(RepositoryServiceConfiguration.class);
                }
             });
          }
          catch (PrivilegedActionException pae)
          {
             Throwable cause = pae.getCause();
             if (cause instanceof JiBXException)
             {
                throw (JiBXException) cause;
             }
             else if (cause instanceof RuntimeException)
             {
                throw (RuntimeExceptioncause;
             }
             else
             {
                throw new RuntimeException(cause);
             }
          }
          IMarshallingContext mctx = bfact.createMarshallingContext();
 
          mctx.marshalDocument(newRepositoryServiceConfiguration"ISO-8859-1"nullsaveStream);
          saveStream.close();
 
          .writeStartElement("original-workspace-config");
          .writeCharacters(config.getName());
          .writeEndElement();
       }
 
       public synchronized void write(BackupConfig configString fullBackupTypeString incrementalBackupType)
                throws XMLStreamExceptionIOException
       {
          .writeStartElement("backup-config");
 
          .writeStartElement("full-backup-type");
          .writeCharacters(fullBackupType);
          .writeEndElement();
 
          .writeStartElement("incremental-backup-type");
          .writeCharacters(incrementalBackupType);
          .writeEndElement();
 
          if (config.getBackupDir() != null)
          {
             .writeStartElement("backup-dir");
             String path =
                      (isRootBackupManagerDir() ? PrivilegedFileHelper.getCanonicalPath(config.getBackupDir())
                               : ".");
 
             .writeCharacters(path);
             .writeEndElement();
          }
 
          if (config.getRepository() != null)
          {
             .writeStartElement("repository");
             .writeCharacters(config.getRepository());
             .writeEndElement();
          }
 
          if (config.getWorkspace() != null)
          {
             .writeStartElement("workspace");
             .writeCharacters(config.getWorkspace());
             .writeEndElement();
          }
 
          .writeStartElement("incremental-job-period");
          .writeCharacters(Long.toString(config.getIncrementalJobPeriod()));
          .writeEndElement();
 
          .writeStartElement("incremental-job-number");
         .writeCharacters(Integer.toString(config.getIncrementalJobNumber()));
         .writeEndElement();
         .writeEndElement();
         .flush();
      }
      public synchronized void write(JobEntryInfo infoBackupConfig configthrows XMLStreamExceptionIOException
      {
         .writeStartElement("job-entry-info");
         .writeStartElement("type");
         .writeCharacters((info.getType() == . ? "FULL" : "INCREMENTAL"));
         .writeEndElement();
         .writeStartElement("state");
         .writeCharacters(getState(info.getState()));
         .writeEndElement();
         .writeStartElement("url");
         .writeCharacters(getRelativeUrl(info.getURL(), config.getBackupDir()));
         .writeEndElement();
         .writeStartElement("date");
         .writeCharacters(JCRDateFormat.format(info.getDate()));
         .writeEndElement();
         .writeEndElement();
         .flush();
      }
      private String getRelativeUrl(URL urlFile backupDirthrows IOException
      {
         String str = PrivilegedFileHelper.getCanonicalPath(new File(url.getFile()));
         return url.getProtocol() + ":"
                  + str.replace(PrivilegedFileHelper.getCanonicalPath(.getBackupDir()) + ."");
      }
      private boolean isRootBackupManagerDir(File logthrows IOException
      {
         return (PrivilegedFileHelper.getCanonicalPath(log.getParentFile()).equals(PrivilegedFileHelper
                  .getCanonicalPath()));
      }
      public synchronized void writeEndLog()
      {
         try
         {
            .writeEndElement();
            .writeEndDocument();
            .flush();
         }
         catch (XMLStreamException e)
         {
            .error("Can't write log"e);
         }
      }
      private String getState(int iState)
      {
         String sState = "" + iState;
         switch (iState)
         {
            case . :
               sState = "FINISHED";
               break;
            case . :
               sState = "STARTING";
               break;
            case . :
               sState = "WAITING";
               break;
            case . :
               sState = "WORKING";
               break;
         }
         return sState;
      }
   }
   public boolean isFinilized()
   {
      return ;
   }
   public String getFullBackupType()
   {
      return ;
   }
   {
      return ;
   }