Author: areshetnyak
Date: 2010-12-21 05:51:58 -0500 (Tue, 21 Dec 2010)
New Revision: 3692
Modified:
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupClient.java
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupClientImpl.java
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupConsole.java
jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/RepositoryServiceConfiguration.java
jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/config/RepositoryServiceConfigurationImpl.java
jcr/trunk/exo.jcr.component.ext/pom.xml
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/BackupChainLog.java
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/ExtendedBackupManager.java
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/RepositoryBackupChainLog.java
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/BackupChainImpl.java
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/BackupManagerImpl.java
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/FileNameProducer.java
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/JobRepositoryRestore.java
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/RepositoryBackupChainImpl.java
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/server/HTTPBackupAgent.java
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/AbstractBackupUseCasesTest.java
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/TestFileNameProduser.java
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/server/HTTPBackupAgentTest.java
jcr/trunk/exo.jcr.component.ext/src/test/resources/conf/standalone/test-jcr-ext-config.xml
jcr/trunk/exo.jcr.docs/exo.jcr.docs.developer/en/src/main/docbook/en-US/modules/jcr/backup/backup-client.xml
jcr/trunk/exo.jcr.docs/exo.jcr.docs.developer/en/src/main/docbook/en-US/modules/jcr/backup/exojcr-backup-service.xml
Log:
JCR-1502 : All changes for this issue was committed.
Modified:
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupClient.java
===================================================================
---
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupClient.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupClient.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -127,6 +127,10 @@
* the backup identifier
* @param config
* InputStream contains workspace configuration
+ * @param backupSetPath
+ * String, path to backup set directory on server side
+ * @param removeExosts
+ * boolean. if 'true' then will be removed(clean db, value storage,
index) existed repository/workspace.
* @return String
* result
* @throws IOException
@@ -134,7 +138,9 @@
* @throws BackupExecuteException
* backup client internal exception
*/
- String restore(String repositoryName, String workspaceName, String backupId,
InputStream config) throws IOException,
+ String restore(String repositoryName, String workspaceName, String backupId,
InputStream config,
+ String backupSetPath, boolean removeExosts)
+ throws IOException,
BackupExecuteException;
/**
Modified:
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupClientImpl.java
===================================================================
---
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupClientImpl.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupClientImpl.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -462,40 +462,74 @@
/**
* {@inheritDoc}
*/
- public String restore(String repositoryName, String workspaceName, String backupId,
InputStream config)
+ public String restore(String repositoryName, String workspaceName, String backupId,
InputStream config,
+ String backupSetPath, boolean removeExists)
throws IOException, BackupExecuteException
{
if (workspaceName != null)
{
- String sURL =
- path + HTTPBackupAgent.Constants.BASE_URL +
HTTPBackupAgent.Constants.OperationType.RESTORE + "/"
- + repositoryName + "/" + backupId;
-
- WorkspaceEntry wEntry = null;
- try
+ String sURL = null;
+ BackupAgentResponse response = null;
+ if (config != null)
{
- wEntry = getWorkspaceEntry(config, repositoryName, workspaceName);
- }
- catch (Throwable e)
- {
- throw new BackupExecuteException("Can not get WorkspaceEntry for
workspace '" + workspaceName
- + "' from config.", e);
- }
+ if (backupId != null )
+ {
+ sURL =
+ path + HTTPBackupAgent.Constants.BASE_URL +
HTTPBackupAgent.Constants.OperationType.RESTORE + "/"
+ + repositoryName + "/" + backupId +
"/" + removeExists;
+ }
+ else if (backupSetPath != null)
+ {
+ sURL =
+ path + HTTPBackupAgent.Constants.BASE_URL
+ +
HTTPBackupAgent.Constants.OperationType.RESTORE_BACKUP_SET + "/"
+ + repositoryName + "/" + backupSetPath +
"/" + removeExists;
+ }
- JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
- JsonValue json;
+ WorkspaceEntry wEntry = null;
+ try
+ {
+ wEntry = getWorkspaceEntry(config, repositoryName, workspaceName);
+ }
+ catch (Throwable e)
+ {
+ throw new BackupExecuteException("Can not get WorkspaceEntry for
workspace '" + workspaceName
+ + "' from config.", e);
+ }
- try
- {
- json = generatorImpl.createJsonObject(wEntry);
+ JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
+ JsonValue json;
+
+ try
+ {
+ json = generatorImpl.createJsonObject(wEntry);
+ }
+ catch (JsonException e)
+ {
+ throw new BackupExecuteException("Can not get json from : " +
wEntry.getClass().toString(), e);
+ }
+
+ response = transport.executePOST(sURL, json.toString());
}
- catch (JsonException e)
+ else
{
- throw new BackupExecuteException("Can not get json from : " +
wEntry.getClass().toString(), e);
+ if (backupId != null)
+ {
+ sURL =
+ path + HTTPBackupAgent.Constants.BASE_URL +
HTTPBackupAgent.Constants.OperationType.RESTORE
+ + "/" + backupId + "/" +
removeExists;
+ }
+ else if (backupSetPath != null)
+ {
+ sURL =
+ path + HTTPBackupAgent.Constants.BASE_URL
+ +
HTTPBackupAgent.Constants.OperationType.RESTORE_BACKUP_SET + "/" +
repositoryName
+ + "/" + backupSetPath + "/" +
removeExists;
+ }
+
+ response = transport.executeGET(sURL);
}
- BackupAgentResponse response = transport.executePOST(sURL, json.toString());
-
if (response.getStatus() == Response.Status.OK.getStatusCode())
{
return "\nSuccessful : \n" + "\tstatus code = " +
response.getStatus() + "\n";
@@ -507,35 +541,71 @@
}
else
{
- String sURL =
- path + HTTPBackupAgent.Constants.BASE_URL
- + HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY +
"/" + backupId;
-
- RepositoryEntry wEntry = null;
- try
+ String sURL = null;
+ BackupAgentResponse response = null;
+ if (config != null)
{
- wEntry = getRepositoryEntry(config, repositoryName);
- }
- catch (Throwable e)
+ if (backupId != null)
+ {
+ sURL =
+ path + HTTPBackupAgent.Constants.BASE_URL
+ +
HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY + "/" + backupId +
"/"
+ + removeExists;
+ }
+ else if (backupSetPath != null)
+ {
+ sURL =
+ path + HTTPBackupAgent.Constants.BASE_URL
+ +
HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY_BACKUP_SET + "/"
+ + backupSetPath + "/"
+ + removeExists;
+ }
+
+ RepositoryEntry wEntry = null;
+ try
+ {
+ wEntry = getRepositoryEntry(config, repositoryName);
+ }
+ catch (Throwable e)
+ {
+ throw new BackupExecuteException("Can not get RepositoryEntry for
repository '" + repositoryName
+ + "' from config.", e);
+ }
+
+ JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
+ JsonValue json;
+
+ try
+ {
+ json = generatorImpl.createJsonObject(wEntry);
+ }
+ catch (JsonException e)
+ {
+ throw new BackupExecuteException("Can not get json from : " +
wEntry.getClass().toString(), e);
+ }
+
+ response = transport.executePOST(sURL, json.toString());
+ }
+ else
{
- throw new BackupExecuteException("Can not get RepositoryEntry for
repository '" + repositoryName
- + "' from config.", e);
- }
+ if (backupId != null)
+ {
+ sURL =
+ path + HTTPBackupAgent.Constants.BASE_URL
+ +
HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY + "/" + backupId +
"/"
+ + removeExists;
+ }
+ else if (backupSetPath != null)
+ {
+ sURL =
+ path + HTTPBackupAgent.Constants.BASE_URL
+ +
HTTPBackupAgent.Constants.OperationType.RESTORE_BACKUP_SET
+ + "/" + backupSetPath + "/" +
removeExists;
+ }
- JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
- JsonValue json;
-
- try
- {
- json = generatorImpl.createJsonObject(wEntry);
+ response = transport.executeGET(sURL);
}
- catch (JsonException e)
- {
- throw new BackupExecuteException("Can not get json from : " +
wEntry.getClass().toString(), e);
- }
- BackupAgentResponse response = transport.executePOST(sURL, json.toString());
-
if (response.getStatus() == Response.Status.OK.getStatusCode())
{
return "\nSuccessful : \n" + "\tstatus code = " +
response.getStatus() + "\n";
Modified:
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupConsole.java
===================================================================
---
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupConsole.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupConsole.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -71,10 +71,10 @@
+ " stop <backup_id> \n"
+ " status <backup_id> \n"
+ " restores <repo[/ws]> \n"
- + " restore <repo[/ws]> <backup_id>
<pathToConfigFile> \n"
+ + " restore [remove-exists] [<repo[/ws]>]
{<backup_id>|<backup_set_path>} [<pathToConfigFile>] \n"
+ " list [completed] \n"
+ " info \n"
- + " drop [force-close-session] <repo[/ws]>
\n"
+ + " drop [force-close-session] <repo[/ws]> \n"
+ " help \n\n"
+ " start - start backup of repositpry or workspace \n"
@@ -90,9 +90,11 @@
+ " <repo[/ws]> -
/<reponsitory-name>[/<workspace-name>] the repository or workspace \n"
+ " <backup_dir> - path to folder for backup on remote server
\n"
- + " <backup_id> - the identifier for backup \n"
+ + " <backup_id> - the identifier for backup \n"
+ + " <backup_set_dir> - path to folder with backup set on remote
server\n"
+ " <incr> - incemental job period \n"
+ " <pathToConfigFile> - path (local) to repository or workspace
configuration \n"
+ + " remove-exists - remove fully (db, value storage,
index) exists repository/workspace \n"
+ " force-close-session - close opened sessions on repositpry or workspace.
\n\n";
/**
@@ -423,21 +425,111 @@
else if (command.equalsIgnoreCase("restore"))
{
- String pathToWS = getRepoWS(args, curArg++);
- if (pathToWS == null)
+ /*
+ All valid combination of paramter.
+ 1. restore remove-exists <repo/ws> <backup_id>
<pathToConfigFile>
+ 2. restore remove-exists <repo> <backup_id>
<pathToConfigFile>
+ 3. restore remove-exists <repo/ws> <backup_set_path>
<pathToConfigFile>
+ 4. restore remove-exists <repo> <backup_set_path>
<pathToConfigFile>
+ 5. restore remove-exists <backup_id>
+ 6. restore remove-exists <backup_set_path>
+ 7. restore <repo/ws> <backup_id> <pathToConfigFile>
+ 8. restore <repo> <backup_id> <pathToConfigFile>
+ 9. restore <repo/ws> <backup_set_path> <pathToConfigFile>
+ 10. restore <repo> <backup_set_path> <pathToConfigFile>
+ 11. restore <backup_id>
+ 12. restore <backup_set_path>
+ */
+
+ boolean removeExists = false;
+ String backupSetPath = null;
+ String backupId = null;
+ String pathToWS = null;
+ String repositoryName = null;
+ String workspaceName = null;
+
+ String parameter = args[curArg++];
+
+ //check remove-exists
+ if (parameter.equals("remove-exists"))
+ {
+ removeExists = true;
+
+ if (curArg == args.length)
+ {
+ System.out.println(INCORRECT_PARAM + "Should be more
parameters.");
+ return;
+ }
+ }
+
+ if (removeExists)
+ {
+ parameter = args[curArg++];
+ }
+
+ //check backup_id
+ if (isBackupId(parameter))
+ {
+ backupId = parameter;
+ curArg++;
+
+ if (curArg < args.length)
+ {
+ System.out.println(TOO_MANY_PARAMS);
+ return;
+ }
+
+ //5. restore remove-exists <backup_id>
+ //11. restore <backup_id>
+ System.out.println(client.restore(repositoryName, workspaceName, backupId,
null,
+ backupSetPath, removeExists));
return;
+ }
+ //check /repo/ws or /repo
+ else if (isRepoWS(parameter))
+ {
+ pathToWS = getRepoWS(args, curArg - 1);
+ if (pathToWS == null)
+ return;
- String repositoryName = getRepositoryName(pathToWS);
- String workspaceName = (pathToWS.split("/").length == 3 ?
getWorkspaceName(pathToWS) : null);
+ repositoryName = getRepositoryName(pathToWS);
+ workspaceName = (pathToWS.split("/").length == 3 ?
getWorkspaceName(pathToWS) : null);
+ }
+ // this is backup_set_path
+ else
+ {
+ backupSetPath = parameter;
- // backup id
+ if (curArg < args.length)
+ {
+ System.out.println(INCORRECT_PARAM + "Should be less parameters :
" + parameter);
+ return;
+ }
+
+ //6. restore remove-exists <backup_set_path>
+ //12. restore <backup_set_path>
+ System.out.println(client.restore(repositoryName, workspaceName, backupId,
null, backupSetPath,
+ removeExists));
+ return;
+ }
+
+ // check backup_id or backup_set_path
if (curArg == args.length)
{
- System.out.println(INCORRECT_PARAM + "There is no backup identifier
parameter.");
+ System.out.println(INCORRECT_PARAM + "There is no backup identifier
or backup set path parameter.");
return;
}
- String backupId = args[curArg++];
+ parameter = args[curArg++];
+ if (isBackupId(parameter))
+ {
+ backupId = parameter;
+ }
+ else
+ {
+ backupSetPath = parameter;
+ }
+
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no path to config file
parameter.");
@@ -457,7 +549,19 @@
System.out.println(TOO_MANY_PARAMS);
return;
}
- System.out.println(client.restore(repositoryName, workspaceName, backupId,
new FileInputStream(conf)));
+
+ /*
+ 1. restore remove-exists <repo/ws> <backup_id>
<pathToConfigFile>
+ 2. restore remove-exists <repo> <backup_id>
<pathToConfigFile>
+ 3. restore remove-exists <repo/ws> <backup_set_path>
<pathToConfigFile>
+ 4. restore remove-exists <repo> <backup_set_path>
<pathToConfigFile>
+ 7. restore <repo/ws> <backup_id> <pathToConfigFile>
+ 8. restore <repo> <backup_id> <pathToConfigFile>
+ 9. restore <repo/ws> <backup_set_path> <pathToConfigFile>
+ 10. restore <repo> <backup_set_path> <pathToConfigFile>
+ */
+ System.out.println(client.restore(repositoryName, workspaceName, backupId,
new FileInputStream(conf),
+ backupSetPath, removeExists));
}
else
{
@@ -480,6 +584,42 @@
}
/**
+ * Check is "/repo" or "/repo/ws" parameter.
+ *
+ * @param parameter
+ * String, parameter.
+ * @return Boolean
+ * return "true" if it "/repo" or "/repo/ws"
parameter
+ */
+ private static boolean isRepoWS(String parameter)
+ {
+ String repWS = parameter;
+ repWS = repWS.replaceAll("\\\\", "/");
+
+ if ( !repWS.matches("[/][^/]+") &&
!repWS.matches("[/][^/]+[/][^/]+"))
+ {
+ return false;
+ }
+ else
+ {
+ return true;
+ }
+ }
+
+ /**
+ * Check is backip_id parameter.
+ *
+ * @param firstParameter
+ * String, parameter.
+ * @return Boolean
+ * return "true" if it backup identifier parameter
+ */
+ private static boolean isBackupId(String parameter)
+ {
+ return parameter.matches("[0-9abcdef]+") && parameter.length() ==
32;
+ }
+
+ /**
* getWorkspaceName.
*
* @param pathToWS
Modified:
jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/RepositoryServiceConfiguration.java
===================================================================
---
jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/RepositoryServiceConfiguration.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/RepositoryServiceConfiguration.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -43,6 +43,16 @@
public class RepositoryServiceConfiguration extends
AbstractRepositoryServiceConfiguration
{
+ public RepositoryServiceConfiguration()
+ {
+ }
+
+ public RepositoryServiceConfiguration(String defaultRepositoryName,
List<RepositoryEntry> repositoryEntries)
+ {
+ this.defaultRepositoryName = defaultRepositoryName;
+ this.repositoryConfigurations = repositoryEntries;
+ }
+
public final RepositoryEntry getRepositoryConfiguration(String name) throws
RepositoryConfigurationException
{
for (int i = 0; i < getRepositoryConfigurations().size(); i++)
Modified:
jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/config/RepositoryServiceConfigurationImpl.java
===================================================================
---
jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/config/RepositoryServiceConfigurationImpl.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/config/RepositoryServiceConfigurationImpl.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -71,7 +71,6 @@
public RepositoryServiceConfigurationImpl(InitParams params, ConfigurationManager
configurationService,
InitialContextInitializer initialContextInitializer) throws
RepositoryConfigurationException
{
-
param = params.getValueParam("conf-path");
if (params.getPropertiesParam("working-conf") != null)
Modified: jcr/trunk/exo.jcr.component.ext/pom.xml
===================================================================
--- jcr/trunk/exo.jcr.component.ext/pom.xml 2010-12-21 09:43:31 UTC (rev 3691)
+++ jcr/trunk/exo.jcr.component.ext/pom.xml 2010-12-21 10:51:58 UTC (rev 3692)
@@ -185,9 +185,12 @@
<include>**/replication/*.java</include>
<include>**/replication/external/*.java</include>
<include>**/replication/async/**/*.java</include>
+ <include>**/backup/TestBackupManager.java</include>
<include>**/backup/*.java</include>
+ <include>**/backup/server/*.java</include>
</includes>
<excludes>
+
<exclude>**/backup/TestRdbmsWorkspaceInitializer.java</exclude>
<exclude>**/BaseStandaloneTest.java</exclude>
<exclude>**/backup/AbstractBackupTestCase.java</exclude>
<exclude>**/backup/BaseRDBMSBackupTest.java</exclude>
Modified:
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/BackupChainLog.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/BackupChainLog.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/BackupChainLog.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -18,6 +18,29 @@
*/
package org.exoplatform.services.jcr.ext.backup;
+import org.exoplatform.commons.utils.PrivilegedFileHelper;
+import org.exoplatform.commons.utils.SecurityHelper;
+import org.exoplatform.services.jcr.config.RepositoryConfigurationException;
+import org.exoplatform.services.jcr.config.RepositoryEntry;
+import org.exoplatform.services.jcr.config.RepositoryServiceConfiguration;
+import org.exoplatform.services.jcr.config.WorkspaceEntry;
+import org.exoplatform.services.jcr.ext.backup.server.WorkspaceRestoreExeption;
+import org.exoplatform.services.jcr.impl.Constants;
+import org.exoplatform.services.jcr.impl.util.JCRDateFormat;
+import org.exoplatform.services.log.ExoLogger;
+import org.exoplatform.services.log.Log;
+import org.exoplatform.ws.frameworks.json.JsonHandler;
+import org.exoplatform.ws.frameworks.json.JsonParser;
+import org.exoplatform.ws.frameworks.json.impl.BeanBuilder;
+import org.exoplatform.ws.frameworks.json.impl.JsonDefaultHandler;
+import org.exoplatform.ws.frameworks.json.impl.JsonParserImpl;
+import org.exoplatform.ws.frameworks.json.value.JsonValue;
+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.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
@@ -35,6 +58,7 @@
import java.util.HashMap;
import java.util.List;
+import javax.jcr.RepositoryException;
import javax.jcr.ValueFormatException;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
@@ -44,22 +68,6 @@
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.events.StartElement;
-import org.exoplatform.commons.utils.PrivilegedFileHelper;
-import org.exoplatform.commons.utils.SecurityHelper;
-import org.exoplatform.services.jcr.config.WorkspaceEntry;
-import org.exoplatform.services.jcr.impl.Constants;
-import org.exoplatform.services.jcr.impl.util.JCRDateFormat;
-import org.exoplatform.services.log.ExoLogger;
-import org.exoplatform.services.log.Log;
-import org.exoplatform.ws.frameworks.json.JsonHandler;
-import org.exoplatform.ws.frameworks.json.JsonParser;
-import org.exoplatform.ws.frameworks.json.impl.BeanBuilder;
-import org.exoplatform.ws.frameworks.json.impl.JsonDefaultHandler;
-import org.exoplatform.ws.frameworks.json.impl.JsonException;
-import org.exoplatform.ws.frameworks.json.impl.JsonGeneratorImpl;
-import org.exoplatform.ws.frameworks.json.impl.JsonParserImpl;
-import org.exoplatform.ws.frameworks.json.value.JsonValue;
-
/**
* Created by The eXo Platform SARL .<br/>
*
@@ -129,13 +137,16 @@
* will be generate the exception BackupOperationException
*/
public BackupChainLog(File logDir, BackupConfig config, String fullBackupType, String
incrementalBackupType,
- String backupId, WorkspaceEntry wEntry, File rootDir) throws
BackupOperationException
+ String backupId, RepositoryServiceConfiguration
repositoryServiceConfiguration, File rootDir)
+ throws BackupOperationException
{
try
{
this.finalized = false;
this.versionLog = VERSION_LOG_1_1;
- this.log = new File(PrivilegedFileHelper.getCanonicalPath(logDir) +
File.separator + (PREFIX + backupId + SUFFIX));
+ this.log =
+ new File(PrivilegedFileHelper.getCanonicalPath(logDir) +
File.separator
+ + (PREFIX + backupId + SUFFIX));
PrivilegedFileHelper.createNewFile(this.log);
this.rootDir = rootDir;
this.backupId = backupId;
@@ -143,12 +154,13 @@
this.incrementalBackupType = incrementalBackupType;
this.config = config;
this.jobEntries = new ArrayList<JobEntryInfo>();
- this.originalWorkspaceEntry = wEntry;
+ this.originalWorkspaceEntry = getWorkspaceEntry(config,
repositoryServiceConfiguration);
+
// write config info here
logWriter = new LogWriter(log);
logWriter.write(config, fullBackupType, incrementalBackupType);
- logWriter.writeWorkspaceEntry(originalWorkspaceEntry);
+ logWriter.writeWorkspaceEntry(originalWorkspaceEntry,
repositoryServiceConfiguration);
}
catch (IOException e)
{
@@ -162,12 +174,53 @@
{
throw new BackupOperationException(e);
}
- catch (JsonException e)
+ catch (JiBXException e)
{
throw new BackupOperationException(e);
}
+ catch (RepositoryException e)
+ {
+ throw new BackupOperationException(e);
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ throw new BackupOperationException(e);
+ }
}
+ private WorkspaceEntry getWorkspaceEntry(BackupConfig config,
+ RepositoryServiceConfiguration repositoryServiceConfiguration) throws
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.
*
@@ -411,9 +464,9 @@
private List<JobEntryInfo> jobEntries;
private List<JobEntryInfo> jobEntriesNormalize;
-
+
private WorkspaceEntry originalWorkspaceEntry;
-
+
private String version;
private String iBackupType;
@@ -425,7 +478,8 @@
this.logFile = logFile;
jobEntries = new ArrayList<JobEntryInfo>();
- reader = XMLInputFactory.newInstance().createXMLStreamReader(
+ reader =
+ XMLInputFactory.newInstance().createXMLStreamReader(
PrivilegedFileHelper.fileInputStream(this.logFile),
Constants.DEFAULT_ENCODING);
}
@@ -512,10 +566,42 @@
private WorkspaceEntry readWorkspaceEntry() throws Exception
{
- String jsonRepositoryEntry = reader.getElementText();
+ String configName = readContent();
- return (WorkspaceEntry) (getObject(WorkspaceEntry.class, jsonRepositoryEntry
- .getBytes(Constants.DEFAULT_ENCODING)));
+ File configFile =
+ new
File(PrivilegedFileHelper.getCanonicalPath(getBackupConfig().getBackupDir()) +
File.separator
+ + configName);
+
+ if (!PrivilegedFileHelper.exists(configFile))
+ {
+ throw new WorkspaceRestoreExeption("The backup set is not contains
original workspace configuration : "
+ +
PrivilegedFileHelper.getCanonicalPath(getBackupConfig().getBackupDir()));
+ }
+
+ IBindingFactory factory =
BindingDirectory.getFactory(RepositoryServiceConfiguration.class);
+ IUnmarshallingContext uctx = factory.createUnmarshallingContext();
+ RepositoryServiceConfiguration conf =
+ (RepositoryServiceConfiguration)
uctx.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);
}
/**
@@ -566,7 +652,8 @@
if (version != null && version.equals(VERSION_LOG_1_1))
{
String path =
- readContent().replace("file:",
+ readContent().replace(
+ "file:",
"file:" +
PrivilegedFileHelper.getCanonicalPath(config.getBackupDir())
+ File.separator);
@@ -747,7 +834,8 @@
{
public XMLStreamWriter run() throws Exception
{
- return XMLOutputFactory.newInstance().createXMLStreamWriter(new
FileOutputStream(logFile), Constants.DEFAULT_ENCODING);
+ return XMLOutputFactory.newInstance().createXMLStreamWriter(new
FileOutputStream(logFile),
+ Constants.DEFAULT_ENCODING);
}
});
}
@@ -756,19 +844,19 @@
Throwable cause = pae.getCause();
if (cause instanceof FileNotFoundException)
{
- throw (FileNotFoundException)cause;
+ throw (FileNotFoundException) cause;
}
else if (cause instanceof XMLStreamException)
{
- throw (XMLStreamException)cause;
+ throw (XMLStreamException) cause;
}
else if (cause instanceof FactoryConfigurationError)
{
- throw (FactoryConfigurationError)cause;
+ throw (FactoryConfigurationError) cause;
}
else if (cause instanceof RuntimeException)
{
- throw (RuntimeException)cause;
+ throw (RuntimeException) cause;
}
else
{
@@ -778,21 +866,77 @@
writer.writeStartDocument();
writer.writeStartElement("backup-chain-log");
-
+
writer.writeStartElement("version-log");
writer.writeCharacters(versionLog);
writer.writeEndElement();
-
+
writer.flush();
}
- public void writeWorkspaceEntry(WorkspaceEntry originalWorkspaceEntry) throws
JsonException, XMLStreamException
+ public void writeWorkspaceEntry(WorkspaceEntry originalWorkspaceEntry,
+ RepositoryServiceConfiguration serviceConfiguration) throws
XMLStreamException, IOException,
+ JiBXException, RepositoryException, RepositoryConfigurationException
{
- JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
- JsonValue json = generatorImpl.createJsonObject(originalWorkspaceEntry);
+ File config =
+ new
File(PrivilegedFileHelper.getCanonicalPath(BackupChainLog.this.config.getBackupDir())
+ + File.separator +
"original-workspace-config.xml");
+ PrivilegedFileHelper.createNewFile(config);
+ OutputStream saveStream = PrivilegedFileHelper.fileOutputStream(config);
+ RepositoryEntry baseRepositoryEntry =
+
serviceConfiguration.getRepositoryConfiguration(BackupChainLog.this.config.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<RepositoryEntry> repositoryEntries = new
ArrayList<RepositoryEntry>();
+ repositoryEntries.add(repositoryEntry);
+
+ RepositoryServiceConfiguration newRepositoryServiceConfiguration =
+ new
RepositoryServiceConfiguration(serviceConfiguration.getDefaultRepositoryName(),
repositoryEntries);
+
+ IBindingFactory bfact;
+ try
+ {
+ bfact = SecurityHelper.doPriviledgedExceptionAction(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);
+ }
+ }
+ IMarshallingContext mctx = bfact.createMarshallingContext();
+
+ mctx.marshalDocument(newRepositoryServiceConfiguration, "ISO-8859-1",
null, saveStream);
+ saveStream.close();
+
writer.writeStartElement("original-workspace-config");
- writer.writeCData(json.toString());
+ writer.writeCharacters(config.getName());
writer.writeEndElement();
}
@@ -814,11 +958,9 @@
writer.writeStartElement("backup-dir");
String path =
(isRootBackupManagerDir(logFile) ?
PrivilegedFileHelper.getCanonicalPath(config.getBackupDir())
- :
PrivilegedFileHelper.getCanonicalPath(config.getBackupDir()).replace(
-
PrivilegedFileHelper.getCanonicalPath(logFile.getParentFile()), ""));
+ : ".");
-
- writer.writeCharacters(path.equals("") ? "." : path);
+ writer.writeCharacters(path);
writer.writeEndElement();
}
Modified:
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/ExtendedBackupManager.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/ExtendedBackupManager.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/ExtendedBackupManager.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -19,6 +19,8 @@
import org.exoplatform.services.jcr.config.RepositoryEntry;
import org.exoplatform.services.jcr.config.WorkspaceEntry;
+import java.io.File;
+
/**
* Created by The eXo Platform SAS.
*
@@ -170,4 +172,70 @@
*/
void restoreRepository(String repositoryBackupIdentifier, boolean asynchronous) throws
BackupOperationException,
BackupConfigurationException;
+
+ /**
+ * Restore existing workspace. Previous data will be deleted.
+ * For getting status of workspace restore can use
+ * BackupManager.getLastRestore(String repositoryName, String workspaceName) method
+ * WorkspaceEntry for restore should be contains in BackupChainLog.
+ *
+ * @param workspaceBackupSetDir
+ * the directory with backup set
+ * @param asynchronous
+ * if 'true' restore will be in asynchronous mode (i.e. in separated
thread)
+ * @throws BackupOperationException
+ * if backup operation exception occurred
+ * @throws BackupConfigurationException
+ * if configuration exception occurred
+ */
+ void restoreExistingWorkspace(File workspaceBackupSetDir, boolean asynchronous)
+ throws BackupOperationException, BackupConfigurationException;
+
+ /**
+ * Restore existing repository. Previous data will be deleted.
+ * For getting status of repository restore can use
+ * BackupManager.getLastRestore(String repositoryName) method.
+ * ReprositoryEntry for restore should be contains in BackupChainLog.
+ *
+ * @param repositoryBackupSetDir
+ * the directory with backup set
+ * @param asynchronous
+ * if 'true' restore will be in asynchronous mode (i.e. in separated
thread)
+ * @throws BackupOperationException
+ * if backup operation exception occurred
+ * @throws BackupConfigurationException
+ * if configuration exception occurred
+ */
+ void restoreExistingRepository(File repositoryBackupSetDir, boolean asynchronous)
+ throws BackupOperationException, BackupConfigurationException;
+
+ /**
+ * WorkspaceEntry for restore should be contains in BackupChainLog.
+ *
+ * @param workspaceBackupSetDir
+ * the directory with backup set
+ * @param asynchronous
+ * if 'true' restore will be in asynchronous mode (i.e. in separated
thread)
+ * @throws BackupOperationException
+ * if backup operation exception occurred
+ * @throws BackupConfigurationException
+ * if configuration exception occurred
+ */
+ void restoreWorkspace(File workspaceBackupSetDir, boolean asynchronous) throws
BackupOperationException,
+ BackupConfigurationException;
+
+ /**
+ * ReprositoryEntry for restore should be contains in BackupChainLog.
+ *
+ * @param repositoryBackupSetDir
+ * the directory with backup set
+ * @param asynchronous
+ * if 'true' restore will be in asynchronous mode (i.e. in separated
thread)
+ * @throws BackupOperationException
+ * if backup operation exception occurred
+ * @throws BackupConfigurationException
+ * if configuration exception occurred
+ */
+ void restoreRepository(File repositoryBackupSetDir, boolean asynchronous) throws
BackupOperationException,
+ BackupConfigurationException;
}
Modified:
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/RepositoryBackupChainLog.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/RepositoryBackupChainLog.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/RepositoryBackupChainLog.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -16,6 +16,27 @@
*/
package org.exoplatform.services.jcr.ext.backup;
+import org.exoplatform.commons.utils.PrivilegedFileHelper;
+import org.exoplatform.commons.utils.SecurityHelper;
+import org.exoplatform.services.jcr.config.RepositoryEntry;
+import org.exoplatform.services.jcr.config.RepositoryServiceConfiguration;
+import org.exoplatform.services.jcr.ext.backup.server.RepositoryRestoreExeption;
+import org.exoplatform.services.jcr.impl.Constants;
+import org.exoplatform.services.jcr.impl.util.JCRDateFormat;
+import org.exoplatform.services.log.ExoLogger;
+import org.exoplatform.services.log.Log;
+import org.exoplatform.ws.frameworks.json.JsonHandler;
+import org.exoplatform.ws.frameworks.json.JsonParser;
+import org.exoplatform.ws.frameworks.json.impl.BeanBuilder;
+import org.exoplatform.ws.frameworks.json.impl.JsonDefaultHandler;
+import org.exoplatform.ws.frameworks.json.impl.JsonParserImpl;
+import org.exoplatform.ws.frameworks.json.value.JsonValue;
+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.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
@@ -38,22 +59,6 @@
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.events.StartElement;
-import org.exoplatform.commons.utils.PrivilegedFileHelper;
-import org.exoplatform.commons.utils.SecurityHelper;
-import org.exoplatform.services.jcr.config.RepositoryEntry;
-import org.exoplatform.services.jcr.impl.Constants;
-import org.exoplatform.services.jcr.impl.util.JCRDateFormat;
-import org.exoplatform.services.log.ExoLogger;
-import org.exoplatform.services.log.Log;
-import org.exoplatform.ws.frameworks.json.JsonHandler;
-import org.exoplatform.ws.frameworks.json.JsonParser;
-import org.exoplatform.ws.frameworks.json.impl.BeanBuilder;
-import org.exoplatform.ws.frameworks.json.impl.JsonDefaultHandler;
-import org.exoplatform.ws.frameworks.json.impl.JsonException;
-import org.exoplatform.ws.frameworks.json.impl.JsonGeneratorImpl;
-import org.exoplatform.ws.frameworks.json.impl.JsonParserImpl;
-import org.exoplatform.ws.frameworks.json.value.JsonValue;
-
/**
* Created by The eXo Platform SAS.
*
@@ -216,14 +221,56 @@
}
}
- public synchronized void writeRepositoryEntry(RepositoryEntry rEntry) throws
JsonException, XMLStreamException
+ public synchronized void writeRepositoryEntry(RepositoryEntry rEntry,
+ RepositoryServiceConfiguration serviceConfiguration) throws
XMLStreamException, IOException,
+ JiBXException
{
-
- JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
- JsonValue json = generatorImpl.createJsonObject(rEntry);
-
+ File config =
+ new
File(PrivilegedFileHelper.getCanonicalPath(RepositoryBackupChainLog.this.config.getBackupDir())
+ + File.separator + "original-repository-config.xml");
+ PrivilegedFileHelper.createNewFile(config);
+ OutputStream saveStream = PrivilegedFileHelper.fileOutputStream(config);
+
+ ArrayList<RepositoryEntry> repositoryEntries = new
ArrayList<RepositoryEntry>();
+ repositoryEntries.add(rEntry);
+
+ RepositoryServiceConfiguration newRepositoryServiceConfiguration =
+ new
RepositoryServiceConfiguration(serviceConfiguration.getDefaultRepositoryName(),
repositoryEntries);
+
+ IBindingFactory bfact;
+ try
+ {
+ bfact = SecurityHelper.doPriviledgedExceptionAction(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);
+ }
+ }
+ IMarshallingContext mctx = bfact.createMarshallingContext();
+
+ mctx.marshalDocument(newRepositoryServiceConfiguration, "ISO-8859-1",
null, saveStream);
+ saveStream.close();
+
writer.writeStartElement("original-repository-config");
- writer.writeCData(json.toString());
+ writer.writeCharacters(config.getName());
writer.writeEndElement();
}
}
@@ -295,10 +342,42 @@
private RepositoryEntry readRepositoryEntry() throws UnsupportedEncodingException,
Exception
{
- String jsonRepositoryEntry = reader.getElementText();
+ String configName = readContent();
- return (RepositoryEntry) (getObject(RepositoryEntry.class, jsonRepositoryEntry
- .getBytes(Constants.DEFAULT_ENCODING)));
+ File configFile =
+ new
File(PrivilegedFileHelper.getCanonicalPath(getBackupConfig().getBackupDir()) +
File.separator
+ + configName);
+
+ if (!PrivilegedFileHelper.exists(configFile))
+ {
+ throw new RepositoryRestoreExeption("The backup set is not contains
original repositpry configuration : "
+ +
PrivilegedFileHelper.getCanonicalPath(getBackupConfig().getBackupDir()));
+ }
+
+ IBindingFactory factory =
BindingDirectory.getFactory(RepositoryServiceConfiguration.class);
+ IUnmarshallingContext uctx = factory.createUnmarshallingContext();
+ RepositoryServiceConfiguration conf =
+ (RepositoryServiceConfiguration)
uctx.unmarshalDocument(PrivilegedFileHelper
+ .fileInputStream(configFile), null);
+
+ if (conf.getRepositoryConfigurations().size() != 1)
+ {
+ throw new RepositoryRestoreExeption(
+ "The oririginal configuration should be contains only one
repository entry :"
+ + PrivilegedFileHelper.getCanonicalPath(configFile));
+ }
+
+ if
(!conf.getRepositoryConfiguration(getBackupConfig().getRepository()).getName().equals(getBackupConfig().getRepository()))
+ {
+ throw new RepositoryRestoreExeption(
+ "The oririginal configuration should be contains only one
repository entry with name \""
+ + getBackupConfig().getRepository() + "\"
:"
+ + PrivilegedFileHelper.getCanonicalPath(configFile));
+ }
+
+
+
+ return conf.getRepositoryConfiguration(getBackupConfig().getRepository());
}
/**
@@ -508,7 +587,7 @@
*/
public RepositoryBackupChainLog(File logDirectory, RepositoryBackupConfig config,
String fullBackupType,
String incrementalBackupType, String systemWorkspace, List<String>
wsLogFilePathList, String backupId,
- Calendar startTime, RepositoryEntry rEntry) throws BackupOperationException
+ Calendar startTime, RepositoryEntry rEntry, RepositoryServiceConfiguration
repositoryServiceConfiguration) throws BackupOperationException
{
try
{
@@ -529,7 +608,7 @@
logWriter.write(config, fullBackupType, incrementalBackupType);
logWriter.writeSystemWorkspaceName(systemWorkspace);
logWriter.writeBackupsPath(wsLogFilePathList, config);
- logWriter.writeRepositoryEntry(rEntry);
+ logWriter.writeRepositoryEntry(rEntry, repositoryServiceConfiguration);
this.workspaceBackupsInfo = wsLogFilePathList;
this.workspaceSystem = systemWorkspace;
@@ -546,7 +625,7 @@
{
throw new BackupOperationException("Can not create backup log ...",
e);
}
- catch (JsonException e)
+ catch (JiBXException e)
{
throw new BackupOperationException("Can not create backup log ...",
e);
}
Modified:
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/BackupChainImpl.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/BackupChainImpl.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/BackupChainImpl.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -18,18 +18,8 @@
*/
package org.exoplatform.services.jcr.ext.backup.impl;
-import java.io.File;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.Timer;
-import java.util.TimerTask;
-
-import org.exoplatform.services.jcr.config.WorkspaceEntry;
+import org.exoplatform.services.jcr.RepositoryService;
+import org.exoplatform.services.jcr.config.RepositoryConfigurationException;
import org.exoplatform.services.jcr.core.ManageableRepository;
import org.exoplatform.services.jcr.ext.backup.BackupChain;
import org.exoplatform.services.jcr.ext.backup.BackupChainLog;
@@ -42,6 +32,19 @@
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
+import java.io.File;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import javax.jcr.RepositoryException;
+
/**
* Created by The eXo Platform SARL .<br/>
*
@@ -74,19 +77,35 @@
private Set<BackupJobListener> listeners = new
LinkedHashSet<BackupJobListener>();
- public BackupChainImpl(BackupConfig config, File logDirectory, ManageableRepository
repository,
- String fullBackupType, String incrementalBackupType, String backupId, File
rootDir)
+ public BackupChainImpl(BackupConfig config, File logDirectory,
+ RepositoryService repositoryService,
+ String fullBackupType, String incrementalBackupType, String backupId, File
rootDir, Calendar startTime)
throws BackupOperationException,
BackupConfigurationException
{
this.config = config;
this.jobs = new ArrayList<BackupJob>();
+ this.timeStamp = startTime;
this.chainLog =
new BackupChainLog(logDirectory, config, fullBackupType,
incrementalBackupType, backupId,
- getWorkspaceEntry(config.getWorkspace(), repository), rootDir);
- this.timeStamp = Calendar.getInstance();
+ repositoryService.getConfig(), rootDir);
+
this.backupId = backupId;
+
+ ManageableRepository repository = null;
+ try
+ {
+ repository = repositoryService.getRepository(config.getRepository());
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ throw new BackupOperationException("Can not get repository \"" +
config.getRepository() + "\"", e);
+ }
+ catch (RepositoryException e)
+ {
+ throw new BackupOperationException("Can not get repository \"" +
config.getRepository() + "\"", e);
+ }
try
{
@@ -118,29 +137,6 @@
+ "_PeriodTimer_" + new
SimpleDateFormat("yyyyMMdd.HHmmss.SSS").format(new Date()), true);
}
- private WorkspaceEntry getWorkspaceEntry(String workspace, ManageableRepository
repository)
- throws BackupOperationException
- {
- WorkspaceEntry wEntry = null;
-
- for (WorkspaceEntry entry : repository.getConfiguration().getWorkspaceEntries())
- {
- if (entry.getName().equals(workspace))
- {
- wEntry = entry;
- break;
- }
- }
-
- if (wEntry == null)
- {
- throw new BackupOperationException("Worksapce \"" + workspace +
"\" was not exsisted in repository \""
- + repository.getConfiguration().getName() + "\".");
- }
-
- return wEntry;
- }
-
/**
* Add all listeners to a given job. Used in startBackup() which itself is
synchronized.
*
Modified:
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/BackupManagerImpl.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/BackupManagerImpl.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/BackupManagerImpl.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -1,2005 +1,2157 @@
-/*
- * 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.impl;
-
-import org.apache.commons.collections.map.HashedMap;
-import org.exoplatform.commons.utils.PrivilegedFileHelper;
-import org.exoplatform.commons.utils.PrivilegedSystemHelper;
-import org.exoplatform.commons.utils.SecurityHelper;
-import org.exoplatform.container.xml.InitParams;
-import org.exoplatform.container.xml.PropertiesParam;
-import org.exoplatform.services.jcr.RepositoryService;
-import org.exoplatform.services.jcr.config.RepositoryConfigurationException;
-import org.exoplatform.services.jcr.config.RepositoryEntry;
-import org.exoplatform.services.jcr.config.SimpleParameterEntry;
-import org.exoplatform.services.jcr.config.WorkspaceEntry;
-import org.exoplatform.services.jcr.config.WorkspaceInitializerEntry;
-import org.exoplatform.services.jcr.core.ManageableRepository;
-import org.exoplatform.services.jcr.core.WorkspaceContainerFacade;
-import org.exoplatform.services.jcr.dataflow.ChangesLogIterator;
-import org.exoplatform.services.jcr.dataflow.ItemState;
-import org.exoplatform.services.jcr.dataflow.PlainChangesLog;
-import org.exoplatform.services.jcr.dataflow.PlainChangesLogImpl;
-import org.exoplatform.services.jcr.dataflow.TransactionChangesLog;
-import org.exoplatform.services.jcr.datamodel.ItemData;
-import org.exoplatform.services.jcr.ext.backup.BackupChain;
-import org.exoplatform.services.jcr.ext.backup.BackupChainLog;
-import org.exoplatform.services.jcr.ext.backup.BackupConfig;
-import org.exoplatform.services.jcr.ext.backup.BackupConfigurationException;
-import org.exoplatform.services.jcr.ext.backup.BackupJob;
-import org.exoplatform.services.jcr.ext.backup.BackupJobListener;
-import org.exoplatform.services.jcr.ext.backup.BackupManager;
-import org.exoplatform.services.jcr.ext.backup.BackupOperationException;
-import org.exoplatform.services.jcr.ext.backup.ExtendedBackupManager;
-import org.exoplatform.services.jcr.ext.backup.JobEntryInfo;
-import org.exoplatform.services.jcr.ext.backup.RepositoryBackupChain;
-import org.exoplatform.services.jcr.ext.backup.RepositoryBackupChainLog;
-import org.exoplatform.services.jcr.ext.backup.RepositoryBackupConfig;
-import org.exoplatform.services.jcr.ext.backup.RepositoryRestoreExeption;
-import org.exoplatform.services.jcr.ext.backup.WorkspaceRestoreException;
-import org.exoplatform.services.jcr.ext.backup.impl.fs.FullBackupJob;
-import org.exoplatform.services.jcr.ext.backup.impl.rdbms.RdbmsWorkspaceInitializer;
-import org.exoplatform.services.jcr.ext.common.SessionProvider;
-import org.exoplatform.services.jcr.ext.registry.RegistryEntry;
-import org.exoplatform.services.jcr.ext.registry.RegistryService;
-import org.exoplatform.services.jcr.ext.replication.FixupStream;
-import org.exoplatform.services.jcr.impl.core.RepositoryImpl;
-import org.exoplatform.services.jcr.impl.core.SessionImpl;
-import org.exoplatform.services.jcr.impl.core.SysViewWorkspaceInitializer;
-import
org.exoplatform.services.jcr.impl.dataflow.persistent.WorkspacePersistentDataManager;
-import org.exoplatform.services.jcr.impl.storage.JCRInvalidItemStateException;
-import org.exoplatform.services.jcr.impl.storage.JCRItemExistsException;
-import org.exoplatform.services.jcr.impl.storage.jdbc.JDBCWorkspaceDataContainer;
-import org.exoplatform.services.jcr.impl.util.io.FileCleaner;
-import org.exoplatform.services.jcr.impl.util.io.SpoolFile;
-import org.exoplatform.services.jcr.observation.ExtendedEvent;
-import org.exoplatform.services.jcr.util.IdGenerator;
-import org.exoplatform.services.log.ExoLogger;
-import org.exoplatform.services.log.Log;
-import org.picocontainer.Startable;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.xml.sax.SAXException;
-
-import java.io.ByteArrayOutputStream;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.PrintWriter;
-import java.security.PrivilegedExceptionAction;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.jcr.PathNotFoundException;
-import javax.jcr.RepositoryException;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-/**
- * Created by The eXo Platform SAS .<br/>
- *
- * @author Gennady Azarenkov
- * @version $Id: $
- */
-
-public class BackupManagerImpl implements ExtendedBackupManager, Startable
-{
-
- protected static Log log =
ExoLogger.getLogger("exo.jcr.component.ext.BackupManagerImpl");
-
- /**
- * Name of default incremental job period parameter in configuration.
- */
- public final static String DEFAULT_INCREMENTAL_JOB_PERIOD =
"default-incremental-job-period";
-
- /**
- * Name of backup properties parameter in configuration.
- */
- public final static String BACKUP_PROPERTIES = "backup-properties";
-
- /**
- * Name of full backup type parameter in configuration.
- */
- public final static String FULL_BACKUP_TYPE = "full-backup-type";
-
- /**
- * Name of incremental backup type parameter in configuration.
- */
- public final static String INCREMENTAL_BACKUP_TYPE =
"incremental-backup-type";
-
- /**
- * Name of backup dir parameter in configuration.
- */
- public final static String BACKUP_DIR = "backup-dir";
-
- /**
- * Backup messages log max. size.
- */
- private static final int MESSAGES_MAXSIZE = 5;
-
- private static final String SERVICE_NAME = "BackupManager";
-
- /**
- * The timeout to checking finish of backup.
- */
- private static final long AUTO_STOPPER_TIMEOUT = 5000;
-
- /**
- * Value of default incremental job period.
- */
- private long defaultIncrementalJobPeriod;
-
- /**
- * Value of default incremental period.
- */
- private String defIncrPeriod;
-
- /**
- * Path to backup folder.
- */
- private String backupDir;
-
- /**
- * Value of full backup type.
- */
- private String fullBackupType;
-
- /**
- * Value of incremental backup type.
- */
- private String incrementalBackupType;
-
- /**
- * Set of current workspace backups.
- */
- private final Set<BackupChain> currentBackups;
-
- /**
- * Set of current repository backups.
- */
- private final Set<RepositoryBackupChain> currentRepositoryBackups;
-
- /**
- * The list of workspace restore job.
- */
- private List<JobWorkspaceRestore> restoreJobs;
-
- /**
- * The list of repository restore job.
- */
- private List<JobRepositoryRestore> restoreRepositoryJobs;
-
- /**
- * Initialization parameters of service.
- */
- private InitParams initParams;
-
- /**
- * Directory to log.
- */
- private File logsDirectory;
-
- private final RepositoryService repoService;
-
- private final RegistryService registryService;
-
- private FileCleaner fileCleaner;
-
- private BackupScheduler scheduler;
-
- private final BackupMessagesLog messages;
-
- private final MessagesListener messagesListener;
-
- private final WorkspaceBackupAutoStopper workspaceBackupStopper;
-
- private final RepositoryBackupAutoStopper repositoryBackupStopper;
-
- /**
- * Temporary directory;
- */
- private final File tempDir;
-
- class MessagesListener implements BackupJobListener
- {
-
- public void onError(BackupJob job, String message, Throwable error)
- {
- messages.addError(makeJobInfo(job, error) + message, error);
- log.error(makeJobInfo(job, error) + message, error);
- }
-
- public void onStateChanged(BackupJob job)
- {
- messages.addMessage(makeJobInfo(job, null));
- if (log.isDebugEnabled())
- log.debug(makeJobInfo(job, null));
- }
-
- private String makeJobInfo(BackupJob job, Throwable error)
- {
- String jobInfo = "";
-
- if (job != null)
- {
-
- switch (job.getType())
- {
- case BackupJob.FULL :
- jobInfo += "FULL BACKUP";
- break;
- case BackupJob.INCREMENTAL :
- jobInfo += "INCREMENTAL BACKUP";
- break;
- }
-
- jobInfo += " [";
- switch (job.getState())
- {
- case BackupJob.FINISHED :
- jobInfo += "FINISHED";
- break;
- case BackupJob.STARTING :
- jobInfo += "STARTING";
- break;
- case BackupJob.WAITING :
- jobInfo += "WAITING";
- break;
- case BackupJob.WORKING :
- jobInfo += "WORKING";
- break;
- }
-
- jobInfo += "]";
-
- if (error != null)
- jobInfo += " Error: " + error.getMessage();
-
- try
- {
- jobInfo += " log: " + job.getStorageURL().getPath();
- }
- catch (BackupOperationException e)
- {
- // skip URL
- }
- finally
- {
- jobInfo += " ";
- }
- }
-
- return jobInfo;
- }
-
- public String printStackTrace(Throwable error)
- {
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintWriter writer = new PrintWriter(out);
- error.printStackTrace(writer);
-
- return new String(out.toByteArray());
- }
- }
-
- class BackupLogsFilter implements FileFilter
- {
-
- public boolean accept(File pathname)
- {
- return pathname.getName().endsWith(".xml") &&
pathname.getName().startsWith(BackupChainLog.PREFIX);
- }
- }
-
- class RepositoryBackupLogsFilter implements FileFilter
- {
-
- public boolean accept(File pathname)
- {
- return pathname.getName().endsWith(".xml") &&
pathname.getName().startsWith(RepositoryBackupChainLog.PREFIX);
- }
- }
-
- class TaskFilter implements FileFilter
- {
-
- public boolean accept(File pathname)
- {
- return pathname.getName().endsWith(".task");
- }
- }
-
- class WorkspaceBackupAutoStopper extends Thread
- {
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void run()
- {
- while (true)
- {
- try
- {
- Thread.sleep(AUTO_STOPPER_TIMEOUT);
-
- Iterator<BackupChain> it = currentBackups.iterator();
- List<BackupChain> stopedList = new ArrayList<BackupChain>();
-
- while (it.hasNext())
- {
- BackupChain chain = it.next();
- boolean isFinished = (chain.getBackupJobs().get(0).getState() ==
BackupJob.FINISHED);
-
- for (int i = 1; i < chain.getBackupJobs().size(); i++)
- isFinished &= (chain.getBackupJobs().get(i).getState() ==
BackupJob.FINISHED);
-
- if (isFinished)
- {
- stopedList.add(chain);
- }
- }
-
- // STOP backups
- for (BackupChain chain : stopedList)
- stopBackup(chain);
- }
- catch (InterruptedException e)
- {
- log.error("The interapted this thread.", e);
- }
- catch (Throwable e)
- {
- log.error("The unknown error", e);
- }
- }
- }
- }
-
- class RepositoryBackupAutoStopper extends Thread
- {
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void run()
- {
- while (true)
- {
- try
- {
- Thread.sleep(AUTO_STOPPER_TIMEOUT);
-
- Iterator<RepositoryBackupChain> it =
currentRepositoryBackups.iterator();
- List<RepositoryBackupChain> stopedList = new
ArrayList<RepositoryBackupChain>();
-
- while (it.hasNext())
- {
- RepositoryBackupChain chain = it.next();
-
- if (chain.isFinished())
- {
- stopedList.add(chain);
- }
- }
-
- // STOP backups
- for (RepositoryBackupChain chain : stopedList)
- stopBackup(chain);
- }
- catch (InterruptedException e)
- {
- log.error("The interapted this thread.", e);
- }
- catch (Throwable e)
- {
- log.error("The unknown error", e);
- }
- }
- }
- }
-
- /**
- * BackupManagerImpl constructor.
- *
- * @param initParams
- * InitParams, the init parameters
- * @param repoService
- * RepositoryService, the repository service
- */
- public BackupManagerImpl(InitParams initParams, RepositoryService repoService)
- {
- this(initParams, repoService, null);
- }
-
- /**
- * BackupManagerImpl constructor.
- *
- * InitParams, the init parameters
- * @param repoService
- * RepositoryService, the repository service
- * @param registryService
- * RegistryService, the registry service
- */
- public BackupManagerImpl(InitParams initParams, RepositoryService repoService,
RegistryService registryService)
- {
-
- this.messagesListener = new MessagesListener();
- this.repoService = repoService;
- this.registryService = registryService;
- this.initParams = initParams;
- this.tempDir = new
File(PrivilegedSystemHelper.getProperty("java.io.tmpdir"));
-
- currentBackups = Collections.synchronizedSet(new HashSet<BackupChain>());
-
- currentRepositoryBackups = Collections.synchronizedSet(new
HashSet<RepositoryBackupChain>());
-
- fileCleaner = new FileCleaner(10000);
-
- messages = new BackupMessagesLog(MESSAGES_MAXSIZE);
-
- scheduler = new BackupScheduler(this, messages);
-
- this.restoreJobs = new ArrayList<JobWorkspaceRestore>();
- this.restoreRepositoryJobs = new ArrayList<JobRepositoryRestore>();
-
- this.workspaceBackupStopper = new WorkspaceBackupAutoStopper();
- this.workspaceBackupStopper.start();
-
- this.repositoryBackupStopper = new RepositoryBackupAutoStopper();
- this.repositoryBackupStopper.start();
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<BackupChain> getCurrentBackups()
- {
- return currentBackups;
- }
-
- /**
- * {@inheritDoc}
- */
- public BackupMessage[] getMessages()
- {
- return messages.getMessages();
- }
-
- /**
- * {@inheritDoc}
- */
- public BackupChainLog[] getBackupsLogs()
- {
- File[] cfs = PrivilegedFileHelper.listFiles(logsDirectory, new
BackupLogsFilter());
- List<BackupChainLog> logs = new ArrayList<BackupChainLog>();
- for (int i = 0; i < cfs.length; i++)
- {
- File cf = cfs[i];
-
- try
- {
- if (!isCurrentBackup(cf))
- logs.add(new BackupChainLog(cf));
- }
- catch (BackupOperationException e)
- {
- log.warn("Log file " + PrivilegedFileHelper.getAbsolutePath(cf) +
" is bussy or corrupted. Skipped. " + e,
- e);
- }
- }
- BackupChainLog[] ls = new BackupChainLog[logs.size()];
- logs.toArray(ls);
- return ls;
- }
-
- /**
- * {@inheritDoc}
- */
- public RepositoryBackupChainLog[] getRepositoryBackupsLogs()
- {
- File[] cfs = PrivilegedFileHelper.listFiles(logsDirectory, new
RepositoryBackupLogsFilter());
- List<RepositoryBackupChainLog> logs = new
ArrayList<RepositoryBackupChainLog>();
- for (int i = 0; i < cfs.length; i++)
- {
- File cf = cfs[i];
-
- try
- {
- if (!isCurrentRepositoryBackup(cf))
- logs.add(new RepositoryBackupChainLog(cf));
- }
- catch (BackupOperationException e)
- {
- log.warn("Log file " + PrivilegedFileHelper.getAbsolutePath(cf) +
" is bussy or corrupted. Skipped. " + e,
- e);
- }
- }
- RepositoryBackupChainLog[] ls = new RepositoryBackupChainLog[logs.size()];
- logs.toArray(ls);
- return ls;
- }
-
- /**
- * isCurrentBackup.
- *
- * @param log
- * File, the log to backup
- * @return boolean return the 'true' if this log is current backup.
- */
- private boolean isCurrentBackup(File log)
- {
- for (BackupChain chain : currentBackups)
- if (log.getName().equals(new File(chain.getLogFilePath()).getName()))
- return true;
-
- return false;
- }
-
- /**
- * isCurrentRepositoryBackup.
- *
- * @param log
- * File, the log to backup
- * @return boolean return the 'true' if this log is current backup.
- */
- private boolean isCurrentRepositoryBackup(File log)
- {
- for (RepositoryBackupChain chain : currentRepositoryBackups)
- if (log.getName().equals(new File(chain.getLogFilePath()).getName()))
- return true;
-
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Deprecated
- public void restore(BackupChainLog log, String repositoryName, WorkspaceEntry
workspaceEntry)
- throws BackupOperationException, RepositoryException,
RepositoryConfigurationException,
- BackupConfigurationException
- {
- List<JobEntryInfo> list = log.getJobEntryInfos();
- BackupConfig config = log.getBackupConfig();
-
- String reposytoryName = (repositoryName == null ? config.getRepository() :
repositoryName);
- String workspaceName = workspaceEntry.getName();
-
- // ws should be registered not created
- if (!workspaceAlreadyExist(reposytoryName, workspaceName))
- {
-
- for (int i = 0; i < list.size(); i++)
- {
- if (i == 0)
- {
- try
- {
- fullRestore(list.get(i).getURL().getPath(), reposytoryName,
workspaceName, workspaceEntry);
- }
- catch (FileNotFoundException e)
- {
- throw new BackupOperationException("Restore of full backup file
error " + e, e);
- }
- catch (IOException e)
- {
- throw new BackupOperationException("Restore of full backup file
I/O error " + e, e);
- }
- }
- else
- {
- // TODO do we not restoring same content few times, i.e. on STARTING,
WAITIG, FINISHED
- // events which are logged in chan log one after another
- try
- {
- incrementalRestore(list.get(i).getURL().getPath(), reposytoryName,
workspaceName);
- }
- catch (FileNotFoundException e)
- {
- throw new BackupOperationException("Restore of incremental backup
file error " + e, e);
- }
- catch (IOException e)
- {
- throw new BackupOperationException("Restore of incremental backup
file I/O error " + e, e);
- }
- catch (ClassNotFoundException e)
- {
- throw new BackupOperationException("Restore of incremental backup
error " + e, e);
- }
- }
- }
- }
- else
- throw new BackupConfigurationException("Workspace should exists " +
workspaceName);
- }
-
- protected void restoreOverInitializer(BackupChainLog log, String repositoryName,
WorkspaceEntry workspaceEntry)
- throws BackupOperationException, RepositoryException,
RepositoryConfigurationException,
- BackupConfigurationException
- {
-
- List<JobEntryInfo> list = log.getJobEntryInfos();
- BackupConfig config = log.getBackupConfig();
-
- String reposytoryName = (repositoryName == null ? config.getRepository() :
repositoryName);
- String workspaceName = workspaceEntry.getName();
-
- String fullbackupType = null;
-
- try
- {
- if ((Class.forName(log.getFullBackupType()).equals(FullBackupJob.class)))
- {
- fullbackupType = log.getFullBackupType();
- }
- else if ((Class.forName(log.getFullBackupType())
-
.equals(org.exoplatform.services.jcr.ext.backup.impl.rdbms.FullBackupJob.class)))
- {
- fullbackupType = log.getFullBackupType();
- }
- else
- {
- throw new BackupOperationException("Class \"" +
log.getFullBackupType() + "\" is not support as full backup.");
- }
- }
- catch (ClassNotFoundException e)
- {
- throw new BackupOperationException("Class \"" +
log.getFullBackupType() + "\" is not found." , e);
- }
-
- // ws should not exists.
- if (!workspaceAlreadyExist(reposytoryName, workspaceName))
- {
-
- for (int i = 0; i < list.size(); i++)
- {
- if (i == 0)
- {
- try
- {
- fullRestoreOverInitializer(list.get(i).getURL().getPath(),
reposytoryName, workspaceEntry,
- fullbackupType);
- }
- catch (FileNotFoundException e)
- {
- throw new BackupOperationException("Restore of full backup file
error " + e, e);
- }
- catch (IOException e)
- {
- throw new BackupOperationException("Restore of full backup file
I/O error " + e, e);
- }
- catch (ClassNotFoundException e)
- {
- throw new BackupOperationException("Restore of full backup class
load error " + e, e);
- }
-
- repoService.getConfig().retain(); // save configuration to persistence
(file or persister)
- }
- else
- {
- // TODO do we not restoring same content few times, i.e. on STARTING,
WAITIG, FINISHED
- // events which are logged in chan log one after another
- try
- {
- incrementalRestore(list.get(i).getURL().getPath(), reposytoryName,
workspaceName);
- }
- catch (FileNotFoundException e)
- {
- throw new BackupOperationException("Restore of incremental backup
file error " + e, e);
- }
- catch (IOException e)
- {
- throw new BackupOperationException("Restore of incremental backup
file I/O error " + e, e);
- }
- catch (ClassNotFoundException e)
- {
- throw new BackupOperationException("Restore of incremental backup
error " + e, e);
- }
- }
- }
- }
- else
- throw new BackupConfigurationException("Workspace \"" +
workspaceName + "\" should not exists.");
- }
-
- private boolean workspaceAlreadyExist(String repository, String workspace) throws
RepositoryException,
- RepositoryConfigurationException
- {
- String[] ws = repoService.getRepository(repository).getWorkspaceNames();
-
- for (int i = 0; i < ws.length; i++)
- if (ws[i].equals(workspace))
- return true;
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public BackupChain startBackup(BackupConfig config) throws BackupOperationException,
BackupConfigurationException,
- RepositoryException, RepositoryConfigurationException
- {
-
- return startBackup(config, null);
- }
-
- /**
- * Internally used for call with job listener from scheduler.
- *
- * @param config
- * @param jobListener
- * @return
- * @throws BackupOperationException
- * @throws BackupConfigurationException
- * @throws RepositoryException
- * @throws RepositoryConfigurationException
- */
- BackupChain startBackup(BackupConfig config, BackupJobListener jobListener) throws
BackupOperationException,
- BackupConfigurationException, RepositoryException,
RepositoryConfigurationException
- {
- validateBackupConfig(config);
-
- try
- {
- // check if it is RDBMS backup of single workspace in case of multi-db
configuration
- if ((Class.forName(fullBackupType)
-
.equals(org.exoplatform.services.jcr.ext.backup.impl.rdbms.FullBackupJob.class)))
- {
- WorkspaceEntry wEntry = null;
- for (WorkspaceEntry entry :
repoService.getRepository(config.getRepository()).getConfiguration()
- .getWorkspaceEntries())
- {
- if (entry.getName().equals(config.getWorkspace()))
- {
- wEntry = entry;
- break;
- }
- }
-
- if (wEntry == null)
- {
- throw new WorkspaceRestoreException("Workspace " +
config.getWorkspace()
- + " did not found in current repository " +
config.getRepository() + " configuration");
- }
-
- if
(Boolean.parseBoolean(wEntry.getContainer().getParameterValue(JDBCWorkspaceDataContainer.MULTIDB)))
- {
- throw new BackupOperationException(
- "Backup of single workspace in case of multi-db configuration is
not supported");
- }
- }
- }
- catch (ClassNotFoundException e)
- {
- throw new BackupOperationException("Class " + fullBackupType + "
is not found.", e);
- }
-
- BackupChain bchain =
- new BackupChainImpl(config, logsDirectory,
repoService.getRepository(config.getRepository()),
- fullBackupType, incrementalBackupType, IdGenerator.generate(),
logsDirectory);
-
- bchain.addListener(messagesListener);
- bchain.addListener(jobListener);
-
- currentBackups.add(bchain);
- bchain.startBackup();
-
- return bchain;
- }
-
- /**
- * Initialize backup chain to workspace backup.
- *
- * @param config
- * @return
- * @throws BackupOperationException
- * @throws BackupConfigurationException
- * @throws RepositoryException
- * @throws RepositoryConfigurationException
- */
- private void validateBackupConfig(RepositoryBackupConfig config) throws
BackupConfigurationException
- {
- if (config.getIncrementalJobPeriod() < 0)
- throw new BackupConfigurationException("The parameter 'incremental job
period' can not be negative.");
-
- if (config.getIncrementalJobNumber() < 0)
- throw new BackupConfigurationException("The parameter 'incremental job
number' can not be negative.");
-
- if (config.getIncrementalJobPeriod() == 0 && config.getBackupType() ==
BackupManager.FULL_AND_INCREMENTAL)
- config.setIncrementalJobPeriod(defaultIncrementalJobPeriod);
- }
-
- /**
- * {@inheritDoc}
- */
- public void stopBackup(BackupChain backup)
- {
- backup.stopBackup();
- currentBackups.remove(backup);
- }
-
- /**
- * {@inheritDoc}
- */
- public void start()
- {
- // start all scheduled before tasks
-
- if (registryService != null &&
!registryService.getForceXMLConfigurationValue(initParams))
- {
- SessionProvider sessionProvider = SessionProvider.createSystemProvider();
- try
- {
- readParamsFromRegistryService(sessionProvider);
- }
- catch (Exception e)
- {
- readParamsFromFile();
- try
- {
- writeParamsToRegistryService(sessionProvider);
- }
- catch (Exception exc)
- {
- log.error("Cannot write init configuration to RegistryService.",
exc);
- }
- }
- finally
- {
- sessionProvider.close();
- }
- }
- else
- {
- readParamsFromFile();
- }
-
- // scan for task files
- File[] tasks = PrivilegedFileHelper.listFiles(this.logsDirectory, new
TaskFilter());
- for (File task : tasks)
- {
- try
- {
- scheduler.restore(task);
- }
- catch (BackupSchedulerException e)
- {
- log.error("Can't restore backup scheduler task from file " +
PrivilegedFileHelper.getAbsolutePath(task), e);
- }
- catch (BackupOperationException e)
- {
- log.error("Can't restore backup scheduler task from file " +
PrivilegedFileHelper.getAbsolutePath(task), e);
- }
- catch (BackupConfigurationException e)
- {
- log.error("Can't restore backup scheduler task from file " +
PrivilegedFileHelper.getAbsolutePath(task), e);
- }
- catch (RepositoryException e)
- {
- log.error("Can't restore backup scheduler task from file " +
PrivilegedFileHelper.getAbsolutePath(task), e);
- }
- catch (RepositoryConfigurationException e)
- {
- log.error("Can't restore backup scheduler task from file " +
PrivilegedFileHelper.getAbsolutePath(task), e);
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void stop()
- {
- // 1. stop current backup chains
- // for (Iterator iterator = currentBackups.iterator(); iterator.hasNext();) {
- // BackupChain bc = (BackupChain) iterator.next();
- // stopBackup(bc);
- // }
- //
- // // 2. stop all scheduled tasks
- // scheduler = null;
- }
-
- @Deprecated
- private void fullRestore(String pathBackupFile, String repositoryName, String
workspaceName,
- WorkspaceEntry workspaceEntry) throws FileNotFoundException, IOException,
RepositoryException,
- RepositoryConfigurationException
- {
-
- RepositoryImpl defRep = (RepositoryImpl)repoService.getRepository(repositoryName);
-
- defRep.importWorkspace(workspaceEntry.getName(),
PrivilegedFileHelper.fileInputStream(pathBackupFile));
- }
-
- private void fullRestoreOverInitializer(String pathBackupFile, String repositoryName,
WorkspaceEntry workspaceEntry,
- String fBackupType) throws FileNotFoundException, IOException,
RepositoryException,
- RepositoryConfigurationException, ClassNotFoundException
- {
- WorkspaceInitializerEntry wieOriginal = workspaceEntry.getInitializer();
-
- RepositoryImpl defRep = (RepositoryImpl)repoService.getRepository(repositoryName);
-
- WorkspaceInitializerEntry wiEntry = new WorkspaceInitializerEntry();
-
- if ((Class.forName(fBackupType).equals(FullBackupJob.class)))
- {
- // set the initializer SysViewWorkspaceInitializer
- wiEntry.setType(SysViewWorkspaceInitializer.class.getCanonicalName());
-
- List<SimpleParameterEntry> wieParams = new
ArrayList<SimpleParameterEntry>();
- wieParams.add(new
SimpleParameterEntry(SysViewWorkspaceInitializer.RESTORE_PATH_PARAMETER,
pathBackupFile));
-
- wiEntry.setParameters(wieParams);
- }
- else if ((Class.forName(fBackupType)
-
.equals(org.exoplatform.services.jcr.ext.backup.impl.rdbms.FullBackupJob.class)))
- {
- // set the initializer RdbmsWorkspaceInitializer
- wiEntry.setType(RdbmsWorkspaceInitializer.class.getCanonicalName());
-
- List<SimpleParameterEntry> wieParams = new
ArrayList<SimpleParameterEntry>();
- wieParams.add(new
SimpleParameterEntry(RdbmsWorkspaceInitializer.RESTORE_PATH_PARAMETER, new File(
- pathBackupFile).getParent()));
-
- wiEntry.setParameters(wieParams);
- }
-
- workspaceEntry.setInitializer(wiEntry);
-
- //restore
- defRep.configWorkspace(workspaceEntry);
- defRep.createWorkspace(workspaceEntry.getName());
-
- //set original workspace initializer
- WorkspaceContainerFacade wcf =
defRep.getWorkspaceContainer(workspaceEntry.getName());
- WorkspaceEntry createdWorkspaceEntry =
(WorkspaceEntry)wcf.getComponent(WorkspaceEntry.class);
- createdWorkspaceEntry.setInitializer(wieOriginal);
- }
-
- private void incrementalRestore(String pathBackupFile, String repositoryName, String
workspaceName)
- throws RepositoryException, RepositoryConfigurationException,
BackupOperationException, FileNotFoundException,
- IOException, ClassNotFoundException
- {
- SessionImpl sesion =
(SessionImpl)repoService.getRepository(repositoryName).getSystemSession(workspaceName);
- WorkspacePersistentDataManager dataManager =
-
(WorkspacePersistentDataManager)sesion.getContainer().getComponentInstanceOfType(
- WorkspacePersistentDataManager.class);
-
- ObjectInputStream ois = null;
- File backupFile = null;
- try
- {
- backupFile = new File(pathBackupFile);
- ois = new ObjectInputStream(PrivilegedFileHelper.fileInputStream(backupFile));
-
- while (true)
- {
- TransactionChangesLog changesLog = readExternal(ois);
-
- ChangesLogIterator cli = changesLog.getLogIterator();
- while (cli.hasNextLog())
- {
- if (cli.nextLog().getEventType() == ExtendedEvent.LOCK)
- cli.removeLog();
- }
-
- saveChangesLog(dataManager, changesLog);
- }
- }
- catch (EOFException ioe)
- {
- // ok - reading all data from backup file;
- }
- finally
- {
- if (sesion != null)
- sesion.logout();
- }
- }
-
- private void saveChangesLog(WorkspacePersistentDataManager dataManager,
TransactionChangesLog changesLog)
- throws RepositoryException, BackupOperationException
- {
- try
- {
- dataManager.save(changesLog);
- }
- catch (JCRInvalidItemStateException e)
- {
- TransactionChangesLog normalizeChangesLog =
- getNormalizedChangesLog(e.getIdentifier(), e.getState(), changesLog);
- if (normalizeChangesLog != null)
- saveChangesLog(dataManager, normalizeChangesLog);
- else
- throw new BackupOperationException(
- "Collisions found during save of restore changes log, but caused item
is not found by ID "
- + e.getIdentifier() + ". " + e, e);
- }
- catch (JCRItemExistsException e)
- {
- TransactionChangesLog normalizeChangesLog =
- getNormalizedChangesLog(e.getIdentifier(), e.getState(), changesLog);
- if (normalizeChangesLog != null)
- saveChangesLog(dataManager, normalizeChangesLog);
- else
- throw new RepositoryException(
- "Collisions found during save of restore changes log, but caused item
is not found by ID "
- + e.getIdentifier() + ". " + e, e);
- }
-
- }
-
- private TransactionChangesLog getNormalizedChangesLog(String collisionID, int state,
TransactionChangesLog changesLog)
- {
- ItemState citem = changesLog.getItemState(collisionID);
-
- if (citem != null)
- {
-
- TransactionChangesLog result = new TransactionChangesLog();
- result.setSystemId(changesLog.getSystemId());
-
- ChangesLogIterator cli = changesLog.getLogIterator();
- while (cli.hasNextLog())
- {
- ArrayList<ItemState> normalized = new ArrayList<ItemState>();
- PlainChangesLog next = cli.nextLog();
- for (ItemState change : next.getAllStates())
- {
- if (state == change.getState())
- {
- ItemData item = change.getData();
- // targeted state
- if (citem.isNode())
- {
- // Node... by ID and desc path
- if (!item.getIdentifier().equals(collisionID)
- &&
!item.getQPath().isDescendantOf(citem.getData().getQPath()))
- normalized.add(change);
- }
- else if (!item.getIdentifier().equals(collisionID))
- {
- // Property... by ID
- normalized.add(change);
- }
- }
- else
- // another state
- normalized.add(change);
- }
-
- PlainChangesLog plog = new PlainChangesLogImpl(normalized,
next.getSessionId(), next.getEventType());
- result.addLog(plog);
- }
-
- return result;
- }
-
- return null;
- }
-
- private TransactionChangesLog readExternal(ObjectInputStream in) throws IOException,
ClassNotFoundException
- {
- int changesLogType = in.readInt();
-
- TransactionChangesLog transactionChangesLog = null;
-
- if (changesLogType == PendingChangesLog.Type.CHANGESLOG_WITH_STREAM)
- {
-
- // read ChangesLog
- transactionChangesLog = (TransactionChangesLog)in.readObject();
-
- // read FixupStream count
- int iFixupStream = in.readInt();
-
- ArrayList<FixupStream> listFixupStreams = new
ArrayList<FixupStream>();
-
- for (int i = 0; i < iFixupStream; i++)
- {
- FixupStream fs = new FixupStream();
- fs.readExternal(in);
- listFixupStreams.add(fs);
- }
- // listFixupStreams.add((FixupStream) in.readObject());
-
- // read stream data
- int iStreamCount = in.readInt();
- ArrayList<File> listFiles = new ArrayList<File>();
-
- for (int i = 0; i < iStreamCount; i++)
- {
-
- // read file size
- long fileSize = in.readLong();
-
- // read content file
- File contentFile = getAsFile(in, fileSize);
- listFiles.add(contentFile);
- }
-
- PendingChangesLog pendingChangesLog =
- new PendingChangesLog(transactionChangesLog, listFixupStreams, listFiles,
fileCleaner);
-
- pendingChangesLog.restore();
-
- TransactionChangesLog log = pendingChangesLog.getItemDataChangesLog();
-
- }
- else if (changesLogType == PendingChangesLog.Type.CHANGESLOG_WITHOUT_STREAM)
- {
- transactionChangesLog = (TransactionChangesLog)in.readObject();
- }
-
- return transactionChangesLog;
- }
-
- private File getAsFile(ObjectInputStream ois, long fileSize) throws IOException
- {
- int bufferSize = /* 8191 */1024 * 8;
- byte[] buf = new byte[bufferSize];
-
- File tempFile = SpoolFile.createTempFile("" + System.currentTimeMillis(),
".stmp", tempDir);
- FileOutputStream fos = PrivilegedFileHelper.fileOutputStream(tempFile);
- long readBytes = fileSize;
-
- while (readBytes > 0)
- {
- // long longTemp = readByte - bufferSize;
- if (readBytes >= bufferSize)
- {
- ois.readFully(buf);
- fos.write(buf);
- }
- else if (readBytes < bufferSize)
- {
- ois.readFully(buf, 0, (int)readBytes);
- fos.write(buf, 0, (int)readBytes);
- }
- readBytes -= bufferSize;
- }
-
- fos.flush();
- fos.close();
-
- return tempFile;
- }
-
- /**
- * Write parameters to RegistryService.
- *
- * @param sessionProvider
- * The SessionProvider
- * @throws ParserConfigurationException
- * @throws SAXException
- * @throws IOException
- * @throws RepositoryException
- */
- private void writeParamsToRegistryService(SessionProvider sessionProvider) throws
IOException, SAXException,
- ParserConfigurationException, RepositoryException
- {
- Document doc = SecurityHelper.doPriviledgedParserConfigurationAction(new
PrivilegedExceptionAction<Document>()
- {
- public Document run() throws Exception
- {
- return
DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
- }
- });
-
- Element root = doc.createElement(SERVICE_NAME);
- doc.appendChild(root);
-
- Element element = doc.createElement(BACKUP_PROPERTIES);
- setAttributeSmart(element, BACKUP_DIR, backupDir);
- setAttributeSmart(element, DEFAULT_INCREMENTAL_JOB_PERIOD, defIncrPeriod);
- setAttributeSmart(element, FULL_BACKUP_TYPE, fullBackupType);
- setAttributeSmart(element, INCREMENTAL_BACKUP_TYPE, incrementalBackupType);
- root.appendChild(element);
-
- RegistryEntry serviceEntry = new RegistryEntry(doc);
- registryService.createEntry(sessionProvider, RegistryService.EXO_SERVICES,
serviceEntry);
- }
-
- /**
- * Read parameters from RegistryService.
- *
- * @param sessionProvider
- * The SessionProvider
- * @throws RepositoryException
- * @throws PathNotFoundException
- */
- private void readParamsFromRegistryService(SessionProvider sessionProvider) throws
PathNotFoundException,
- RepositoryException
- {
- String entryPath = RegistryService.EXO_SERVICES + "/" + SERVICE_NAME +
"/" + BACKUP_PROPERTIES;
- RegistryEntry registryEntry = registryService.getEntry(sessionProvider,
entryPath);
- Document doc = registryEntry.getDocument();
- Element element = doc.getDocumentElement();
-
- backupDir = getAttributeSmart(element, BACKUP_DIR);
- defIncrPeriod = getAttributeSmart(element, DEFAULT_INCREMENTAL_JOB_PERIOD);
- fullBackupType = getAttributeSmart(element, FULL_BACKUP_TYPE);
- incrementalBackupType = getAttributeSmart(element, INCREMENTAL_BACKUP_TYPE);
-
- log.info("Backup dir from RegistryService: " + backupDir);
- log.info("Default incremental job period from RegistryService: " +
defIncrPeriod);
- log.info("Full backup type from RegistryService: " + fullBackupType);
- log.info("Incremental backup type from RegistryService: " +
incrementalBackupType);
-
- checkParams();
- }
-
- /**
- * Get attribute value.
- *
- * @param element
- * The element to get attribute value
- * @param attr
- * The attribute name
- * @return Value of attribute if present and null in other case
- */
- private String getAttributeSmart(Element element, String attr)
- {
- return element.hasAttribute(attr) ? element.getAttribute(attr) : null;
- }
-
- /**
- * Set attribute value. If value is null the attribute will be removed.
- *
- * @param element
- * The element to set attribute value
- * @param attr
- * The attribute name
- * @param value
- * The value of attribute
- */
- private void setAttributeSmart(Element element, String attr, String value)
- {
- if (value == null)
- {
- element.removeAttribute(attr);
- }
- else
- {
- element.setAttribute(attr, value);
- }
- }
-
- /**
- * Get parameters which passed from the file.
- *
- * @throws RepositoryConfigurationException
- */
- private void readParamsFromFile()
- {
- PropertiesParam pps = initParams.getPropertiesParam(BACKUP_PROPERTIES);
-
- backupDir = pps.getProperty(BACKUP_DIR);
- defIncrPeriod = pps.getProperty(DEFAULT_INCREMENTAL_JOB_PERIOD);
- fullBackupType = pps.getProperty(FULL_BACKUP_TYPE);
- incrementalBackupType = pps.getProperty(INCREMENTAL_BACKUP_TYPE);
-
- log.info("Backup dir from configuration file: " + backupDir);
- log.info("Default incremental job period from configuration file: " +
defIncrPeriod);
- log.info("Full backup type from configuration file: " + fullBackupType);
- log.info("Incremental backup type from configuration file: " +
incrementalBackupType);
-
- checkParams();
- }
-
- /**
- * Check read params and initialize.
- */
- private void checkParams()
- {
- if (backupDir == null)
- throw new RuntimeException(BACKUP_DIR + " not specified");
-
- logsDirectory = new File(backupDir);
- if (!PrivilegedFileHelper.exists(logsDirectory))
- PrivilegedFileHelper.mkdirs(logsDirectory);
-
- if (defIncrPeriod == null)
- throw new RuntimeException(DEFAULT_INCREMENTAL_JOB_PERIOD + " not
specified");
-
- defaultIncrementalJobPeriod = Integer.valueOf(defIncrPeriod);
-
- if (fullBackupType == null)
- throw new RuntimeException(FULL_BACKUP_TYPE + " not specified");
-
- if (incrementalBackupType == null)
- throw new RuntimeException(INCREMENTAL_BACKUP_TYPE + " not
specified");
- }
-
- /**
- * {@inheritDoc}
- */
- public BackupChain findBackup(String repository, String workspace)
- {
- Iterator<BackupChain> it = currentBackups.iterator();
- while (it.hasNext())
- {
- BackupChain chain = it.next();
- if (repository.equals(chain.getBackupConfig().getRepository())
- && workspace.equals(chain.getBackupConfig().getWorkspace()))
- return chain;
- }
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public BackupChain findBackup(String backupId)
- {
- Iterator<BackupChain> it = currentBackups.iterator();
- while (it.hasNext())
- {
- BackupChain chain = it.next();
- if (backupId.equals(chain.getBackupId()))
- return chain;
- }
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public BackupScheduler getScheduler()
- {
- return scheduler;
- }
-
- /**
- * getLogsDirectory.
- *
- * @return File
- * return the logs directory
- */
- File getLogsDirectory()
- {
- return logsDirectory;
- }
-
- /**
- * {@inheritDoc}
- */
- public File getBackupDirectory()
- {
- return getLogsDirectory();
- }
-
- /**
- * {@inheritDoc}
- */
- public String getFullBackupType()
- {
- return fullBackupType;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getIncrementalBackupType()
- {
- return incrementalBackupType;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getDefaultIncrementalJobPeriod()
- {
- return defaultIncrementalJobPeriod;
- }
-
- /**
- * {@inheritDoc}
- */
- public List<JobWorkspaceRestore> getRestores()
- {
- return restoreJobs;
- }
-
- /**
- * {@inheritDoc}
- */
- public JobWorkspaceRestore getLastRestore(String repositoryName, String
workspaceName)
- {
- for (int i = restoreJobs.size() - 1; i >= 0; i--)
- {
- JobWorkspaceRestore job = restoreJobs.get(i);
-
- if (repositoryName.equals(job.getRepositoryName()) &&
workspaceName.equals(job.getWorkspaceName()))
- {
- return job;
-
- }
- }
-
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public JobRepositoryRestore getLastRepositoryRestore(String repositoryName)
- {
-
- for (int i = restoreRepositoryJobs.size() - 1; i >= 0; i--)
- {
- JobRepositoryRestore job = restoreRepositoryJobs.get(i);
-
- if (repositoryName.equals(job.getRepositoryName()))
- {
- return job;
-
- }
- }
-
- return null;
- }
-
- public List<JobRepositoryRestore> getRepositoryRestores()
- {
- return restoreRepositoryJobs;
- }
-
- /**
- * {@inheritDoc}
- */
- public void restore(BackupChainLog log, String repositoryName, WorkspaceEntry
workspaceEntry, boolean asynchronous)
- throws BackupOperationException, BackupConfigurationException,
RepositoryException,
- RepositoryConfigurationException
- {
- if (asynchronous)
- {
- JobWorkspaceRestore jobRestore =
- new JobWorkspaceRestore(repoService, this, repositoryName, log,
workspaceEntry);
- restoreJobs.add(jobRestore);
- jobRestore.start();
- }
- else
- {
- this.restoreOverInitializer(log, repositoryName, workspaceEntry);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void restore(RepositoryBackupChainLog log, RepositoryEntry repositoryEntry,
boolean asynchronous)
- throws BackupOperationException, BackupConfigurationException,
RepositoryException,
- RepositoryConfigurationException
- {
- this.restore(log, repositoryEntry, null, asynchronous);
- }
-
- /**
- * {@inheritDoc}
- */
- public void restore(RepositoryBackupChainLog rblog, RepositoryEntry repositoryEntry,
- Map<String, String> workspaceNamesCorrespondMap, boolean asynchronous) throws
BackupOperationException,
- BackupConfigurationException, RepositoryException,
RepositoryConfigurationException
- {
- // Checking repository exists.
- try
- {
- repoService.getRepository(repositoryEntry.getName());
- throw new BackupConfigurationException("Repository \"" +
repositoryEntry.getName() + "\" is already exists.");
- }
- catch (RepositoryException e)
- {
- //OK. Repository with "repositoryEntry.getName" is not exists.
- }
-
- Map<String, BackupChainLog> workspacesMapping = new HashedMap();
-
- Map<String, BackupChainLog> backups = new HashedMap();
-
- if (workspaceNamesCorrespondMap == null)
- {
- for (String path : rblog.getWorkspaceBackupsInfo())
- {
- BackupChainLog bLog = new BackupChainLog(new File(path));
- backups.put(bLog.getBackupConfig().getWorkspace(), bLog);
- }
-
- if
(!rblog.getSystemWorkspace().equals(repositoryEntry.getSystemWorkspaceName()))
- {
- throw new BackupConfigurationException(
- "The backup to system workspace is not system workspace in repository
entry: "
- + rblog.getSystemWorkspace() + " is not equal " +
repositoryEntry.getSystemWorkspaceName());
- }
-
- if (backups.size() != repositoryEntry.getWorkspaceEntries().size())
- {
- throw new BackupConfigurationException(
- "The repository entry is contains more or less workspace entry than
backups of workspace in "
- + rblog.getLogFilePath());
- }
-
- for (WorkspaceEntry wsEntry : repositoryEntry.getWorkspaceEntries())
- {
- if (!backups.containsKey(wsEntry.getName()))
- {
- throw new BackupConfigurationException("The workspace '" +
wsEntry.getName()
- + "' is not found in backup " + rblog.getLogFilePath());
- }
- else
- {
- workspacesMapping.put(wsEntry.getName(), backups.get(wsEntry.getName()));
- }
- }
- }
- else
- {
- // Create map [new_ws_name : backupLog to that workspace].
- for (String path : rblog.getWorkspaceBackupsInfo())
- {
- BackupChainLog bLog = new BackupChainLog(new File(path));
-
- if
(!workspaceNamesCorrespondMap.containsKey(bLog.getBackupConfig().getWorkspace()))
- {
- throw new BackupConfigurationException("Can not found coresptonding
workspace name to workspace '"
- + bLog.getBackupConfig().getWorkspace() + "' in " +
workspaceNamesCorrespondMap.keySet());
- }
-
-
backups.put(workspaceNamesCorrespondMap.get(bLog.getBackupConfig().getWorkspace()),
bLog);
- }
-
- // Checking system workspace.
- if (!repositoryEntry.getSystemWorkspaceName().equals(
- workspaceNamesCorrespondMap.get(rblog.getSystemWorkspace())))
- {
- throw new BackupConfigurationException(
- "The backup to system workspace is not system workspace in repository
entry: "
- + repositoryEntry.getSystemWorkspaceName() + " is not equal
"
- + workspaceNamesCorrespondMap.get(rblog.getSystemWorkspace()));
- }
-
- // Checking count of corresponding workspaces.
- if (workspaceNamesCorrespondMap.size() !=
repositoryEntry.getWorkspaceEntries().size())
- {
- throw new BackupConfigurationException(
- "The repository entry is contains more or less workspace entry than
backups of workspace in "
- + rblog.getLogFilePath());
- }
-
- for (WorkspaceEntry wsEntry : repositoryEntry.getWorkspaceEntries())
- {
- if (!workspaceNamesCorrespondMap.containsValue(wsEntry.getName()))
- {
- throw new BackupConfigurationException("The workspace '" +
wsEntry.getName()
- + "' is not found workspaceNamesCorrespondMap : " +
workspaceNamesCorrespondMap.values());
- }
- else if (!backups.containsKey(wsEntry.getName()))
- {
- throw new BackupConfigurationException("The workspace '" +
wsEntry.getName()
- + "' is not found in backup " + rblog.getLogFilePath());
- }
- else
- {
- workspacesMapping.put(wsEntry.getName(), backups.get(wsEntry.getName()));
- }
- }
- }
-
- JobRepositoryRestore jobRepositoryRestore =
- new JobRepositoryRestore(repoService, this, repositoryEntry, workspacesMapping,
rblog);
-
- restoreRepositoryJobs.add(jobRepositoryRestore);
- if (asynchronous)
- {
- jobRepositoryRestore.start();
- }
- else
- {
- jobRepositoryRestore.restore();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public RepositoryBackupChain startBackup(RepositoryBackupConfig config) throws
BackupOperationException,
- BackupConfigurationException, RepositoryException,
RepositoryConfigurationException
- {
- validateBackupConfig(config);
-
- ManageableRepository repository =
repoService.getRepository(config.getRepository());
-
- File dir =
- new File(config.getBackupDir() + File.separator + "repository_" +
config.getRepository() + "_backup_"
- + System.currentTimeMillis());
- PrivilegedFileHelper.mkdirs(dir);
- config.setBackupDir(dir);
-
- RepositoryBackupChain repositoryBackupChain =
- new RepositoryBackupChainImpl(config, logsDirectory, repository, fullBackupType,
incrementalBackupType,
- IdGenerator.generate());
-
- repositoryBackupChain.startBackup();
-
- currentRepositoryBackups.add(repositoryBackupChain);
-
- return repositoryBackupChain;
- }
-
- /**
- * {@inheritDoc}
- */
- public void stopBackup(RepositoryBackupChain backup)
- {
- backup.stopBackup();
- currentRepositoryBackups.remove(backup);
- }
-
- /**
- * {@inheritDoc}
- */
- public RepositoryBackupChain findRepositoryBackup(String repository)
- {
- Iterator<RepositoryBackupChain> it = currentRepositoryBackups.iterator();
- while (it.hasNext())
- {
- RepositoryBackupChain chain = it.next();
- if (repository.equals(chain.getBackupConfig().getRepository()))
- return chain;
- }
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<RepositoryBackupChain> getCurrentRepositoryBackups()
- {
- return currentRepositoryBackups;
- }
-
- /**
- * {@inheritDoc}
- */
- public RepositoryBackupChain findRepositoryBackupId(String backupId)
- {
- Iterator<RepositoryBackupChain> it = currentRepositoryBackups.iterator();
- while (it.hasNext())
- {
- RepositoryBackupChain chain = it.next();
- if (backupId.equals(chain.getBackupId()))
- return chain;
- }
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void restoreExistingRepository(RepositoryBackupChainLog rblog, RepositoryEntry
repositoryEntry,
- boolean asynchronous) throws BackupOperationException,
BackupConfigurationException
- {
- try
- {
- // repository should be existed
- repoService.getRepository(repositoryEntry.getName());
- }
- catch (RepositoryException e)
- {
- throw new RepositoryRestoreExeption("Repository \"" +
repositoryEntry.getName() + "\" should be existed", e);
- }
- catch (RepositoryConfigurationException e)
- {
- throw new RepositoryRestoreExeption("Repository \"" +
repositoryEntry.getName() + "\" should be existed", e);
- }
-
- Map<String, BackupChainLog> workspacesMapping = new HashedMap();
-
- Map<String, BackupChainLog> backups = new HashedMap();
-
- for (String path : rblog.getWorkspaceBackupsInfo())
- {
- BackupChainLog bLog = new BackupChainLog(new File(path));
- backups.put(bLog.getBackupConfig().getWorkspace(), bLog);
- }
-
- if (!rblog.getSystemWorkspace().equals(repositoryEntry.getSystemWorkspaceName()))
- {
- throw new BackupConfigurationException(
- "The backup to system workspace is not system workspace in
repository entry: "
- + rblog.getSystemWorkspace() + " is not equal " +
repositoryEntry.getSystemWorkspaceName());
- }
-
- if (backups.size() != repositoryEntry.getWorkspaceEntries().size())
- {
- throw new BackupConfigurationException(
- "The repository entry is contains more or less workspace entry
than backups of workspace in "
- + rblog.getLogFilePath());
- }
-
- for (WorkspaceEntry wsEntry : repositoryEntry.getWorkspaceEntries())
- {
- if (!backups.containsKey(wsEntry.getName()))
- {
- throw new BackupConfigurationException("The workspace '" +
wsEntry.getName() + "' is not found in backup "
- + rblog.getLogFilePath());
- }
- else
- {
- workspacesMapping.put(wsEntry.getName(), backups.get(wsEntry.getName()));
- }
- }
-
- JobExistedRepositoryRestore jobExistedRepositoryRestore =
- new JobExistedRepositoryRestore(repoService, this, repositoryEntry,
workspacesMapping, rblog);
-
- restoreRepositoryJobs.add(jobExistedRepositoryRestore);
- if (asynchronous)
- {
- jobExistedRepositoryRestore.start();
- }
- else
- {
- jobExistedRepositoryRestore.restore();
- }
-
- }
-
- /**
- * {@inheritDoc}
- */
- public void restoreExistingRepository(String repositoryBackupIdentifier,
RepositoryEntry repositoryEntry,
- boolean asynchronous) throws BackupOperationException,
BackupConfigurationException
- {
- RepositoryBackupChainLog backupChainLog = null;
-
- for(RepositoryBackupChainLog chainLog : getRepositoryBackupsLogs())
- {
- if (chainLog.getBackupId().equals(repositoryBackupIdentifier))
- {
- backupChainLog = chainLog;
- break;
- }
- }
-
- if (backupChainLog == null)
- {
- throw new BackupConfigurationException("Can not founf backup of repository
with id \"" + repositoryBackupIdentifier + "\"");
- }
-
- this.restoreExistingRepository(backupChainLog, repositoryEntry, asynchronous);
- }
-
- /**
- * {@inheritDoc}
- */
- public void restoreExistingWorkspace(BackupChainLog log, String repositoryName,
WorkspaceEntry workspaceEntry,
- boolean asynchronous) throws BackupOperationException,
BackupConfigurationException
- {
- try
- {
- // repository should be existed
- repoService.getRepository(repositoryName);
-
- // workspace should be existed
- if (!workspaceAlreadyExist(repositoryName, workspaceEntry.getName()))
- {
- throw new WorkspaceRestoreException("Workspace \"" +
workspaceEntry.getName() + "\" should be existed in repository \"" +
repositoryName + "\".");
- }
- }
- catch (RepositoryException e)
- {
- throw new WorkspaceRestoreException("Repository \"" +
repositoryName + "\" should be existed", e);
- }
- catch (RepositoryConfigurationException e)
- {
- throw new WorkspaceRestoreException("Repository \"" +
repositoryName + "\" should be existed", e);
- }
-
- JobExistedWorkspaceRestore jobRestore =
- new JobExistedWorkspaceRestore(repoService, this, repositoryName, log,
workspaceEntry);
- restoreJobs.add(jobRestore);
-
- if (asynchronous)
- {
- jobRestore.start();
- }
- else
- {
- jobRestore.restore();
- }
-
- }
-
- /**
- * {@inheritDoc}
- */
- public void restoreExistingWorkspace(String workspaceBackupIdentifier, String
repositoryName,
- WorkspaceEntry workspaceEntry, boolean asynchronous) throws
BackupOperationException,
- BackupConfigurationException
- {
- BackupChainLog backupChainLog = null;
-
- for(BackupChainLog chainLog : getBackupsLogs())
- {
- if (chainLog.getBackupId().equals(workspaceBackupIdentifier))
- {
- backupChainLog = chainLog;
- break;
- }
- }
-
- if (backupChainLog == null)
- {
- throw new BackupConfigurationException("Can not founf backup of workspace
with id \"" + workspaceBackupIdentifier + "\"");
- }
-
- this.restoreExistingWorkspace(backupChainLog, repositoryName, workspaceEntry,
asynchronous);
- }
-
- /**
- * {@inheritDoc}
- */
- public void restoreExistingRepository(String repositoryBackupIdentifier, boolean
asynchronous)
- throws BackupOperationException, BackupConfigurationException
- {
- RepositoryBackupChainLog backupChainLog = null;
-
- for (RepositoryBackupChainLog chainLog : getRepositoryBackupsLogs())
- {
- if (chainLog.getBackupId().equals(repositoryBackupIdentifier))
- {
- backupChainLog = chainLog;
- break;
- }
- }
-
- if (backupChainLog == null)
- {
- throw new BackupConfigurationException("Can not founf backup of repository
with id \""
- + repositoryBackupIdentifier + "\"");
- }
-
- this.restoreExistingRepository(backupChainLog,
backupChainLog.getOriginalRepositoryEntry(), asynchronous);
-
- }
-
- /**
- * {@inheritDoc}
- */
- public void restoreExistingWorkspace(String workspaceBackupIdentifier, boolean
asynchronous)
- throws BackupOperationException, BackupConfigurationException
- {
- BackupChainLog backupChainLog = null;
-
- for (BackupChainLog chainLog : getBackupsLogs())
- {
- if (chainLog.getBackupId().equals(workspaceBackupIdentifier))
- {
- backupChainLog = chainLog;
- break;
- }
- }
-
- if (backupChainLog == null)
- {
- throw new BackupConfigurationException("Can not founf backup of workspace
with id \""
- + workspaceBackupIdentifier + "\"");
- }
-
- this.restoreExistingWorkspace(backupChainLog,
backupChainLog.getBackupConfig().getRepository(), backupChainLog
- .getOriginalWorkspaceEntry(), asynchronous);
-
- }
-
- /**
- * {@inheritDoc}
- */
- public void restoreRepository(String repositoryBackupIdentifier, boolean
asynchronous)
- throws BackupOperationException, BackupConfigurationException
- {
- RepositoryBackupChainLog backupChainLog = null;
-
- for (RepositoryBackupChainLog chainLog : getRepositoryBackupsLogs())
- {
- if (chainLog.getBackupId().equals(repositoryBackupIdentifier))
- {
- backupChainLog = chainLog;
- break;
- }
- }
-
- if (backupChainLog == null)
- {
- throw new BackupConfigurationException("Can not founf backup of repository
with id \""
- + repositoryBackupIdentifier + "\"");
- }
-
- try
- {
- this.restore(backupChainLog, backupChainLog.getOriginalRepositoryEntry(),
asynchronous);
- }
- catch (RepositoryException e)
- {
- throw new RepositoryRestoreExeption("Repository \"" +
backupChainLog.getOriginalRepositoryEntry().getName()
- + "\" was not restored", e);
- }
- catch (RepositoryConfigurationException e)
- {
- throw new RepositoryRestoreExeption("Repository \"" +
backupChainLog.getOriginalRepositoryEntry().getName()
- + "\" was not restored", e);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void restoreWorkspace(String workspaceBackupIdentifier, boolean asynchronous)
- throws BackupOperationException, BackupConfigurationException
- {
- BackupChainLog backupChainLog = null;
-
- for (BackupChainLog chainLog : getBackupsLogs())
- {
- if (chainLog.getBackupId().equals(workspaceBackupIdentifier))
- {
- backupChainLog = chainLog;
- break;
- }
- }
-
- if (backupChainLog == null)
- {
- throw new BackupConfigurationException("Can not founf backup of workspace
with id \""
- + workspaceBackupIdentifier + "\"");
- }
-
- try
- {
- this.restore(backupChainLog, backupChainLog.getBackupConfig().getRepository(),
backupChainLog
- .getOriginalWorkspaceEntry(), asynchronous);
- }
- catch (RepositoryException e)
- {
- throw new WorkspaceRestoreException("Workapce \"" +
backupChainLog.getOriginalWorkspaceEntry().getName()
- + "\" was not restored in repository \"" +
backupChainLog.getBackupConfig().getRepository() + "\"", e);
- }
- catch (RepositoryConfigurationException e)
- {
-
- throw new WorkspaceRestoreException("Workapce \"" +
backupChainLog.getOriginalWorkspaceEntry().getName()
- + "\" was not restored in repository \"" +
backupChainLog.getBackupConfig().getRepository() + "\"", e);
- }
-
- }
-
-}
+/*
+ * 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.impl;
+
+import org.apache.commons.collections.map.HashedMap;
+import org.exoplatform.commons.utils.PrivilegedFileHelper;
+import org.exoplatform.commons.utils.PrivilegedSystemHelper;
+import org.exoplatform.commons.utils.SecurityHelper;
+import org.exoplatform.container.xml.InitParams;
+import org.exoplatform.container.xml.PropertiesParam;
+import org.exoplatform.services.jcr.RepositoryService;
+import org.exoplatform.services.jcr.config.RepositoryConfigurationException;
+import org.exoplatform.services.jcr.config.RepositoryEntry;
+import org.exoplatform.services.jcr.config.SimpleParameterEntry;
+import org.exoplatform.services.jcr.config.WorkspaceEntry;
+import org.exoplatform.services.jcr.config.WorkspaceInitializerEntry;
+import org.exoplatform.services.jcr.core.WorkspaceContainerFacade;
+import org.exoplatform.services.jcr.dataflow.ChangesLogIterator;
+import org.exoplatform.services.jcr.dataflow.ItemState;
+import org.exoplatform.services.jcr.dataflow.PlainChangesLog;
+import org.exoplatform.services.jcr.dataflow.PlainChangesLogImpl;
+import org.exoplatform.services.jcr.dataflow.TransactionChangesLog;
+import org.exoplatform.services.jcr.datamodel.ItemData;
+import org.exoplatform.services.jcr.ext.backup.BackupChain;
+import org.exoplatform.services.jcr.ext.backup.BackupChainLog;
+import org.exoplatform.services.jcr.ext.backup.BackupConfig;
+import org.exoplatform.services.jcr.ext.backup.BackupConfigurationException;
+import org.exoplatform.services.jcr.ext.backup.BackupJob;
+import org.exoplatform.services.jcr.ext.backup.BackupJobListener;
+import org.exoplatform.services.jcr.ext.backup.BackupManager;
+import org.exoplatform.services.jcr.ext.backup.BackupOperationException;
+import org.exoplatform.services.jcr.ext.backup.ExtendedBackupManager;
+import org.exoplatform.services.jcr.ext.backup.JobEntryInfo;
+import org.exoplatform.services.jcr.ext.backup.RepositoryBackupChain;
+import org.exoplatform.services.jcr.ext.backup.RepositoryBackupChainLog;
+import org.exoplatform.services.jcr.ext.backup.RepositoryBackupConfig;
+import org.exoplatform.services.jcr.ext.backup.RepositoryRestoreExeption;
+import org.exoplatform.services.jcr.ext.backup.WorkspaceRestoreException;
+import org.exoplatform.services.jcr.ext.backup.impl.fs.FullBackupJob;
+import org.exoplatform.services.jcr.ext.backup.impl.rdbms.RdbmsWorkspaceInitializer;
+import org.exoplatform.services.jcr.ext.common.SessionProvider;
+import org.exoplatform.services.jcr.ext.registry.RegistryEntry;
+import org.exoplatform.services.jcr.ext.registry.RegistryService;
+import org.exoplatform.services.jcr.ext.replication.FixupStream;
+import org.exoplatform.services.jcr.impl.core.RepositoryImpl;
+import org.exoplatform.services.jcr.impl.core.SessionImpl;
+import org.exoplatform.services.jcr.impl.core.SysViewWorkspaceInitializer;
+import
org.exoplatform.services.jcr.impl.dataflow.persistent.WorkspacePersistentDataManager;
+import org.exoplatform.services.jcr.impl.storage.JCRInvalidItemStateException;
+import org.exoplatform.services.jcr.impl.storage.JCRItemExistsException;
+import org.exoplatform.services.jcr.impl.storage.jdbc.JDBCWorkspaceDataContainer;
+import org.exoplatform.services.jcr.impl.util.io.FileCleaner;
+import org.exoplatform.services.jcr.impl.util.io.SpoolFile;
+import org.exoplatform.services.jcr.observation.ExtendedEvent;
+import org.exoplatform.services.jcr.util.IdGenerator;
+import org.exoplatform.services.log.ExoLogger;
+import org.exoplatform.services.log.Log;
+import org.picocontainer.Startable;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
+
+import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.PrintWriter;
+import java.security.PrivilegedExceptionAction;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.jcr.PathNotFoundException;
+import javax.jcr.RepositoryException;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+/**
+ * Created by The eXo Platform SAS .<br/>
+ *
+ * @author Gennady Azarenkov
+ * @version $Id: $
+ */
+
+public class BackupManagerImpl implements ExtendedBackupManager, Startable
+{
+
+ protected static Log log =
ExoLogger.getLogger("exo.jcr.component.ext.BackupManagerImpl");
+
+ /**
+ * Name of default incremental job period parameter in configuration.
+ */
+ public final static String DEFAULT_INCREMENTAL_JOB_PERIOD =
"default-incremental-job-period";
+
+ /**
+ * Name of backup properties parameter in configuration.
+ */
+ public final static String BACKUP_PROPERTIES = "backup-properties";
+
+ /**
+ * Name of full backup type parameter in configuration.
+ */
+ public final static String FULL_BACKUP_TYPE = "full-backup-type";
+
+ /**
+ * Name of incremental backup type parameter in configuration.
+ */
+ public final static String INCREMENTAL_BACKUP_TYPE =
"incremental-backup-type";
+
+ /**
+ * Name of backup dir parameter in configuration.
+ */
+ public final static String BACKUP_DIR = "backup-dir";
+
+ /**
+ * Backup messages log max. size.
+ */
+ private static final int MESSAGES_MAXSIZE = 5;
+
+ private static final String SERVICE_NAME = "BackupManager";
+
+ /**
+ * The timeout to checking finish of backup.
+ */
+ private static final long AUTO_STOPPER_TIMEOUT = 5000;
+
+ /**
+ * Value of default incremental job period.
+ */
+ private long defaultIncrementalJobPeriod;
+
+ /**
+ * Value of default incremental period.
+ */
+ private String defIncrPeriod;
+
+ /**
+ * Path to backup folder.
+ */
+ private String backupDir;
+
+ /**
+ * Value of full backup type.
+ */
+ private String fullBackupType;
+
+ /**
+ * Value of incremental backup type.
+ */
+ private String incrementalBackupType;
+
+ /**
+ * Set of current workspace backups.
+ */
+ private final Set<BackupChain> currentBackups;
+
+ /**
+ * Set of current repository backups.
+ */
+ private final Set<RepositoryBackupChain> currentRepositoryBackups;
+
+ /**
+ * The list of workspace restore job.
+ */
+ private List<JobWorkspaceRestore> restoreJobs;
+
+ /**
+ * The list of repository restore job.
+ */
+ private List<JobRepositoryRestore> restoreRepositoryJobs;
+
+ /**
+ * Initialization parameters of service.
+ */
+ private InitParams initParams;
+
+ /**
+ * Directory to log.
+ */
+ private File logsDirectory;
+
+ private final RepositoryService repoService;
+
+ private final RegistryService registryService;
+
+ private FileCleaner fileCleaner;
+
+ private BackupScheduler scheduler;
+
+ private final BackupMessagesLog messages;
+
+ private final MessagesListener messagesListener;
+
+ private final WorkspaceBackupAutoStopper workspaceBackupStopper;
+
+ private final RepositoryBackupAutoStopper repositoryBackupStopper;
+
+ /**
+ * Temporary directory;
+ */
+ private final File tempDir;
+
+ class MessagesListener implements BackupJobListener
+ {
+
+ public void onError(BackupJob job, String message, Throwable error)
+ {
+ messages.addError(makeJobInfo(job, error) + message, error);
+ log.error(makeJobInfo(job, error) + message, error);
+ }
+
+ public void onStateChanged(BackupJob job)
+ {
+ messages.addMessage(makeJobInfo(job, null));
+ if (log.isDebugEnabled())
+ log.debug(makeJobInfo(job, null));
+ }
+
+ private String makeJobInfo(BackupJob job, Throwable error)
+ {
+ String jobInfo = "";
+
+ if (job != null)
+ {
+
+ switch (job.getType())
+ {
+ case BackupJob.FULL :
+ jobInfo += "FULL BACKUP";
+ break;
+ case BackupJob.INCREMENTAL :
+ jobInfo += "INCREMENTAL BACKUP";
+ break;
+ }
+
+ jobInfo += " [";
+ switch (job.getState())
+ {
+ case BackupJob.FINISHED :
+ jobInfo += "FINISHED";
+ break;
+ case BackupJob.STARTING :
+ jobInfo += "STARTING";
+ break;
+ case BackupJob.WAITING :
+ jobInfo += "WAITING";
+ break;
+ case BackupJob.WORKING :
+ jobInfo += "WORKING";
+ break;
+ }
+
+ jobInfo += "]";
+
+ if (error != null)
+ jobInfo += " Error: " + error.getMessage();
+
+ try
+ {
+ jobInfo += " log: " + job.getStorageURL().getPath();
+ }
+ catch (BackupOperationException e)
+ {
+ // skip URL
+ }
+ finally
+ {
+ jobInfo += " ";
+ }
+ }
+
+ return jobInfo;
+ }
+
+ public String printStackTrace(Throwable error)
+ {
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ PrintWriter writer = new PrintWriter(out);
+ error.printStackTrace(writer);
+
+ return new String(out.toByteArray());
+ }
+ }
+
+ class TaskFilter implements FileFilter
+ {
+
+ public boolean accept(File pathname)
+ {
+ return pathname.getName().endsWith(".task");
+ }
+ }
+
+ class WorkspaceBackupAutoStopper extends Thread
+ {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void run()
+ {
+ while (true)
+ {
+ try
+ {
+ Thread.sleep(AUTO_STOPPER_TIMEOUT);
+
+ Iterator<BackupChain> it = currentBackups.iterator();
+ List<BackupChain> stopedList = new ArrayList<BackupChain>();
+
+ while (it.hasNext())
+ {
+ BackupChain chain = it.next();
+ boolean isFinished = (chain.getBackupJobs().get(0).getState() ==
BackupJob.FINISHED);
+
+ for (int i = 1; i < chain.getBackupJobs().size(); i++)
+ isFinished &= (chain.getBackupJobs().get(i).getState() ==
BackupJob.FINISHED);
+
+ if (isFinished)
+ {
+ stopedList.add(chain);
+ }
+ }
+
+ // STOP backups
+ for (BackupChain chain : stopedList)
+ stopBackup(chain);
+ }
+ catch (InterruptedException e)
+ {
+ log.error("The interapted this thread.", e);
+ }
+ catch (Throwable e)
+ {
+ log.error("The unknown error", e);
+ }
+ }
+ }
+ }
+
+ class RepositoryBackupAutoStopper extends Thread
+ {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void run()
+ {
+ while (true)
+ {
+ try
+ {
+ Thread.sleep(AUTO_STOPPER_TIMEOUT);
+
+ Iterator<RepositoryBackupChain> it =
currentRepositoryBackups.iterator();
+ List<RepositoryBackupChain> stopedList = new
ArrayList<RepositoryBackupChain>();
+
+ while (it.hasNext())
+ {
+ RepositoryBackupChain chain = it.next();
+
+ if (chain.isFinished())
+ {
+ stopedList.add(chain);
+ }
+ }
+
+ // STOP backups
+ for (RepositoryBackupChain chain : stopedList)
+ stopBackup(chain);
+ }
+ catch (InterruptedException e)
+ {
+ log.error("The interapted this thread.", e);
+ }
+ catch (Throwable e)
+ {
+ log.error("The unknown error", e);
+ }
+ }
+ }
+ }
+
+ /**
+ * BackupManagerImpl constructor.
+ *
+ * @param initParams
+ * InitParams, the init parameters
+ * @param repoService
+ * RepositoryService, the repository service
+ */
+ public BackupManagerImpl(InitParams initParams, RepositoryService repoService)
+ {
+ this(initParams, repoService, null);
+ }
+
+ /**
+ * BackupManagerImpl constructor.
+ *
+ * InitParams, the init parameters
+ * @param repoService
+ * RepositoryService, the repository service
+ * @param registryService
+ * RegistryService, the registry service
+ */
+ public BackupManagerImpl(InitParams initParams, RepositoryService repoService,
RegistryService registryService)
+ {
+
+ this.messagesListener = new MessagesListener();
+ this.repoService = repoService;
+ this.registryService = registryService;
+ this.initParams = initParams;
+ this.tempDir = new
File(PrivilegedSystemHelper.getProperty("java.io.tmpdir"));
+
+ currentBackups = Collections.synchronizedSet(new HashSet<BackupChain>());
+
+ currentRepositoryBackups = Collections.synchronizedSet(new
HashSet<RepositoryBackupChain>());
+
+ fileCleaner = new FileCleaner(10000);
+
+ messages = new BackupMessagesLog(MESSAGES_MAXSIZE);
+
+ scheduler = new BackupScheduler(this, messages);
+
+ this.restoreJobs = new ArrayList<JobWorkspaceRestore>();
+ this.restoreRepositoryJobs = new ArrayList<JobRepositoryRestore>();
+
+ this.workspaceBackupStopper = new WorkspaceBackupAutoStopper();
+ this.workspaceBackupStopper.start();
+
+ this.repositoryBackupStopper = new RepositoryBackupAutoStopper();
+ this.repositoryBackupStopper.start();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<BackupChain> getCurrentBackups()
+ {
+ return currentBackups;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public BackupMessage[] getMessages()
+ {
+ return messages.getMessages();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public BackupChainLog[] getBackupsLogs()
+ {
+ File[] cfs = PrivilegedFileHelper.listFiles(logsDirectory, new
BackupLogsFilter());
+ List<BackupChainLog> logs = new ArrayList<BackupChainLog>();
+ for (int i = 0; i < cfs.length; i++)
+ {
+ File cf = cfs[i];
+
+ try
+ {
+ if (!isCurrentBackup(cf))
+ logs.add(new BackupChainLog(cf));
+ }
+ catch (BackupOperationException e)
+ {
+ log.warn("Log file " + PrivilegedFileHelper.getAbsolutePath(cf) +
" is bussy or corrupted. Skipped. " + e,
+ e);
+ }
+ }
+ BackupChainLog[] ls = new BackupChainLog[logs.size()];
+ logs.toArray(ls);
+ return ls;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public RepositoryBackupChainLog[] getRepositoryBackupsLogs()
+ {
+ File[] cfs = PrivilegedFileHelper.listFiles(logsDirectory, new
RepositoryBackupLogsFilter());
+ List<RepositoryBackupChainLog> logs = new
ArrayList<RepositoryBackupChainLog>();
+ for (int i = 0; i < cfs.length; i++)
+ {
+ File cf = cfs[i];
+
+ try
+ {
+ if (!isCurrentRepositoryBackup(cf))
+ logs.add(new RepositoryBackupChainLog(cf));
+ }
+ catch (BackupOperationException e)
+ {
+ log.warn("Log file " + PrivilegedFileHelper.getAbsolutePath(cf) +
" is bussy or corrupted. Skipped. " + e,
+ e);
+ }
+ }
+ RepositoryBackupChainLog[] ls = new RepositoryBackupChainLog[logs.size()];
+ logs.toArray(ls);
+ return ls;
+ }
+
+ /**
+ * isCurrentBackup.
+ *
+ * @param log
+ * File, the log to backup
+ * @return boolean return the 'true' if this log is current backup.
+ */
+ private boolean isCurrentBackup(File log)
+ {
+ for (BackupChain chain : currentBackups)
+ if (log.getName().equals(new File(chain.getLogFilePath()).getName()))
+ return true;
+
+ return false;
+ }
+
+ /**
+ * isCurrentRepositoryBackup.
+ *
+ * @param log
+ * File, the log to backup
+ * @return boolean return the 'true' if this log is current backup.
+ */
+ private boolean isCurrentRepositoryBackup(File log)
+ {
+ for (RepositoryBackupChain chain : currentRepositoryBackups)
+ if (log.getName().equals(new File(chain.getLogFilePath()).getName()))
+ return true;
+
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Deprecated
+ public void restore(BackupChainLog log, String repositoryName, WorkspaceEntry
workspaceEntry)
+ throws BackupOperationException, RepositoryException,
RepositoryConfigurationException,
+ BackupConfigurationException
+ {
+ List<JobEntryInfo> list = log.getJobEntryInfos();
+ BackupConfig config = log.getBackupConfig();
+
+ String reposytoryName = (repositoryName == null ? config.getRepository() :
repositoryName);
+ String workspaceName = workspaceEntry.getName();
+
+ // ws should be registered not created
+ if (!workspaceAlreadyExist(reposytoryName, workspaceName))
+ {
+
+ for (int i = 0; i < list.size(); i++)
+ {
+ if (i == 0)
+ {
+ try
+ {
+ fullRestore(list.get(i).getURL().getPath(), reposytoryName,
workspaceName, workspaceEntry);
+ }
+ catch (FileNotFoundException e)
+ {
+ throw new BackupOperationException("Restore of full backup file
error " + e, e);
+ }
+ catch (IOException e)
+ {
+ throw new BackupOperationException("Restore of full backup file
I/O error " + e, e);
+ }
+ }
+ else
+ {
+ // TODO do we not restoring same content few times, i.e. on STARTING,
WAITIG, FINISHED
+ // events which are logged in chan log one after another
+ try
+ {
+ incrementalRestore(list.get(i).getURL().getPath(), reposytoryName,
workspaceName);
+ }
+ catch (FileNotFoundException e)
+ {
+ throw new BackupOperationException("Restore of incremental backup
file error " + e, e);
+ }
+ catch (IOException e)
+ {
+ throw new BackupOperationException("Restore of incremental backup
file I/O error " + e, e);
+ }
+ catch (ClassNotFoundException e)
+ {
+ throw new BackupOperationException("Restore of incremental backup
error " + e, e);
+ }
+ }
+ }
+ }
+ else
+ throw new BackupConfigurationException("Workspace should exists " +
workspaceName);
+ }
+
+ protected void restoreOverInitializer(BackupChainLog log, String repositoryName,
WorkspaceEntry workspaceEntry)
+ throws BackupOperationException, RepositoryException,
RepositoryConfigurationException,
+ BackupConfigurationException
+ {
+
+ List<JobEntryInfo> list = log.getJobEntryInfos();
+ BackupConfig config = log.getBackupConfig();
+
+ String reposytoryName = (repositoryName == null ? config.getRepository() :
repositoryName);
+ String workspaceName = workspaceEntry.getName();
+
+ String fullbackupType = null;
+
+ try
+ {
+ if ((Class.forName(log.getFullBackupType()).equals(FullBackupJob.class)))
+ {
+ fullbackupType = log.getFullBackupType();
+ }
+ else if ((Class.forName(log.getFullBackupType())
+
.equals(org.exoplatform.services.jcr.ext.backup.impl.rdbms.FullBackupJob.class)))
+ {
+ fullbackupType = log.getFullBackupType();
+ }
+ else
+ {
+ throw new BackupOperationException("Class \"" +
log.getFullBackupType() + "\" is not support as full backup.");
+ }
+ }
+ catch (ClassNotFoundException e)
+ {
+ throw new BackupOperationException("Class \"" +
log.getFullBackupType() + "\" is not found." , e);
+ }
+
+ // ws should not exists.
+ if (!workspaceAlreadyExist(reposytoryName, workspaceName))
+ {
+
+ for (int i = 0; i < list.size(); i++)
+ {
+ if (i == 0)
+ {
+ try
+ {
+ fullRestoreOverInitializer(list.get(i).getURL().getPath(),
reposytoryName, workspaceEntry,
+ fullbackupType);
+ }
+ catch (FileNotFoundException e)
+ {
+ throw new BackupOperationException("Restore of full backup file
error " + e, e);
+ }
+ catch (IOException e)
+ {
+ throw new BackupOperationException("Restore of full backup file
I/O error " + e, e);
+ }
+ catch (ClassNotFoundException e)
+ {
+ throw new BackupOperationException("Restore of full backup class
load error " + e, e);
+ }
+
+ repoService.getConfig().retain(); // save configuration to persistence
(file or persister)
+ }
+ else
+ {
+ // TODO do we not restoring same content few times, i.e. on STARTING,
WAITIG, FINISHED
+ // events which are logged in chan log one after another
+ try
+ {
+ incrementalRestore(list.get(i).getURL().getPath(), reposytoryName,
workspaceName);
+ }
+ catch (FileNotFoundException e)
+ {
+ throw new BackupOperationException("Restore of incremental backup
file error " + e, e);
+ }
+ catch (IOException e)
+ {
+ throw new BackupOperationException("Restore of incremental backup
file I/O error " + e, e);
+ }
+ catch (ClassNotFoundException e)
+ {
+ throw new BackupOperationException("Restore of incremental backup
error " + e, e);
+ }
+ }
+ }
+ }
+ else
+ throw new BackupConfigurationException("Workspace \"" +
workspaceName + "\" should not exists.");
+ }
+
+ private boolean workspaceAlreadyExist(String repository, String workspace) throws
RepositoryException,
+ RepositoryConfigurationException
+ {
+ String[] ws = repoService.getRepository(repository).getWorkspaceNames();
+
+ for (int i = 0; i < ws.length; i++)
+ if (ws[i].equals(workspace))
+ return true;
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public BackupChain startBackup(BackupConfig config) throws BackupOperationException,
BackupConfigurationException,
+ RepositoryException, RepositoryConfigurationException
+ {
+
+ return startBackup(config, null);
+ }
+
+ /**
+ * Internally used for call with job listener from scheduler.
+ *
+ * @param config
+ * @param jobListener
+ * @return
+ * @throws BackupOperationException
+ * @throws BackupConfigurationException
+ * @throws RepositoryException
+ * @throws RepositoryConfigurationException
+ */
+ BackupChain startBackup(BackupConfig config, BackupJobListener jobListener) throws
BackupOperationException,
+ BackupConfigurationException, RepositoryException,
RepositoryConfigurationException
+ {
+ validateBackupConfig(config);
+
+ Calendar startTime = Calendar.getInstance();
+ File dir =
+ FileNameProducer.generateBackupSetDir(config.getRepository(),
config.getWorkspace(), config
+ .getBackupDir().getPath(), startTime);
+ PrivilegedFileHelper.mkdirs(dir);
+ config.setBackupDir(dir);
+
+ try
+ {
+ // check if it is RDBMS backup of single workspace in case of multi-db
configuration
+ if ((Class.forName(fullBackupType)
+
.equals(org.exoplatform.services.jcr.ext.backup.impl.rdbms.FullBackupJob.class)))
+ {
+ WorkspaceEntry wEntry = null;
+ for (WorkspaceEntry entry :
repoService.getRepository(config.getRepository()).getConfiguration()
+ .getWorkspaceEntries())
+ {
+ if (entry.getName().equals(config.getWorkspace()))
+ {
+ wEntry = entry;
+ break;
+ }
+ }
+
+ if (wEntry == null)
+ {
+ throw new WorkspaceRestoreException("Workspace " +
config.getWorkspace()
+ + " did not found in current repository " +
config.getRepository() + " configuration");
+ }
+
+ if
(Boolean.parseBoolean(wEntry.getContainer().getParameterValue(JDBCWorkspaceDataContainer.MULTIDB)))
+ {
+ throw new BackupOperationException(
+ "Backup of single workspace in case of multi-db configuration is
not supported");
+ }
+ }
+ }
+ catch (ClassNotFoundException e)
+ {
+ throw new BackupOperationException("Class " + fullBackupType + "
is not found.", e);
+ }
+
+ BackupChain bchain =
+ new BackupChainImpl(config, logsDirectory, repoService,
+ fullBackupType, incrementalBackupType, IdGenerator.generate(),
logsDirectory, startTime);
+
+ bchain.addListener(messagesListener);
+ bchain.addListener(jobListener);
+
+ currentBackups.add(bchain);
+ bchain.startBackup();
+
+ return bchain;
+ }
+
+ /**
+ * Initialize backup chain to workspace backup.
+ *
+ * @param config
+ * @return
+ * @throws BackupOperationException
+ * @throws BackupConfigurationException
+ * @throws RepositoryException
+ * @throws RepositoryConfigurationException
+ */
+ private void validateBackupConfig(RepositoryBackupConfig config) throws
BackupConfigurationException
+ {
+ if (config.getIncrementalJobPeriod() < 0)
+ throw new BackupConfigurationException("The parameter 'incremental job
period' can not be negative.");
+
+ if (config.getIncrementalJobNumber() < 0)
+ throw new BackupConfigurationException("The parameter 'incremental job
number' can not be negative.");
+
+ if (config.getIncrementalJobPeriod() == 0 && config.getBackupType() ==
BackupManager.FULL_AND_INCREMENTAL)
+ config.setIncrementalJobPeriod(defaultIncrementalJobPeriod);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void stopBackup(BackupChain backup)
+ {
+ backup.stopBackup();
+ currentBackups.remove(backup);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void start()
+ {
+ // start all scheduled before tasks
+
+ if (registryService != null &&
!registryService.getForceXMLConfigurationValue(initParams))
+ {
+ SessionProvider sessionProvider = SessionProvider.createSystemProvider();
+ try
+ {
+ readParamsFromRegistryService(sessionProvider);
+ }
+ catch (Exception e)
+ {
+ readParamsFromFile();
+ try
+ {
+ writeParamsToRegistryService(sessionProvider);
+ }
+ catch (Exception exc)
+ {
+ log.error("Cannot write init configuration to RegistryService.",
exc);
+ }
+ }
+ finally
+ {
+ sessionProvider.close();
+ }
+ }
+ else
+ {
+ readParamsFromFile();
+ }
+
+ // scan for task files
+ File[] tasks = PrivilegedFileHelper.listFiles(this.logsDirectory, new
TaskFilter());
+ for (File task : tasks)
+ {
+ try
+ {
+ scheduler.restore(task);
+ }
+ catch (BackupSchedulerException e)
+ {
+ log.error("Can't restore backup scheduler task from file " +
PrivilegedFileHelper.getAbsolutePath(task), e);
+ }
+ catch (BackupOperationException e)
+ {
+ log.error("Can't restore backup scheduler task from file " +
PrivilegedFileHelper.getAbsolutePath(task), e);
+ }
+ catch (BackupConfigurationException e)
+ {
+ log.error("Can't restore backup scheduler task from file " +
PrivilegedFileHelper.getAbsolutePath(task), e);
+ }
+ catch (RepositoryException e)
+ {
+ log.error("Can't restore backup scheduler task from file " +
PrivilegedFileHelper.getAbsolutePath(task), e);
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ log.error("Can't restore backup scheduler task from file " +
PrivilegedFileHelper.getAbsolutePath(task), e);
+ }
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void stop()
+ {
+ // 1. stop current backup chains
+ // for (Iterator iterator = currentBackups.iterator(); iterator.hasNext();) {
+ // BackupChain bc = (BackupChain) iterator.next();
+ // stopBackup(bc);
+ // }
+ //
+ // // 2. stop all scheduled tasks
+ // scheduler = null;
+ }
+
+ @Deprecated
+ private void fullRestore(String pathBackupFile, String repositoryName, String
workspaceName,
+ WorkspaceEntry workspaceEntry) throws FileNotFoundException, IOException,
RepositoryException,
+ RepositoryConfigurationException
+ {
+
+ RepositoryImpl defRep = (RepositoryImpl)repoService.getRepository(repositoryName);
+
+ defRep.importWorkspace(workspaceEntry.getName(),
PrivilegedFileHelper.fileInputStream(pathBackupFile));
+ }
+
+ private void fullRestoreOverInitializer(String pathBackupFile, String repositoryName,
WorkspaceEntry workspaceEntry,
+ String fBackupType) throws FileNotFoundException, IOException,
RepositoryException,
+ RepositoryConfigurationException, ClassNotFoundException
+ {
+ WorkspaceInitializerEntry wieOriginal = workspaceEntry.getInitializer();
+
+ RepositoryImpl defRep = (RepositoryImpl)repoService.getRepository(repositoryName);
+
+ WorkspaceInitializerEntry wiEntry = new WorkspaceInitializerEntry();
+
+ if ((Class.forName(fBackupType).equals(FullBackupJob.class)))
+ {
+ // set the initializer SysViewWorkspaceInitializer
+ wiEntry.setType(SysViewWorkspaceInitializer.class.getCanonicalName());
+
+ List<SimpleParameterEntry> wieParams = new
ArrayList<SimpleParameterEntry>();
+ wieParams.add(new
SimpleParameterEntry(SysViewWorkspaceInitializer.RESTORE_PATH_PARAMETER,
pathBackupFile));
+
+ wiEntry.setParameters(wieParams);
+ }
+ else if ((Class.forName(fBackupType)
+
.equals(org.exoplatform.services.jcr.ext.backup.impl.rdbms.FullBackupJob.class)))
+ {
+ // set the initializer RdbmsWorkspaceInitializer
+ wiEntry.setType(RdbmsWorkspaceInitializer.class.getCanonicalName());
+
+ List<SimpleParameterEntry> wieParams = new
ArrayList<SimpleParameterEntry>();
+ wieParams.add(new
SimpleParameterEntry(RdbmsWorkspaceInitializer.RESTORE_PATH_PARAMETER, new File(
+ pathBackupFile).getParent()));
+
+ wiEntry.setParameters(wieParams);
+ }
+
+ workspaceEntry.setInitializer(wiEntry);
+
+ //restore
+ defRep.configWorkspace(workspaceEntry);
+ defRep.createWorkspace(workspaceEntry.getName());
+
+ //set original workspace initializer
+ WorkspaceContainerFacade wcf =
defRep.getWorkspaceContainer(workspaceEntry.getName());
+ WorkspaceEntry createdWorkspaceEntry =
(WorkspaceEntry)wcf.getComponent(WorkspaceEntry.class);
+ createdWorkspaceEntry.setInitializer(wieOriginal);
+ }
+
+ private void incrementalRestore(String pathBackupFile, String repositoryName, String
workspaceName)
+ throws RepositoryException, RepositoryConfigurationException,
BackupOperationException, FileNotFoundException,
+ IOException, ClassNotFoundException
+ {
+ SessionImpl sesion =
(SessionImpl)repoService.getRepository(repositoryName).getSystemSession(workspaceName);
+ WorkspacePersistentDataManager dataManager =
+
(WorkspacePersistentDataManager)sesion.getContainer().getComponentInstanceOfType(
+ WorkspacePersistentDataManager.class);
+
+ ObjectInputStream ois = null;
+ File backupFile = null;
+ try
+ {
+ backupFile = new File(pathBackupFile);
+ ois = new ObjectInputStream(PrivilegedFileHelper.fileInputStream(backupFile));
+
+ while (true)
+ {
+ TransactionChangesLog changesLog = readExternal(ois);
+
+ ChangesLogIterator cli = changesLog.getLogIterator();
+ while (cli.hasNextLog())
+ {
+ if (cli.nextLog().getEventType() == ExtendedEvent.LOCK)
+ cli.removeLog();
+ }
+
+ saveChangesLog(dataManager, changesLog);
+ }
+ }
+ catch (EOFException ioe)
+ {
+ // ok - reading all data from backup file;
+ }
+ finally
+ {
+ if (sesion != null)
+ sesion.logout();
+ }
+ }
+
+ private void saveChangesLog(WorkspacePersistentDataManager dataManager,
TransactionChangesLog changesLog)
+ throws RepositoryException, BackupOperationException
+ {
+ try
+ {
+ dataManager.save(changesLog);
+ }
+ catch (JCRInvalidItemStateException e)
+ {
+ TransactionChangesLog normalizeChangesLog =
+ getNormalizedChangesLog(e.getIdentifier(), e.getState(), changesLog);
+ if (normalizeChangesLog != null)
+ saveChangesLog(dataManager, normalizeChangesLog);
+ else
+ throw new BackupOperationException(
+ "Collisions found during save of restore changes log, but caused item
is not found by ID "
+ + e.getIdentifier() + ". " + e, e);
+ }
+ catch (JCRItemExistsException e)
+ {
+ TransactionChangesLog normalizeChangesLog =
+ getNormalizedChangesLog(e.getIdentifier(), e.getState(), changesLog);
+ if (normalizeChangesLog != null)
+ saveChangesLog(dataManager, normalizeChangesLog);
+ else
+ throw new RepositoryException(
+ "Collisions found during save of restore changes log, but caused item
is not found by ID "
+ + e.getIdentifier() + ". " + e, e);
+ }
+
+ }
+
+ private TransactionChangesLog getNormalizedChangesLog(String collisionID, int state,
TransactionChangesLog changesLog)
+ {
+ ItemState citem = changesLog.getItemState(collisionID);
+
+ if (citem != null)
+ {
+
+ TransactionChangesLog result = new TransactionChangesLog();
+ result.setSystemId(changesLog.getSystemId());
+
+ ChangesLogIterator cli = changesLog.getLogIterator();
+ while (cli.hasNextLog())
+ {
+ ArrayList<ItemState> normalized = new ArrayList<ItemState>();
+ PlainChangesLog next = cli.nextLog();
+ for (ItemState change : next.getAllStates())
+ {
+ if (state == change.getState())
+ {
+ ItemData item = change.getData();
+ // targeted state
+ if (citem.isNode())
+ {
+ // Node... by ID and desc path
+ if (!item.getIdentifier().equals(collisionID)
+ &&
!item.getQPath().isDescendantOf(citem.getData().getQPath()))
+ normalized.add(change);
+ }
+ else if (!item.getIdentifier().equals(collisionID))
+ {
+ // Property... by ID
+ normalized.add(change);
+ }
+ }
+ else
+ // another state
+ normalized.add(change);
+ }
+
+ PlainChangesLog plog = new PlainChangesLogImpl(normalized,
next.getSessionId(), next.getEventType());
+ result.addLog(plog);
+ }
+
+ return result;
+ }
+
+ return null;
+ }
+
+ private TransactionChangesLog readExternal(ObjectInputStream in) throws IOException,
ClassNotFoundException
+ {
+ int changesLogType = in.readInt();
+
+ TransactionChangesLog transactionChangesLog = null;
+
+ if (changesLogType == PendingChangesLog.Type.CHANGESLOG_WITH_STREAM)
+ {
+
+ // read ChangesLog
+ transactionChangesLog = (TransactionChangesLog)in.readObject();
+
+ // read FixupStream count
+ int iFixupStream = in.readInt();
+
+ ArrayList<FixupStream> listFixupStreams = new
ArrayList<FixupStream>();
+
+ for (int i = 0; i < iFixupStream; i++)
+ {
+ FixupStream fs = new FixupStream();
+ fs.readExternal(in);
+ listFixupStreams.add(fs);
+ }
+ // listFixupStreams.add((FixupStream) in.readObject());
+
+ // read stream data
+ int iStreamCount = in.readInt();
+ ArrayList<File> listFiles = new ArrayList<File>();
+
+ for (int i = 0; i < iStreamCount; i++)
+ {
+
+ // read file size
+ long fileSize = in.readLong();
+
+ // read content file
+ File contentFile = getAsFile(in, fileSize);
+ listFiles.add(contentFile);
+ }
+
+ PendingChangesLog pendingChangesLog =
+ new PendingChangesLog(transactionChangesLog, listFixupStreams, listFiles,
fileCleaner);
+
+ pendingChangesLog.restore();
+
+ TransactionChangesLog log = pendingChangesLog.getItemDataChangesLog();
+
+ }
+ else if (changesLogType == PendingChangesLog.Type.CHANGESLOG_WITHOUT_STREAM)
+ {
+ transactionChangesLog = (TransactionChangesLog)in.readObject();
+ }
+
+ return transactionChangesLog;
+ }
+
+ private File getAsFile(ObjectInputStream ois, long fileSize) throws IOException
+ {
+ int bufferSize = /* 8191 */1024 * 8;
+ byte[] buf = new byte[bufferSize];
+
+ File tempFile = SpoolFile.createTempFile("" + System.currentTimeMillis(),
".stmp", tempDir);
+ FileOutputStream fos = PrivilegedFileHelper.fileOutputStream(tempFile);
+ long readBytes = fileSize;
+
+ while (readBytes > 0)
+ {
+ // long longTemp = readByte - bufferSize;
+ if (readBytes >= bufferSize)
+ {
+ ois.readFully(buf);
+ fos.write(buf);
+ }
+ else if (readBytes < bufferSize)
+ {
+ ois.readFully(buf, 0, (int)readBytes);
+ fos.write(buf, 0, (int)readBytes);
+ }
+ readBytes -= bufferSize;
+ }
+
+ fos.flush();
+ fos.close();
+
+ return tempFile;
+ }
+
+ /**
+ * Write parameters to RegistryService.
+ *
+ * @param sessionProvider
+ * The SessionProvider
+ * @throws ParserConfigurationException
+ * @throws SAXException
+ * @throws IOException
+ * @throws RepositoryException
+ */
+ private void writeParamsToRegistryService(SessionProvider sessionProvider) throws
IOException, SAXException,
+ ParserConfigurationException, RepositoryException
+ {
+ Document doc = SecurityHelper.doPriviledgedParserConfigurationAction(new
PrivilegedExceptionAction<Document>()
+ {
+ public Document run() throws Exception
+ {
+ return
DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
+ }
+ });
+
+ Element root = doc.createElement(SERVICE_NAME);
+ doc.appendChild(root);
+
+ Element element = doc.createElement(BACKUP_PROPERTIES);
+ setAttributeSmart(element, BACKUP_DIR, backupDir);
+ setAttributeSmart(element, DEFAULT_INCREMENTAL_JOB_PERIOD, defIncrPeriod);
+ setAttributeSmart(element, FULL_BACKUP_TYPE, fullBackupType);
+ setAttributeSmart(element, INCREMENTAL_BACKUP_TYPE, incrementalBackupType);
+ root.appendChild(element);
+
+ RegistryEntry serviceEntry = new RegistryEntry(doc);
+ registryService.createEntry(sessionProvider, RegistryService.EXO_SERVICES,
serviceEntry);
+ }
+
+ /**
+ * Read parameters from RegistryService.
+ *
+ * @param sessionProvider
+ * The SessionProvider
+ * @throws RepositoryException
+ * @throws PathNotFoundException
+ */
+ private void readParamsFromRegistryService(SessionProvider sessionProvider) throws
PathNotFoundException,
+ RepositoryException
+ {
+ String entryPath = RegistryService.EXO_SERVICES + "/" + SERVICE_NAME +
"/" + BACKUP_PROPERTIES;
+ RegistryEntry registryEntry = registryService.getEntry(sessionProvider,
entryPath);
+ Document doc = registryEntry.getDocument();
+ Element element = doc.getDocumentElement();
+
+ backupDir = getAttributeSmart(element, BACKUP_DIR);
+ defIncrPeriod = getAttributeSmart(element, DEFAULT_INCREMENTAL_JOB_PERIOD);
+ fullBackupType = getAttributeSmart(element, FULL_BACKUP_TYPE);
+ incrementalBackupType = getAttributeSmart(element, INCREMENTAL_BACKUP_TYPE);
+
+ log.info("Backup dir from RegistryService: " + backupDir);
+ log.info("Default incremental job period from RegistryService: " +
defIncrPeriod);
+ log.info("Full backup type from RegistryService: " + fullBackupType);
+ log.info("Incremental backup type from RegistryService: " +
incrementalBackupType);
+
+ checkParams();
+ }
+
+ /**
+ * Get attribute value.
+ *
+ * @param element
+ * The element to get attribute value
+ * @param attr
+ * The attribute name
+ * @return Value of attribute if present and null in other case
+ */
+ private String getAttributeSmart(Element element, String attr)
+ {
+ return element.hasAttribute(attr) ? element.getAttribute(attr) : null;
+ }
+
+ /**
+ * Set attribute value. If value is null the attribute will be removed.
+ *
+ * @param element
+ * The element to set attribute value
+ * @param attr
+ * The attribute name
+ * @param value
+ * The value of attribute
+ */
+ private void setAttributeSmart(Element element, String attr, String value)
+ {
+ if (value == null)
+ {
+ element.removeAttribute(attr);
+ }
+ else
+ {
+ element.setAttribute(attr, value);
+ }
+ }
+
+ /**
+ * Get parameters which passed from the file.
+ *
+ * @throws RepositoryConfigurationException
+ */
+ private void readParamsFromFile()
+ {
+ PropertiesParam pps = initParams.getPropertiesParam(BACKUP_PROPERTIES);
+
+ backupDir = pps.getProperty(BACKUP_DIR);
+ defIncrPeriod = pps.getProperty(DEFAULT_INCREMENTAL_JOB_PERIOD);
+ fullBackupType = pps.getProperty(FULL_BACKUP_TYPE);
+ incrementalBackupType = pps.getProperty(INCREMENTAL_BACKUP_TYPE);
+
+ log.info("Backup dir from configuration file: " + backupDir);
+ log.info("Default incremental job period from configuration file: " +
defIncrPeriod);
+ log.info("Full backup type from configuration file: " + fullBackupType);
+ log.info("Incremental backup type from configuration file: " +
incrementalBackupType);
+
+ checkParams();
+ }
+
+ /**
+ * Check read params and initialize.
+ */
+ private void checkParams()
+ {
+ if (backupDir == null)
+ throw new RuntimeException(BACKUP_DIR + " not specified");
+
+ logsDirectory = new File(backupDir);
+ if (!PrivilegedFileHelper.exists(logsDirectory))
+ PrivilegedFileHelper.mkdirs(logsDirectory);
+
+ if (defIncrPeriod == null)
+ throw new RuntimeException(DEFAULT_INCREMENTAL_JOB_PERIOD + " not
specified");
+
+ defaultIncrementalJobPeriod = Integer.valueOf(defIncrPeriod);
+
+ if (fullBackupType == null)
+ throw new RuntimeException(FULL_BACKUP_TYPE + " not specified");
+
+ if (incrementalBackupType == null)
+ throw new RuntimeException(INCREMENTAL_BACKUP_TYPE + " not
specified");
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public BackupChain findBackup(String repository, String workspace)
+ {
+ Iterator<BackupChain> it = currentBackups.iterator();
+ while (it.hasNext())
+ {
+ BackupChain chain = it.next();
+ if (repository.equals(chain.getBackupConfig().getRepository())
+ && workspace.equals(chain.getBackupConfig().getWorkspace()))
+ return chain;
+ }
+ return null;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public BackupChain findBackup(String backupId)
+ {
+ Iterator<BackupChain> it = currentBackups.iterator();
+ while (it.hasNext())
+ {
+ BackupChain chain = it.next();
+ if (backupId.equals(chain.getBackupId()))
+ return chain;
+ }
+ return null;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public BackupScheduler getScheduler()
+ {
+ return scheduler;
+ }
+
+ /**
+ * getLogsDirectory.
+ *
+ * @return File
+ * return the logs directory
+ */
+ File getLogsDirectory()
+ {
+ return logsDirectory;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public File getBackupDirectory()
+ {
+ return getLogsDirectory();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getFullBackupType()
+ {
+ return fullBackupType;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getIncrementalBackupType()
+ {
+ return incrementalBackupType;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public long getDefaultIncrementalJobPeriod()
+ {
+ return defaultIncrementalJobPeriod;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public List<JobWorkspaceRestore> getRestores()
+ {
+ return restoreJobs;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public JobWorkspaceRestore getLastRestore(String repositoryName, String
workspaceName)
+ {
+ for (int i = restoreJobs.size() - 1; i >= 0; i--)
+ {
+ JobWorkspaceRestore job = restoreJobs.get(i);
+
+ if (repositoryName.equals(job.getRepositoryName()) &&
workspaceName.equals(job.getWorkspaceName()))
+ {
+ return job;
+
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public JobRepositoryRestore getLastRepositoryRestore(String repositoryName)
+ {
+
+ for (int i = restoreRepositoryJobs.size() - 1; i >= 0; i--)
+ {
+ JobRepositoryRestore job = restoreRepositoryJobs.get(i);
+
+ if (repositoryName.equals(job.getRepositoryName()))
+ {
+ return job;
+
+ }
+ }
+
+ return null;
+ }
+
+ public List<JobRepositoryRestore> getRepositoryRestores()
+ {
+ return restoreRepositoryJobs;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restore(BackupChainLog log, String repositoryName, WorkspaceEntry
workspaceEntry, boolean asynchronous)
+ throws BackupOperationException, BackupConfigurationException,
RepositoryException,
+ RepositoryConfigurationException
+ {
+ if (workspaceEntry == null)
+ {
+ if (!log.getBackupConfig().getRepository().equals(repositoryName))
+ {
+ throw new WorkspaceRestoreException("If workspaceEntry is null, so will
be restored with original configuration. " +
+ "The repositoryName (\"" + repositoryName +"\")
should be equals original repository name (\"" +
log.getBackupConfig().getRepository() +"\"). " );
+ }
+
+ if (log.getOriginalWorkspaceEntry() == null)
+ {
+ throw new RepositoryRestoreExeption("The backup log is not contains
original repository log : " + log.getLogFilePath());
+ }
+
+
+ this.restore(log, log.getBackupConfig().getRepository(),
log.getOriginalWorkspaceEntry(), asynchronous);
+ return;
+ }
+
+ if (asynchronous)
+ {
+ JobWorkspaceRestore jobRestore =
+ new JobWorkspaceRestore(repoService, this, repositoryName, log,
workspaceEntry);
+ restoreJobs.add(jobRestore);
+ jobRestore.start();
+ }
+ else
+ {
+ this.restoreOverInitializer(log, repositoryName, workspaceEntry);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restore(RepositoryBackupChainLog log, RepositoryEntry repositoryEntry,
boolean asynchronous)
+ throws BackupOperationException, BackupConfigurationException,
RepositoryException,
+ RepositoryConfigurationException
+ {
+ if (repositoryEntry == null)
+ {
+ if (log.getOriginalRepositoryEntry() == null)
+ {
+ throw new RepositoryRestoreExeption("The backup log is not contains
original repository log : "
+ + log.getLogFilePath());
+ }
+
+ this.restore(log, log.getOriginalRepositoryEntry(), asynchronous);
+ return;
+ }
+
+ this.restore(log, repositoryEntry, null, asynchronous);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restore(RepositoryBackupChainLog rblog, RepositoryEntry repositoryEntry,
+ Map<String, String> workspaceNamesCorrespondMap, boolean asynchronous) throws
BackupOperationException,
+ BackupConfigurationException, RepositoryException,
RepositoryConfigurationException
+ {
+ // Checking repository exists.
+ try
+ {
+ repoService.getRepository(repositoryEntry.getName());
+ throw new BackupConfigurationException("Repository \"" +
repositoryEntry.getName() + "\" is already exists.");
+ }
+ catch (RepositoryException e)
+ {
+ //OK. Repository with "repositoryEntry.getName" is not exists.
+ }
+
+ Map<String, BackupChainLog> workspacesMapping = new HashedMap();
+
+ Map<String, BackupChainLog> backups = new HashedMap();
+
+ if (workspaceNamesCorrespondMap == null)
+ {
+ for (String path : rblog.getWorkspaceBackupsInfo())
+ {
+ BackupChainLog bLog = new BackupChainLog(new File(path));
+ backups.put(bLog.getBackupConfig().getWorkspace(), bLog);
+ }
+
+ if
(!rblog.getSystemWorkspace().equals(repositoryEntry.getSystemWorkspaceName()))
+ {
+ throw new BackupConfigurationException(
+ "The backup to system workspace is not system workspace in repository
entry: "
+ + rblog.getSystemWorkspace() + " is not equal " +
repositoryEntry.getSystemWorkspaceName());
+ }
+
+ if (backups.size() != repositoryEntry.getWorkspaceEntries().size())
+ {
+ throw new BackupConfigurationException(
+ "The repository entry is contains more or less workspace entry than
backups of workspace in "
+ + rblog.getLogFilePath());
+ }
+
+ for (WorkspaceEntry wsEntry : repositoryEntry.getWorkspaceEntries())
+ {
+ if (!backups.containsKey(wsEntry.getName()))
+ {
+ throw new BackupConfigurationException("The workspace '" +
wsEntry.getName()
+ + "' is not found in backup " + rblog.getLogFilePath());
+ }
+ else
+ {
+ workspacesMapping.put(wsEntry.getName(), backups.get(wsEntry.getName()));
+ }
+ }
+ }
+ else
+ {
+ // Create map [new_ws_name : backupLog to that workspace].
+ for (String path : rblog.getWorkspaceBackupsInfo())
+ {
+ BackupChainLog bLog = new BackupChainLog(new File(path));
+
+ if
(!workspaceNamesCorrespondMap.containsKey(bLog.getBackupConfig().getWorkspace()))
+ {
+ throw new BackupConfigurationException("Can not found coresptonding
workspace name to workspace '"
+ + bLog.getBackupConfig().getWorkspace() + "' in " +
workspaceNamesCorrespondMap.keySet());
+ }
+
+
backups.put(workspaceNamesCorrespondMap.get(bLog.getBackupConfig().getWorkspace()),
bLog);
+ }
+
+ // Checking system workspace.
+ if (!repositoryEntry.getSystemWorkspaceName().equals(
+ workspaceNamesCorrespondMap.get(rblog.getSystemWorkspace())))
+ {
+ throw new BackupConfigurationException(
+ "The backup to system workspace is not system workspace in repository
entry: "
+ + repositoryEntry.getSystemWorkspaceName() + " is not equal
"
+ + workspaceNamesCorrespondMap.get(rblog.getSystemWorkspace()));
+ }
+
+ // Checking count of corresponding workspaces.
+ if (workspaceNamesCorrespondMap.size() !=
repositoryEntry.getWorkspaceEntries().size())
+ {
+ throw new BackupConfigurationException(
+ "The repository entry is contains more or less workspace entry than
backups of workspace in "
+ + rblog.getLogFilePath());
+ }
+
+ for (WorkspaceEntry wsEntry : repositoryEntry.getWorkspaceEntries())
+ {
+ if (!workspaceNamesCorrespondMap.containsValue(wsEntry.getName()))
+ {
+ throw new BackupConfigurationException("The workspace '" +
wsEntry.getName()
+ + "' is not found workspaceNamesCorrespondMap : " +
workspaceNamesCorrespondMap.values());
+ }
+ else if (!backups.containsKey(wsEntry.getName()))
+ {
+ throw new BackupConfigurationException("The workspace '" +
wsEntry.getName()
+ + "' is not found in backup " + rblog.getLogFilePath());
+ }
+ else
+ {
+ workspacesMapping.put(wsEntry.getName(), backups.get(wsEntry.getName()));
+ }
+ }
+ }
+
+ JobRepositoryRestore jobRepositoryRestore =
+ new JobRepositoryRestore(repoService, this, repositoryEntry, workspacesMapping,
rblog);
+
+ restoreRepositoryJobs.add(jobRepositoryRestore);
+ if (asynchronous)
+ {
+ jobRepositoryRestore.start();
+ }
+ else
+ {
+ jobRepositoryRestore.restore();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public RepositoryBackupChain startBackup(RepositoryBackupConfig config) throws
BackupOperationException,
+ BackupConfigurationException, RepositoryException,
RepositoryConfigurationException
+ {
+ validateBackupConfig(config);
+
+ File dir =
+ new File(config.getBackupDir() + File.separator + "repository_" +
config.getRepository() + "_backup_"
+ + System.currentTimeMillis());
+ PrivilegedFileHelper.mkdirs(dir);
+ config.setBackupDir(dir);
+
+ RepositoryBackupChain repositoryBackupChain =
+ new RepositoryBackupChainImpl(config, logsDirectory, repoService,
fullBackupType,
+ incrementalBackupType,
+ IdGenerator.generate());
+
+ repositoryBackupChain.startBackup();
+
+ currentRepositoryBackups.add(repositoryBackupChain);
+
+ return repositoryBackupChain;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void stopBackup(RepositoryBackupChain backup)
+ {
+ backup.stopBackup();
+ currentRepositoryBackups.remove(backup);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public RepositoryBackupChain findRepositoryBackup(String repository)
+ {
+ Iterator<RepositoryBackupChain> it = currentRepositoryBackups.iterator();
+ while (it.hasNext())
+ {
+ RepositoryBackupChain chain = it.next();
+ if (repository.equals(chain.getBackupConfig().getRepository()))
+ return chain;
+ }
+ return null;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<RepositoryBackupChain> getCurrentRepositoryBackups()
+ {
+ return currentRepositoryBackups;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public RepositoryBackupChain findRepositoryBackupId(String backupId)
+ {
+ Iterator<RepositoryBackupChain> it = currentRepositoryBackups.iterator();
+ while (it.hasNext())
+ {
+ RepositoryBackupChain chain = it.next();
+ if (backupId.equals(chain.getBackupId()))
+ return chain;
+ }
+ return null;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreExistingRepository(RepositoryBackupChainLog rblog, RepositoryEntry
repositoryEntry,
+ boolean asynchronous) throws BackupOperationException,
BackupConfigurationException
+ {
+ try
+ {
+ // repository should be existed
+ repoService.getRepository(repositoryEntry.getName());
+ }
+ catch (RepositoryException e)
+ {
+ throw new RepositoryRestoreExeption("Repository \"" +
repositoryEntry.getName() + "\" should be existed", e);
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ throw new RepositoryRestoreExeption("Repository \"" +
repositoryEntry.getName() + "\" should be existed", e);
+ }
+
+ Map<String, BackupChainLog> workspacesMapping = new HashedMap();
+
+ Map<String, BackupChainLog> backups = new HashedMap();
+
+ for (String path : rblog.getWorkspaceBackupsInfo())
+ {
+ BackupChainLog bLog = new BackupChainLog(new File(path));
+ backups.put(bLog.getBackupConfig().getWorkspace(), bLog);
+ }
+
+ if (!rblog.getSystemWorkspace().equals(repositoryEntry.getSystemWorkspaceName()))
+ {
+ throw new BackupConfigurationException(
+ "The backup to system workspace is not system workspace in
repository entry: "
+ + rblog.getSystemWorkspace() + " is not equal " +
repositoryEntry.getSystemWorkspaceName());
+ }
+
+ if (backups.size() != repositoryEntry.getWorkspaceEntries().size())
+ {
+ throw new BackupConfigurationException(
+ "The repository entry is contains more or less workspace entry
than backups of workspace in "
+ + rblog.getLogFilePath());
+ }
+
+ for (WorkspaceEntry wsEntry : repositoryEntry.getWorkspaceEntries())
+ {
+ if (!backups.containsKey(wsEntry.getName()))
+ {
+ throw new BackupConfigurationException("The workspace '" +
wsEntry.getName() + "' is not found in backup "
+ + rblog.getLogFilePath());
+ }
+ else
+ {
+ workspacesMapping.put(wsEntry.getName(), backups.get(wsEntry.getName()));
+ }
+ }
+
+ JobExistedRepositoryRestore jobExistedRepositoryRestore =
+ new JobExistedRepositoryRestore(repoService, this, repositoryEntry,
workspacesMapping, rblog);
+
+ restoreRepositoryJobs.add(jobExistedRepositoryRestore);
+ if (asynchronous)
+ {
+ jobExistedRepositoryRestore.start();
+ }
+ else
+ {
+ jobExistedRepositoryRestore.restore();
+ }
+
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreExistingRepository(String repositoryBackupIdentifier,
RepositoryEntry repositoryEntry,
+ boolean asynchronous) throws BackupOperationException,
BackupConfigurationException
+ {
+ RepositoryBackupChainLog backupChainLog = null;
+
+ for(RepositoryBackupChainLog chainLog : getRepositoryBackupsLogs())
+ {
+ if (chainLog.getBackupId().equals(repositoryBackupIdentifier))
+ {
+ backupChainLog = chainLog;
+ break;
+ }
+ }
+
+ if (backupChainLog == null)
+ {
+ throw new BackupConfigurationException("Can not found backup of repository
with id \""
+ + repositoryBackupIdentifier + "\"");
+ }
+
+ this.restoreExistingRepository(backupChainLog, repositoryEntry, asynchronous);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreExistingWorkspace(BackupChainLog log, String repositoryName,
WorkspaceEntry workspaceEntry,
+ boolean asynchronous) throws BackupOperationException,
BackupConfigurationException
+ {
+ try
+ {
+ // repository should be existed
+ repoService.getRepository(repositoryName);
+
+ // workspace should be existed
+ if (!workspaceAlreadyExist(repositoryName, workspaceEntry.getName()))
+ {
+ throw new WorkspaceRestoreException("Workspace \"" +
workspaceEntry.getName() + "\" should be existed in repository \"" +
repositoryName + "\".");
+ }
+ }
+ catch (RepositoryException e)
+ {
+ throw new WorkspaceRestoreException("Repository \"" +
repositoryName + "\" should be existed", e);
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ throw new WorkspaceRestoreException("Repository \"" +
repositoryName + "\" should be existed", e);
+ }
+
+ JobExistedWorkspaceRestore jobRestore =
+ new JobExistedWorkspaceRestore(repoService, this, repositoryName, log,
workspaceEntry);
+ restoreJobs.add(jobRestore);
+
+ if (asynchronous)
+ {
+ jobRestore.start();
+ }
+ else
+ {
+ jobRestore.restore();
+ }
+
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreExistingWorkspace(String workspaceBackupIdentifier, String
repositoryName,
+ WorkspaceEntry workspaceEntry, boolean asynchronous) throws
BackupOperationException,
+ BackupConfigurationException
+ {
+ BackupChainLog backupChainLog = null;
+
+ for(BackupChainLog chainLog : getBackupsLogs())
+ {
+ if (chainLog.getBackupId().equals(workspaceBackupIdentifier))
+ {
+ backupChainLog = chainLog;
+ break;
+ }
+ }
+
+ if (backupChainLog == null)
+ {
+ throw new BackupConfigurationException("Can not found backup of workspace
with id \""
+ + workspaceBackupIdentifier + "\"");
+ }
+
+ this.restoreExistingWorkspace(backupChainLog, repositoryName, workspaceEntry,
asynchronous);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreExistingRepository(String repositoryBackupIdentifier, boolean
asynchronous)
+ throws BackupOperationException, BackupConfigurationException
+ {
+ RepositoryBackupChainLog backupChainLog = null;
+
+ for (RepositoryBackupChainLog chainLog : getRepositoryBackupsLogs())
+ {
+ if (chainLog.getBackupId().equals(repositoryBackupIdentifier))
+ {
+ backupChainLog = chainLog;
+ break;
+ }
+ }
+
+ if (backupChainLog == null)
+ {
+ throw new BackupConfigurationException("Can not found backup of repository
with id \""
+ + repositoryBackupIdentifier + "\"");
+ }
+
+ this.restoreExistingRepository(backupChainLog,
backupChainLog.getOriginalRepositoryEntry(), asynchronous);
+
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreExistingWorkspace(String workspaceBackupIdentifier, boolean
asynchronous)
+ throws BackupOperationException, BackupConfigurationException
+ {
+ BackupChainLog backupChainLog = null;
+
+ for (BackupChainLog chainLog : getBackupsLogs())
+ {
+ if (chainLog.getBackupId().equals(workspaceBackupIdentifier))
+ {
+ backupChainLog = chainLog;
+ break;
+ }
+ }
+
+ if (backupChainLog == null)
+ {
+ throw new BackupConfigurationException("Can not found backup of workspace
with id \""
+ + workspaceBackupIdentifier + "\"");
+ }
+
+ this.restoreExistingWorkspace(backupChainLog,
backupChainLog.getBackupConfig().getRepository(), backupChainLog
+ .getOriginalWorkspaceEntry(), asynchronous);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreRepository(String repositoryBackupIdentifier, boolean
asynchronous)
+ throws BackupOperationException, BackupConfigurationException
+ {
+ RepositoryBackupChainLog backupChainLog = null;
+
+ for (RepositoryBackupChainLog chainLog : getRepositoryBackupsLogs())
+ {
+ if (chainLog.getBackupId().equals(repositoryBackupIdentifier))
+ {
+ backupChainLog = chainLog;
+ break;
+ }
+ }
+
+ if (backupChainLog == null)
+ {
+ throw new BackupConfigurationException("Can not found backup of repository
with id \""
+ + repositoryBackupIdentifier + "\"");
+ }
+
+ try
+ {
+ this.restore(backupChainLog, backupChainLog.getOriginalRepositoryEntry(),
asynchronous);
+ }
+ catch (RepositoryException e)
+ {
+ throw new RepositoryRestoreExeption("Repository \"" +
backupChainLog.getOriginalRepositoryEntry().getName()
+ + "\" was not restored", e);
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ throw new RepositoryRestoreExeption("Repository \"" +
backupChainLog.getOriginalRepositoryEntry().getName()
+ + "\" was not restored", e);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreWorkspace(String workspaceBackupIdentifier, boolean asynchronous)
+ throws BackupOperationException, BackupConfigurationException
+ {
+ BackupChainLog backupChainLog = null;
+
+ for (BackupChainLog chainLog : getBackupsLogs())
+ {
+ if (chainLog.getBackupId().equals(workspaceBackupIdentifier))
+ {
+ backupChainLog = chainLog;
+ break;
+ }
+ }
+
+ if (backupChainLog == null)
+ {
+ throw new BackupConfigurationException("Can not found backup of workspace
with id \""
+ + workspaceBackupIdentifier + "\"");
+ }
+
+ try
+ {
+ this.restore(backupChainLog, backupChainLog.getBackupConfig().getRepository(),
backupChainLog
+ .getOriginalWorkspaceEntry(), asynchronous);
+ }
+ catch (RepositoryException e)
+ {
+ throw new WorkspaceRestoreException("Workapce \"" +
backupChainLog.getOriginalWorkspaceEntry().getName()
+ + "\" was not restored in repository \"" +
backupChainLog.getBackupConfig().getRepository() + "\"", e);
+ }
+ catch (RepositoryConfigurationException e)
+ {
+
+ throw new WorkspaceRestoreException("Workapce \"" +
backupChainLog.getOriginalWorkspaceEntry().getName()
+ + "\" was not restored in repository \"" +
backupChainLog.getBackupConfig().getRepository() + "\"", e);
+ }
+
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreExistingRepository(File repositoryBackupSetDir, boolean
asynchronous)
+ throws BackupOperationException, BackupConfigurationException
+ {
+ File[] cfs = PrivilegedFileHelper.listFiles(repositoryBackupSetDir, new
RepositoryBackupLogsFilter());
+
+ if (cfs.length == 0)
+ {
+ throw new BackupConfigurationException("Can not found repository backup log
in directory : "
+ + repositoryBackupSetDir.getPath());
+ }
+
+ if (cfs.length > 1)
+ {
+ throw new BackupConfigurationException(
+ "Backup set directory should contains only one repository backup
log : "
+ + repositoryBackupSetDir.getPath());
+ }
+
+ RepositoryBackupChainLog backupChainLog = new RepositoryBackupChainLog(cfs[0]);
+
+ this.restoreExistingRepository(backupChainLog,
backupChainLog.getOriginalRepositoryEntry(), asynchronous);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreExistingWorkspace(File workspaceBackupSetDir, boolean
asynchronous)
+ throws BackupOperationException, BackupConfigurationException
+ {
+ File[] cfs = PrivilegedFileHelper.listFiles(workspaceBackupSetDir, new
BackupLogsFilter());
+
+ if (cfs.length == 0)
+ {
+ throw new BackupConfigurationException("Can not found workspace backup log
in directory : "
+ + workspaceBackupSetDir.getPath());
+ }
+
+ if (cfs.length > 1)
+ {
+ throw new BackupConfigurationException(
+ "Backup set directory should contains only one workspace backup
log : "
+ + workspaceBackupSetDir.getPath());
+ }
+
+ BackupChainLog backupChainLog = new BackupChainLog(cfs[0]);
+
+ this.restoreExistingWorkspace(backupChainLog,
backupChainLog.getBackupConfig().getRepository(), backupChainLog
+ .getOriginalWorkspaceEntry(), asynchronous);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreRepository(File repositoryBackupSetDir, boolean asynchronous)
throws BackupOperationException,
+ BackupConfigurationException
+ {
+ File[] cfs = PrivilegedFileHelper.listFiles(repositoryBackupSetDir, new
RepositoryBackupLogsFilter());
+
+ if (cfs.length == 0)
+ {
+ throw new BackupConfigurationException("Can not found repository backup log
in directory : "
+ + repositoryBackupSetDir.getPath());
+ }
+
+ if (cfs.length > 1)
+ {
+ throw new BackupConfigurationException(
+ "Backup set directory should contains only one repository backup
log : "
+ + repositoryBackupSetDir.getPath());
+ }
+
+ RepositoryBackupChainLog backupChainLog = new RepositoryBackupChainLog(cfs[0]);
+
+ try
+ {
+ this.restore(backupChainLog, backupChainLog.getOriginalRepositoryEntry(),
asynchronous);
+ }
+ catch (RepositoryException e)
+ {
+ throw new RepositoryRestoreExeption("Repository \"" +
backupChainLog.getOriginalRepositoryEntry().getName()
+ + "\" was not restored", e);
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ throw new RepositoryRestoreExeption("Repository \"" +
backupChainLog.getOriginalRepositoryEntry().getName()
+ + "\" was not restored", e);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void restoreWorkspace(File workspaceBackupSetDir, boolean asynchronous) throws
BackupOperationException,
+ BackupConfigurationException
+ {
+ File[] cfs = PrivilegedFileHelper.listFiles(workspaceBackupSetDir, new
BackupLogsFilter());
+
+ if (cfs.length == 0)
+ {
+ throw new BackupConfigurationException("Can not found workspace backup log
in directory : "
+ + workspaceBackupSetDir.getPath());
+ }
+
+ if (cfs.length > 1)
+ {
+ throw new BackupConfigurationException("Backup set directory should
contains only one workspace backup log : "
+ + workspaceBackupSetDir.getPath());
+ }
+
+ BackupChainLog backupChainLog = new BackupChainLog(cfs[0]);
+
+ try
+ {
+ this.restore(backupChainLog, backupChainLog.getBackupConfig().getRepository(),
backupChainLog
+ .getOriginalWorkspaceEntry(), asynchronous);
+ }
+ catch (RepositoryException e)
+ {
+ throw new WorkspaceRestoreException("Workapce \"" +
backupChainLog.getOriginalWorkspaceEntry().getName()
+ + "\" was not restored in repository \"" +
backupChainLog.getBackupConfig().getRepository() + "\"", e);
+ }
+ catch (RepositoryConfigurationException e)
+ {
+
+ throw new WorkspaceRestoreException("Workapce \"" +
backupChainLog.getOriginalWorkspaceEntry().getName()
+ + "\" was not restored in repository \"" +
backupChainLog.getBackupConfig().getRepository() + "\"", e);
+ }
+
+ }
+
+}
Modified:
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/FileNameProducer.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/FileNameProducer.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/FileNameProducer.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -21,6 +21,7 @@
import org.exoplatform.commons.utils.PrivilegedFileHelper;
import java.io.File;
+import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Calendar;
@@ -30,15 +31,25 @@
*/
public class FileNameProducer
{
+ class SkipBackupLogFilter
+ implements FilenameFilter
+ {
+
+ public boolean accept(File dir, String name)
+ {
+ return !name.endsWith(".xml");
+ }
+ }
+
/**
* Backup set name.
*/
- private final String backupSetName;
+ private String backupSetName;
/**
* Backup set directory.
*/
- private final File backupSetDir;
+ private File backupSetDir;
/**
* Indicates is full backup or not.
@@ -48,7 +59,7 @@
/**
* Indicates that need to create a directory for full backup otherwise is will be the
single file.
*/
- private final boolean isDirectoryForFullBackup;
+ private boolean isDirectoryForFullBackup;
/**
* Constructor FileNameProducer.
@@ -65,14 +76,13 @@
* indicates that need to create a directory for full backup otherwise is
will be the single file
*/
public FileNameProducer(String backupSetName, String backupDir, Calendar timeStamp,
boolean isFullBackup,
- boolean isDirectory)
+ boolean isDirectory)
{
this.backupSetName = backupSetName;
this.isFullBackup = isFullBackup;
this.isDirectoryForFullBackup = isDirectory;
- String sTime = "-" + getStrDate(timeStamp) + "_" +
getStrTime(timeStamp);
- this.backupSetDir = new File(backupDir + File.separator + backupSetName + sTime);
+ this.backupSetDir = new File(backupDir);
if (!PrivilegedFileHelper.exists(backupSetDir))
{
@@ -80,6 +90,21 @@
}
}
+ public static File generateBackupSetDir(String repositoryName, String workspaceName,
String backupDir,
+ Calendar timeStamp)
+ {
+ FileNameProducer fileNameProducer = new FileNameProducer();
+ String sTime = "-" + fileNameProducer.getStrDate(timeStamp) +
"_" + fileNameProducer.getStrTime(timeStamp);
+ File fBackupSetDir = new File(backupDir + File.separator + repositoryName +
"_" + workspaceName + sTime);
+
+ if (!PrivilegedFileHelper.exists(fBackupSetDir))
+ {
+ PrivilegedFileHelper.mkdirs(fBackupSetDir);
+ }
+
+ return fBackupSetDir;
+ }
+
/**
* Constructor FileNameProducer.
*
@@ -97,7 +122,7 @@
* indicates that need to create a directory for full backup otherwise is
will be the single file
*/
public FileNameProducer(String repositoryName, String workspaceName, String backupDir,
Calendar timeStamp,
- boolean isFullBackup, boolean isDirectory)
+ boolean isFullBackup, boolean isDirectory)
{
this(repositoryName + "_" + workspaceName, backupDir, timeStamp,
isFullBackup, isDirectory);
}
@@ -117,12 +142,19 @@
* indicates is full backup or not
*/
public FileNameProducer(String repositoryName, String workspaceName, String backupDir,
Calendar timeStamp,
- boolean isFullBackup)
+ boolean isFullBackup)
{
this(repositoryName + "_" + workspaceName, backupDir, timeStamp,
isFullBackup, false);
}
/**
+ * Empty constructor.
+ */
+ public FileNameProducer()
+ {
+ }
+
+ /**
* Get next file in backup set.
*
* @return
@@ -185,14 +217,14 @@
private String getNextSufix()
{
- String[] fileList = PrivilegedFileHelper.list(backupSetDir);
+ String[] fileList = PrivilegedFileHelper.list(backupSetDir, new
SkipBackupLogFilter());
int sufix = 0;
for (int i = 0; i < fileList.length; i++)
{
String[] stringArray = fileList[i].split("[.]");
-
+
int currentSufix = Integer.valueOf(stringArray[stringArray.length -
1]).intValue();
if (currentSufix > sufix)
@@ -225,4 +257,15 @@
return "" + (h < 10 ? "0" + h : h) + (m < 10 ?
"0" + m : m) + (s < 10 ? "0" + s : s);
}
+ /**
+ * Get Backup set directory.
+ *
+ * @return File
+ * The backup set directory
+ */
+ public File getBackupSetDir()
+ {
+ return backupSetDir;
+ }
+
}
Modified:
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/JobRepositoryRestore.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/JobRepositoryRestore.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/JobRepositoryRestore.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -16,6 +16,8 @@
*/
package org.exoplatform.services.jcr.ext.backup.impl;
+
+
import org.exoplatform.services.jcr.RepositoryService;
import org.exoplatform.services.jcr.config.RepositoryEntry;
import org.exoplatform.services.jcr.config.SimpleParameterEntry;
@@ -28,10 +30,10 @@
import org.exoplatform.services.jcr.ext.backup.RepositoryBackupChainLog;
import org.exoplatform.services.jcr.ext.backup.RepositoryRestoreExeption;
import org.exoplatform.services.jcr.ext.backup.impl.fs.FullBackupJob;
-import org.exoplatform.services.jcr.ext.backup.impl.rdbms.RdbmsWorkspaceInitializer;
+import
org.exoplatform.services.jcr.ext.backup.impl.rdbms.RdbmsBackupWorkspaceInitializer;
+import org.exoplatform.services.jcr.impl.core.BackupWorkspaceInitializer;
import org.exoplatform.services.jcr.impl.core.RepositoryImpl;
import org.exoplatform.services.jcr.impl.core.SessionRegistry;
-import org.exoplatform.services.jcr.impl.core.SysViewWorkspaceInitializer;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
@@ -302,22 +304,23 @@
WorkspaceInitializerEntry wiEntry = new WorkspaceInitializerEntry();
if ((Class.forName(fullbackupType).equals(FullBackupJob.class)))
{
- // set the initializer SysViewWorkspaceInitializer
- wiEntry.setType(SysViewWorkspaceInitializer.class.getCanonicalName());
+ // set the initializer BackupWorkspaceInitializer
+ wiEntry.setType(BackupWorkspaceInitializer.class.getCanonicalName());
List<SimpleParameterEntry> wieParams = new
ArrayList<SimpleParameterEntry>();
- wieParams.add(new
SimpleParameterEntry(SysViewWorkspaceInitializer.RESTORE_PATH_PARAMETER,
fullBackupPath));
+ wieParams.add(new
SimpleParameterEntry(BackupWorkspaceInitializer.RESTORE_PATH_PARAMETER, (new File(
+ fullBackupPath).getParent())));
wiEntry.setParameters(wieParams);
}
else if ((Class.forName(fullbackupType)
.equals(org.exoplatform.services.jcr.ext.backup.impl.rdbms.FullBackupJob.class)))
{
- // set the initializer RdbmsWorkspaceInitializer
- wiEntry.setType(RdbmsWorkspaceInitializer.class.getCanonicalName());
+ // set the initializer RdbmsBackupWorkspaceInitializer
+ wiEntry.setType(RdbmsBackupWorkspaceInitializer.class.getCanonicalName());
List<SimpleParameterEntry> wieParams = new
ArrayList<SimpleParameterEntry>();
- wieParams.add(new
SimpleParameterEntry(RdbmsWorkspaceInitializer.RESTORE_PATH_PARAMETER, (new File(
+ wieParams.add(new
SimpleParameterEntry(RdbmsBackupWorkspaceInitializer.RESTORE_PATH_PARAMETER, (new File(
fullBackupPath).getParent())));
wiEntry.setParameters(wieParams);
Modified:
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/RepositoryBackupChainImpl.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/RepositoryBackupChainImpl.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/RepositoryBackupChainImpl.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -16,16 +16,11 @@
*/
package org.exoplatform.services.jcr.ext.backup.impl;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
+import org.exoplatform.commons.utils.PrivilegedFileHelper;
+import org.exoplatform.services.jcr.RepositoryService;
+import org.exoplatform.services.jcr.config.RepositoryConfigurationException;
+import org.exoplatform.services.jcr.config.RepositoryEntry;
import org.exoplatform.services.jcr.config.WorkspaceEntry;
-import org.exoplatform.services.jcr.core.ManageableRepository;
import org.exoplatform.services.jcr.ext.backup.BackupChain;
import org.exoplatform.services.jcr.ext.backup.BackupConfig;
import org.exoplatform.services.jcr.ext.backup.BackupConfigurationException;
@@ -39,6 +34,14 @@
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
/**
* Created by The eXo Platform SAS.
*
@@ -67,7 +70,8 @@
private int state;
- public RepositoryBackupChainImpl(RepositoryBackupConfig config, File logDirectory,
ManageableRepository repository,
+ public RepositoryBackupChainImpl(RepositoryBackupConfig config, File logDirectory,
+ RepositoryService repositoryService,
String fullBackupType, String incrementalBackupType, String
repositoryBackupId)
throws BackupOperationException,
BackupConfigurationException
@@ -79,19 +83,35 @@
List<String> wsLogFilePathList = new ArrayList<String>();
- for (WorkspaceEntry workspaceEntry :
repository.getConfiguration().getWorkspaceEntries())
+ RepositoryEntry repository;
+ try
{
+ repository =
repositoryService.getConfig().getRepositoryConfiguration(config.getRepository());
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ throw new BackupOperationException("Can not get repository \"" +
config.getRepository() + "\"", e);
+ }
+
+ for (WorkspaceEntry workspaceEntry : repository.getWorkspaceEntries())
+ {
BackupConfig wsBackupConfig = new BackupConfig();
wsBackupConfig.setRepository(config.getRepository());
wsBackupConfig.setWorkspace(workspaceEntry.getName());
- wsBackupConfig.setBackupDir(config.getBackupDir());
wsBackupConfig.setBackupType(config.getBackupType());
wsBackupConfig.setIncrementalJobNumber(config.getIncrementalJobNumber());
wsBackupConfig.setIncrementalJobPeriod(config.getIncrementalJobPeriod());
+ Calendar startTime = Calendar.getInstance();
+ File dir =
+ FileNameProducer.generateBackupSetDir(wsBackupConfig.getRepository(),
wsBackupConfig.getWorkspace(),
+ config.getBackupDir().getPath(), startTime);
+ PrivilegedFileHelper.mkdirs(dir);
+ wsBackupConfig.setBackupDir(dir);
+
BackupChain bchain =
- new BackupChainImpl(wsBackupConfig, config.getBackupDir(), repository,
fullBackupType,
- incrementalBackupType, IdGenerator.generate(), logDirectory);
+ new BackupChainImpl(wsBackupConfig, wsBackupConfig.getBackupDir(),
repositoryService, fullBackupType,
+ incrementalBackupType, IdGenerator.generate(), logDirectory,
startTime);
wsLogFilePathList.add(bchain.getLogFilePath());
workspaceBackups.add(bchain);
@@ -101,11 +121,12 @@
this.config,
fullBackupType,
incrementalBackupType,
-
repository.getConfiguration().getSystemWorkspaceName(),
+
repository.getSystemWorkspaceName(),
wsLogFilePathList,
this.repositoryBackupId,
startTime,
-
repository.getConfiguration());
+ repository,
+
repositoryService.getConfig());
state = INITIALIZED;
}
Modified:
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/server/HTTPBackupAgent.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/server/HTTPBackupAgent.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/server/HTTPBackupAgent.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -32,11 +32,16 @@
import org.exoplatform.services.jcr.ext.backup.BackupConfigurationException;
import org.exoplatform.services.jcr.ext.backup.BackupManager;
import org.exoplatform.services.jcr.ext.backup.BackupOperationException;
+import org.exoplatform.services.jcr.ext.backup.ExtendedBackupManager;
import org.exoplatform.services.jcr.ext.backup.RepositoryBackupChain;
import org.exoplatform.services.jcr.ext.backup.RepositoryBackupChainLog;
import org.exoplatform.services.jcr.ext.backup.RepositoryBackupConfig;
+import org.exoplatform.services.jcr.ext.backup.RestoreConfigurationException;
+import org.exoplatform.services.jcr.ext.backup.WorkspaceRestoreException;
+import org.exoplatform.services.jcr.ext.backup.impl.BackupLogsFilter;
import org.exoplatform.services.jcr.ext.backup.impl.JobRepositoryRestore;
import org.exoplatform.services.jcr.ext.backup.impl.JobWorkspaceRestore;
+import org.exoplatform.services.jcr.ext.backup.impl.RepositoryBackupLogsFilter;
import org.exoplatform.services.jcr.ext.backup.server.bean.BackupConfigBean;
import
org.exoplatform.services.jcr.ext.backup.server.bean.response.BackupServiceInfoBean;
import org.exoplatform.services.jcr.ext.backup.server.bean.response.DetailedInfo;
@@ -120,11 +125,21 @@
public static final String RESTORE = "/restore";
/**
+ * Restore operations from backup set.
+ */
+ public static final String RESTORE_BACKUP_SET =
"/restore/backup-set";
+
+ /**
* Restore repository operations.
*/
public static final String RESTORE_REPOSITORY =
"/restore-repository";
/**
+ * Restore repository operations from backup set.
+ */
+ public static final String RESTORE_REPOSITORY_BACKUP_SET =
"/restore-repository/backup-set";
+
+ /**
* Stop backup operations.
*/
public static final String STOP_BACKUP = "/stop";
@@ -260,7 +275,7 @@
/**
* The backup manager.
*/
- private BackupManager backupManager;
+ private ExtendedBackupManager backupManager;
/**
* Will be get session over base authenticate.
@@ -281,7 +296,7 @@
ThreadLocalSessionProviderService sessionProviderService)
{
this.repositoryService = repoService;
- this.backupManager = backupManager;
+ this.backupManager = (ExtendedBackupManager) backupManager;
this.sessionProviderService = sessionProviderService;
log.info("HTTPBackupAgent inited");
@@ -576,7 +591,7 @@
validateRepositoryName(repository);
if (isWorkspaceExist(repository, wEntry.getName()))
- throw new Exception("Workspace " + wEntry.getName() + "
already exist!");
+ throw new WorkspaceRestoreException("Workspace " + wEntry.getName()
+ " already exist!");
BackupChainLog backupChainLog = new BackupChainLog(backupLog);
@@ -656,6 +671,713 @@
}
/**
+ * Restore the workspace.
+ *
+ * @param wEntry
+ * WorkspaceEntry, the configuration to restored workspace
+ * @param repository
+ * String, the repository name
+ * @param backupId
+ * String, the identifier of backup
+ * @param removeExisting
+ * Boolean, if 'true' will be removed fully (db, value storage,
index) existed workspace.
+ * @return Response return the response
+ */
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @RolesAllowed("administrators")
+ @Path("/restore/{repo}/{id}/{remove-Existing}")
+ public Response restore(WorkspaceEntry wEntry, @PathParam("repo") String
repository,
+ @PathParam("id") String backupId,
@PathParam("remove-Existing") Boolean removeExisting)
+ {
+ String failMessage;
+ Response.Status status;
+ Throwable exception;
+
+ try
+ {
+ validateOneRestoreInstants(repository, wEntry.getName());
+
+ File backupLog = getBackupLogbyId(backupId);
+
+ // validate backup log file
+ if (backupLog == null)
+ {
+ throw new BackupLogNotFoundException("The backup log file with id "
+ backupId + " not exists.");
+ }
+
+ validateRepositoryName(repository);
+
+ BackupChainLog backupChainLog = new BackupChainLog(backupLog);
+
+ if (removeExisting)
+ {
+ if (!isWorkspaceExist(repository, wEntry.getName()))
+ {
+ throw new WorkspaceRestoreException("Workspace " +
wEntry.getName() + " is not exist!");
+ }
+
+ backupManager.restoreExistingWorkspace(backupChainLog, repository, wEntry,
true);
+ }
+ else
+ {
+ if (isWorkspaceExist(repository, wEntry.getName()))
+ {
+ throw new Exception("Workspace " + wEntry.getName() + "
already exist!");
+ }
+
+ backupManager.restore(backupChainLog, repository, wEntry, true);
+ }
+
+ /*
+ * Sleeping
+ * Restore must be initialized by job thread
+ */
+
+ Thread.sleep(100);
+
+ /*
+ * search necessary restore
+ */
+
+ List<JobWorkspaceRestore> restoreJobs = backupManager.getRestores();
+ JobWorkspaceRestore restore = null;
+ for (JobWorkspaceRestore curRestore : restoreJobs)
+ {
+ if (curRestore.getRepositoryName().equals(repository)
+ && curRestore.getWorkspaceName().equals(wEntry.getName()))
+ {
+ restore = curRestore;
+ break;
+ }
+ }
+
+ if (restore != null)
+ {
+ ShortInfo info =
+ new ShortInfo(ShortInfo.RESTORE, restore.getBackupChainLog(),
restore.getStartTime(), restore
+ .getEndTime(), restore.getStateRestore(),
restore.getRepositoryName(), restore
+ .getWorkspaceName());
+ return Response.ok(info).cacheControl(noCache).build();
+ }
+
+ return Response.ok().cacheControl(noCache).build();
+ }
+ catch (WorkspaceRestoreExeption e)
+ {
+ exception = e;
+ status = Response.Status.FORBIDDEN;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (BackupLogNotFoundException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (Throwable e)
+ {
+ exception = e;
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ failMessage = e.getMessage();
+ }
+
+ log.error("Can not start restore the workspace '" + "/" +
repository + "/" + wEntry.getName()
+ + "' from backup log with id '" + backupId +
"'", exception);
+
+ return Response.status(status).entity(
+ "Can not start restore the workspace '" + "/" +
repository + "/" + wEntry.getName()
+ + "' from backup log with id '" + backupId +
"' : " + failMessage).type(MediaType.TEXT_PLAIN)
+ .cacheControl(noCache).build();
+ }
+
+ /**
+ * Restore the workspace from backup set with changing configuration
(WorkspaceEntry).
+ *
+ * @param wEntry
+ * WorkspaceEntry, the configuration to restored workspace
+ * @param repository
+ * String, the repository name
+ * @param backupSetPath
+ * String, the path to backup set
+ * @param removeExisting
+ * Boolean, if 'true' will be removed fully (db, value storage,
index) existed workspace.
+ * @return Response return the response
+ */
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @RolesAllowed("administrators")
+ @Path("/restore/backup-set/{repo}/{backup-set-path:.*}/{remove-Existing}")
+ public Response restoreBackupSet(WorkspaceEntry wEntry, @PathParam("repo")
String repository,
+ @PathParam("backup-set-path") String backupSetPath,
@PathParam("remove-Existing") Boolean removeExisting)
+ {
+ String failMessage;
+ Response.Status status;
+ Throwable exception;
+
+ try
+ {
+ validateOneRestoreInstants(repository, wEntry.getName());
+
+ File backupSetDir = (new File(backupSetPath));
+
+ if (!backupSetDir.exists())
+ {
+ throw new RestoreConfigurationException("Backup set directory is not
exists :" + backupSetPath);
+ }
+
+ if (!backupSetDir.isDirectory())
+ {
+ throw new RestoreConfigurationException("Backup set directory is not
directory :" + backupSetPath);
+ }
+
+ File[] cfs = PrivilegedFileHelper.listFiles(backupSetDir, new
BackupLogsFilter());
+
+ if (cfs.length == 0)
+ {
+ throw new RestoreConfigurationException("Can not found workspace backup
log in directory : "
+ + backupSetPath);
+ }
+
+ if (cfs.length > 1)
+ {
+ throw new RestoreConfigurationException(
+ "Backup set directory should contains only one workspace backup
log : " + backupSetPath);
+ }
+
+ validateRepositoryName(repository);
+
+ BackupChainLog backupChainLog = new BackupChainLog(cfs[0]);
+
+ if (removeExisting)
+ {
+ if (!isWorkspaceExist(repository, wEntry.getName()))
+ {
+ throw new WorkspaceRestoreException("Workspace " +
wEntry.getName() + " is not exist!");
+ }
+
+ backupManager.restoreExistingWorkspace(backupChainLog, repository, wEntry,
true);
+ }
+ else
+ {
+ if (isWorkspaceExist(repository, wEntry.getName()))
+ {
+ throw new Exception("Workspace " + wEntry.getName() + "
already exist!");
+ }
+
+ backupManager.restore(backupChainLog, repository, wEntry, true);
+ }
+
+ /*
+ * Sleeping
+ * Restore must be initialized by job thread
+ */
+
+ Thread.sleep(100);
+
+ /*
+ * search necessary restore
+ */
+
+ List<JobWorkspaceRestore> restoreJobs = backupManager.getRestores();
+ JobWorkspaceRestore restore = null;
+ for (JobWorkspaceRestore curRestore : restoreJobs)
+ {
+ if (curRestore.getRepositoryName().equals(repository)
+ && curRestore.getWorkspaceName().equals(wEntry.getName()))
+ {
+ restore = curRestore;
+ break;
+ }
+ }
+
+ if (restore != null)
+ {
+ ShortInfo info =
+ new ShortInfo(ShortInfo.RESTORE, restore.getBackupChainLog(),
restore.getStartTime(), restore
+ .getEndTime(), restore.getStateRestore(),
restore.getRepositoryName(), restore
+ .getWorkspaceName());
+ return Response.ok(info).cacheControl(noCache).build();
+ }
+
+ return Response.ok().cacheControl(noCache).build();
+ }
+ catch (WorkspaceRestoreExeption e)
+ {
+ exception = e;
+ status = Response.Status.FORBIDDEN;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (BackupLogNotFoundException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (Throwable e)
+ {
+ exception = e;
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ failMessage = e.getMessage();
+ }
+
+ log.error("Can not start restore the workspace '" + "/" +
repository + "/" + wEntry.getName()
+ + "' from backup set '" + backupSetPath +
"'", exception);
+
+ return Response.status(status).entity(
+ "Can not start restore the workspace '" + "/" +
repository + "/" + wEntry.getName()
+ + "' from backup set '" + backupSetPath +
"' : " + failMessage).type(MediaType.TEXT_PLAIN)
+ .cacheControl(noCache).build();
+ }
+
+ /**
+ * Restore the workspace with original configuration (this configuration was stored in
backup chain log).
+ *
+ * @param repository
+ * String, the repository name
+ * @param backupId
+ * String, the identifier of backup
+ * @param removeExisting
+ * Boolean, if 'true' will be removed fully (db, value storage,
index) existed workspace.
+ * @return Response return the response
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ @RolesAllowed("administrators")
+ @Path("/restore/{id}/{remove-Existing}")
+ public Response restore(@PathParam("id") String backupId,
@PathParam("remove-Existing") Boolean removeExisting)
+ {
+ String failMessage;
+ Response.Status status;
+ Throwable exception;
+
+ String repository = null;
+ String workspace = null;
+
+ try
+ {
+ File backupLog = getBackupLogbyId(backupId);
+
+ // validate backup log file
+ if (backupLog == null)
+ {
+ throw new BackupLogNotFoundException("The backup log file with id "
+ backupId + " not exists.");
+ }
+
+ BackupChainLog backupChainLog = new BackupChainLog(backupLog);
+
+ repository = backupChainLog.getBackupConfig().getRepository();
+ workspace = backupChainLog.getBackupConfig().getWorkspace();
+
+ validateOneRestoreInstants(repository, workspace);
+
+ validateRepositoryName(repository);
+
+ //workspace name and repository name should equals original names from backup
set.
+ if (!repository.equals(backupChainLog.getBackupConfig().getRepository()))
+ {
+ throw new WorkspaceRestoreException("Repository name\"" +
repository
+ + "\" should equals original repository name from backup
set : \""
+ + backupChainLog.getBackupConfig().getRepository() +
"\".");
+ }
+
+ if (!workspace.equals(backupChainLog.getBackupConfig().getWorkspace()))
+ {
+ throw new WorkspaceRestoreException("Workspace name\"" +
workspace
+ + "\" should equals original workspace name from backup
set : \""
+ + backupChainLog.getBackupConfig().getWorkspace() +
"\".");
+ }
+
+ if (removeExisting)
+ {
+ if (!isWorkspaceExist(repository, workspace))
+ {
+ throw new WorkspaceRestoreException("Workspace " + workspace +
" is not exists!");
+ }
+
+ backupManager.restoreExistingWorkspace(backupId, true);
+ }
+ else
+ {
+ if (isWorkspaceExist(repository, workspace))
+ {
+ throw new Exception("Workspace " + workspace + " already
exists!");
+ }
+
+ backupManager.restoreWorkspace(backupId, true);
+ }
+
+ /*
+ * Sleeping
+ * Restore must be initialized by job thread
+ */
+
+ Thread.sleep(100);
+
+ /*
+ * search necessary restore
+ */
+
+ List<JobWorkspaceRestore> restoreJobs = backupManager.getRestores();
+ JobWorkspaceRestore restore = null;
+ for (JobWorkspaceRestore curRestore : restoreJobs)
+ {
+ if (curRestore.getRepositoryName().equals(repository)
+ && curRestore.getWorkspaceName().equals(workspace))
+ {
+ restore = curRestore;
+ break;
+ }
+ }
+
+ if (restore != null)
+ {
+ ShortInfo info =
+ new ShortInfo(ShortInfo.RESTORE, restore.getBackupChainLog(),
restore.getStartTime(), restore
+ .getEndTime(), restore.getStateRestore(),
restore.getRepositoryName(), restore
+ .getWorkspaceName());
+ return Response.ok(info).cacheControl(noCache).build();
+ }
+
+ return Response.ok().cacheControl(noCache).build();
+ }
+ catch (WorkspaceRestoreExeption e)
+ {
+ exception = e;
+ status = Response.Status.FORBIDDEN;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (BackupLogNotFoundException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (Throwable e)
+ {
+ exception = e;
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ failMessage = e.getMessage();
+ }
+
+ log.error("Can not start restore the workspace '" + "/" +
repository + "/" + workspace
+ + "' from backup log with id '" + backupId +
"'", exception);
+
+ return Response.status(status).entity(
+ "Can not start restore the workspace '" + "/" +
repository + "/" + workspace
+ + "' from backup log with id '" + backupId +
"' : " + failMessage).type(MediaType.TEXT_PLAIN)
+ .cacheControl(noCache).build();
+ }
+
+ /**
+ * Restore the workspace or repository with original configuration (this configuration
was stored in backup log).
+ *
+ * @param backupId
+ * String, the identifier of backup
+ * @param removeExisting
+ * Boolean, if 'true' will be removed fully (db, value storage,
index) existed workspace.
+ * @return Response return the response
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ @RolesAllowed("administrators")
+ @Path("/restore/backup-set/{backup-set-path:.*}/{remove-Existing}")
+ public Response restoreFromBackupSet(@PathParam("backup-set-path") String
backupSetPath,
+ @PathParam("remove-Existing") Boolean removeExisting)
+ {
+ String failMessage = null;
+ Response.Status status = null;
+ Throwable exception = null;
+
+ File backupSetDir = (new File(backupSetPath));
+ File backuplog = null;
+
+ boolean restoreWorkspace = true;
+
+ try
+ {
+ if (!backupSetDir.exists())
+ {
+ throw new RestoreConfigurationException("Backup set directory is not
exists :" + backupSetPath);
+ }
+
+ if (!backupSetDir.isDirectory())
+ {
+ throw new RestoreConfigurationException("Backup set directory is not
directory :" + backupSetPath);
+ }
+
+ File[] cfsw = PrivilegedFileHelper.listFiles(backupSetDir, new
BackupLogsFilter());
+ File[] cfsr = PrivilegedFileHelper.listFiles(backupSetDir, new
RepositoryBackupLogsFilter());
+
+ if (cfsw.length == 0 && cfsr.length == 0)
+ {
+ throw new RestoreConfigurationException("Can not found backup log in
directory : " + backupSetPath);
+ }
+ else if ((cfsw.length == 1 && cfsr.length == 1) || (cfsw.length > 1)
|| (cfsr.length > 1))
+ {
+ throw new RestoreConfigurationException("Backup set directory should
contains only one backup log : "
+ + backupSetPath);
+ }
+ else if (cfsw.length != 0 && cfsr.length == 0)
+ {
+ restoreWorkspace = true;
+ backuplog = cfsw[0];
+ }
+ else if (cfsw.length == 0 && cfsr.length != 0)
+ {
+ restoreWorkspace = false;
+ backuplog = cfsr[0];
+ }
+
+ }
+ catch (RestoreConfigurationException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (Throwable e)
+ {
+ exception = e;
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ failMessage = e.getMessage();
+ }
+ finally
+ {
+ if (exception != null)
+ {
+ log.error("Can not start restore from backup set '" +
backupSetPath + "'", exception);
+
+ return Response.status(status).entity(
+ "Can not start restore from backup set '" +
backupSetPath + "' : " + failMessage).type(
+ MediaType.TEXT_PLAIN).cacheControl(noCache).build();
+ }
+ }
+
+ if (restoreWorkspace)
+ {
+
+ String repository = null;
+ String workspace = null;
+
+ try
+ {
+
+ BackupChainLog backupChainLog = new BackupChainLog(backuplog);
+
+ repository = backupChainLog.getBackupConfig().getRepository();
+ workspace = backupChainLog.getBackupConfig().getWorkspace();
+
+ validateOneRestoreInstants(repository, workspace);
+
+ validateRepositoryName(repository);
+
+ if (removeExisting)
+ {
+ if (!isWorkspaceExist(repository, workspace))
+ {
+ throw new WorkspaceRestoreException("Workspace " + workspace
+ " is not exists!");
+ }
+
+ backupManager.restoreExistingWorkspace(backupSetDir, true);
+ }
+ else
+ {
+ if (isWorkspaceExist(repository, workspace))
+ {
+ throw new Exception("Workspace " + workspace + " already
exists!");
+ }
+
+ backupManager.restoreWorkspace(backupSetDir, true);
+ }
+
+ /*
+ * Sleeping
+ * Restore must be initialized by job thread
+ */
+
+ Thread.sleep(100);
+
+ /*
+ * search necessary restore
+ */
+
+ List<JobWorkspaceRestore> restoreJobs = backupManager.getRestores();
+ JobWorkspaceRestore restore = null;
+ for (JobWorkspaceRestore curRestore : restoreJobs)
+ {
+ if (curRestore.getRepositoryName().equals(repository) &&
curRestore.getWorkspaceName().equals(workspace))
+ {
+ restore = curRestore;
+ break;
+ }
+ }
+
+ if (restore != null)
+ {
+ ShortInfo info =
+ new ShortInfo(ShortInfo.RESTORE, restore.getBackupChainLog(),
restore.getStartTime(), restore
+ .getEndTime(), restore.getStateRestore(),
restore.getRepositoryName(), restore
+ .getWorkspaceName());
+ return Response.ok(info).cacheControl(noCache).build();
+ }
+
+ return Response.ok().cacheControl(noCache).build();
+ }
+ catch (WorkspaceRestoreExeption e)
+ {
+ exception = e;
+ status = Response.Status.FORBIDDEN;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (BackupLogNotFoundException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (Throwable e)
+ {
+ exception = e;
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ failMessage = e.getMessage();
+ }
+
+ log.error("Can not start restore the workspace '" + "/"
+ repository + "/" + workspace
+ + "' from backup set \"" + backupSetPath +
"\"", exception);
+
+ return Response.status(status).entity(
+ "Can not start restore the workspace '" + "/" +
repository + "/" + workspace + "' from backup set \""
+ + backupSetPath + "\" : " +
failMessage).type(MediaType.TEXT_PLAIN).cacheControl(noCache)
+ .build();
+ }
+ else
+ {
+ String repository = null;
+
+ try
+ {
+
+ RepositoryBackupChainLog backupChainLog = new
RepositoryBackupChainLog(backuplog);
+ repository = backupChainLog.getBackupConfig().getRepository();
+
+ validateOneRepositoryRestoreInstants(repository);
+
+ if (removeExisting)
+ {
+ if (!isRepositoryExist(repository))
+ {
+ throw new RepositoryRestoreExeption("Repository " +
repository + " is not exists!");
+ }
+
+ backupManager.restoreExistingRepository(backupSetDir, true);
+ }
+ else
+ {
+ if (isRepositoryExist(repository))
+ {
+ throw new RepositoryRestoreExeption("Repository " +
repository + " already exists!");
+ }
+
+ backupManager.restoreRepository(backupSetDir, true);
+ }
+
+ // Sleeping. Restore should be initialized by job thread
+ Thread.sleep(100);
+
+ // search necessary restore
+ JobRepositoryRestore restore =
backupManager.getLastRepositoryRestore(repository);
+ ShortInfo info =
+ new ShortInfo(ShortInfo.RESTORE,
restore.getRepositoryBackupChainLog(), restore.getStartTime(),
+ restore.getEndTime(), restore.getStateRestore(),
restore.getRepositoryName());
+
+ return Response.ok(info).cacheControl(noCache).build();
+ }
+ catch (RepositoryRestoreExeption e)
+ {
+ exception = e;
+ status = Response.Status.FORBIDDEN;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (Throwable e)
+ {
+ exception = e;
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ failMessage = e.getMessage();
+ }
+
+ log.error("Can not start restore the repository '" + "/"
+ repository + "' from backup set '" + backupSetPath
+ + "'", exception);
+
+ return Response.status(status).entity(
+ "Can not start restore the repository '" + "/"
+ repository + "' from backup set '" + backupSetPath
+ + "' : " +
failMessage).type(MediaType.TEXT_PLAIN).cacheControl(noCache).build();
+ }
+ }
+
+ /**
* Restore the repository.
*
* @param rEntry
@@ -749,6 +1471,466 @@
}
/**
+ * Restore the repository.
+ *
+ * @param rEntry
+ * RepositoryEntry, the configuration to restored repository
+ * @param repository
+ * String, the repository name
+ * @param backupId
+ * String, the identifier of backup
+ * @param removeExisting
+ * Boolean, if 'true' will be removed fully (db, value storage,
index) existed repository.
+ * @return Response return the response
+ */
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @RolesAllowed("administrators")
+ @Path("/restore-repository/{id}/{remove-Existing}")
+ public Response restoreRepository(RepositoryEntry rEntry, @PathParam("id")
String backupId,
+ @PathParam("remove-Existing") Boolean removeExisting)
+ {
+ String failMessage;
+ Response.Status status;
+ Throwable exception;
+
+ try
+ {
+ validateOneRepositoryRestoreInstants(rEntry.getName());
+
+ File backupLog = getRepositoryBackupLogbyId(backupId);
+
+ // validate backup log file
+ if (backupLog == null)
+ {
+ throw new BackupLogNotFoundException("The repository backup log file
with id " + backupId + " not exists.");
+ }
+
+ RepositoryBackupChainLog backupChainLog = new
RepositoryBackupChainLog(backupLog);
+
+ if (removeExisting)
+ {
+ if (!isRepositoryExist(rEntry.getName()))
+ {
+ throw new RepositoryRestoreExeption("Repository " +
rEntry.getName() + " is not exists!");
+ }
+
+ backupManager.restoreExistingRepository(backupChainLog, rEntry, true);
+ }
+ else
+ {
+ if (isRepositoryExist(rEntry.getName()))
+ {
+ throw new RepositoryRestoreExeption("Repository " +
rEntry.getName() + " already exists!");
+ }
+
+ backupManager.restore(backupChainLog, rEntry, true);
+ }
+
+ // Sleeping. Restore should be initialized by job thread
+ Thread.sleep(100);
+
+ // search necessary restore
+ JobRepositoryRestore restore =
backupManager.getLastRepositoryRestore(rEntry.getName());
+ ShortInfo info =
+ new ShortInfo(ShortInfo.RESTORE, restore.getRepositoryBackupChainLog(),
restore.getStartTime(),
+ restore.getEndTime(), restore.getStateRestore(),
restore.getRepositoryName());
+
+ return Response.ok(info).cacheControl(noCache).build();
+ }
+ catch (RepositoryRestoreExeption e)
+ {
+ exception = e;
+ status = Response.Status.FORBIDDEN;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (BackupLogNotFoundException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (Throwable e)
+ {
+ exception = e;
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ failMessage = e.getMessage();
+ }
+
+ log.error("Can not start restore the repository '" + "/" +
rEntry.getName() + "' from backup log with id '"
+ + backupId + "'", exception);
+
+ return Response.status(status).entity(
+ "Can not start restore the repository '" + "/" +
rEntry.getName() + "' from backup log with id '"
+ + backupId + "' : " +
failMessage).type(MediaType.TEXT_PLAIN).cacheControl(noCache).build();
+ }
+
+ /**
+ * Restore the repository from backup set with changing configuration
(RepositoryEntry).
+ *
+ * @param rEntry
+ * RepositoryEntry, the configuration to restored repository
+ * @param repository
+ * String, the repository name
+ * @param backupSetPath
+ * String, the path to backup set
+ * @param removeExisting
+ * Boolean, if 'true' will be removed fully (db, value storage,
index) existed repository.
+ * @return Response return the response
+ */
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @RolesAllowed("administrators")
+
@Path("/restore-repository/backup-set/{backup-set-path:.*}/{remove-Existing}")
+ public Response restoreRepositoryBackupSet(RepositoryEntry rEntry,
+ @PathParam("backup-set-path") String backupSetPath,
+ @PathParam("remove-Existing") Boolean removeExisting)
+ {
+ String failMessage;
+ Response.Status status;
+ Throwable exception;
+
+ try
+ {
+ validateOneRepositoryRestoreInstants(rEntry.getName());
+
+ File backupSetDir = (new File(backupSetPath));
+
+ if (!backupSetDir.exists())
+ {
+ throw new RestoreConfigurationException("Backup set directory is not
exists :" + backupSetPath);
+ }
+
+ if (!backupSetDir.isDirectory())
+ {
+ throw new RestoreConfigurationException("Backup set directory is not
directory :" + backupSetPath);
+ }
+
+ File[] cfs = PrivilegedFileHelper.listFiles(backupSetDir, new
RepositoryBackupLogsFilter());
+
+ if (cfs.length == 0)
+ {
+ throw new RestoreConfigurationException("Can not found repository backup
log in directory : "
+ + backupSetPath);
+ }
+
+ if (cfs.length > 1)
+ {
+ throw new RestoreConfigurationException(
+ "Backup set directory should contains only one repository
backup log : " + backupSetPath);
+ }
+
+ RepositoryBackupChainLog backupChainLog = new RepositoryBackupChainLog(cfs[0]);
+
+ if (removeExisting)
+ {
+ if (!isRepositoryExist(rEntry.getName()))
+ {
+ throw new RepositoryRestoreExeption("Repository " +
rEntry.getName() + " is not exists!");
+ }
+
+ backupManager.restoreExistingRepository(backupChainLog, rEntry, true);
+ }
+ else
+ {
+ if (isRepositoryExist(rEntry.getName()))
+ {
+ throw new RepositoryRestoreExeption("Repository " +
rEntry.getName() + " already exists!");
+ }
+
+ backupManager.restore(backupChainLog, rEntry, true);
+ }
+
+ // Sleeping. Restore should be initialized by job thread
+ Thread.sleep(100);
+
+ // search necessary restore
+ JobRepositoryRestore restore =
backupManager.getLastRepositoryRestore(rEntry.getName());
+ ShortInfo info =
+ new ShortInfo(ShortInfo.RESTORE, restore.getRepositoryBackupChainLog(),
restore.getStartTime(),
+ restore.getEndTime(), restore.getStateRestore(),
restore.getRepositoryName());
+
+ return Response.ok(info).cacheControl(noCache).build();
+ }
+ catch (RepositoryRestoreExeption e)
+ {
+ exception = e;
+ status = Response.Status.FORBIDDEN;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (Throwable e)
+ {
+ exception = e;
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ failMessage = e.getMessage();
+ }
+
+ log.error("Can not start restore the repository '" + "/" +
rEntry.getName() + "' from backup set '"
+ + backupSetPath + "'", exception);
+
+ return Response.status(status).entity(
+ "Can not start restore the repository '" + "/" +
rEntry.getName() + "' from backup set '"
+ + backupSetPath + "' : " +
failMessage).type(MediaType.TEXT_PLAIN).cacheControl(noCache)
+ .build();
+ }
+
+ /**
+ * Restore the repository.
+ *
+ * @param backupId
+ * String, the identifier of backup
+ * @param removeExisting
+ * Boolean, if 'true' will be removed fully (db, value storage,
index) existed repository.
+ * @return Response return the response
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ @RolesAllowed("administrators")
+ @Path("/restore-repository/{id}/{remove-Existing}")
+ public Response restoreRepository(@PathParam("id") String backupId,
+ @PathParam("remove-Existing") Boolean removeExisting)
+ {
+ String failMessage;
+ Response.Status status;
+ Throwable exception;
+
+ String repository = null;
+
+ try
+ {
+ File backupLog = getRepositoryBackupLogbyId(backupId);
+
+ // validate backup log file
+ if (backupLog == null)
+ {
+ throw new BackupLogNotFoundException("The repository backup log file
with id " + backupId + " not exists.");
+ }
+
+ RepositoryBackupChainLog backupChainLog = new
RepositoryBackupChainLog(backupLog);
+ repository = backupChainLog.getBackupConfig().getRepository();
+
+ validateOneRepositoryRestoreInstants(repository);
+
+ if (removeExisting)
+ {
+ if (!isRepositoryExist(repository))
+ {
+ throw new RepositoryRestoreExeption("Repository " + repository +
" is not exists!");
+ }
+
+ backupManager.restoreExistingRepository(backupId, true);
+ }
+ else
+ {
+ if (isRepositoryExist(repository))
+ {
+ throw new RepositoryRestoreExeption("Repository " + repository +
" already exists!");
+ }
+
+ backupManager.restoreRepository(backupId, true);
+ }
+
+ // Sleeping. Restore should be initialized by job thread
+ Thread.sleep(100);
+
+ // search necessary restore
+ JobRepositoryRestore restore =
+ backupManager.getLastRepositoryRestore(repository);
+ ShortInfo info =
+ new ShortInfo(ShortInfo.RESTORE, restore.getRepositoryBackupChainLog(),
restore.getStartTime(),
+ restore.getEndTime(), restore.getStateRestore(),
restore.getRepositoryName());
+
+ return Response.ok(info).cacheControl(noCache).build();
+ }
+ catch (RepositoryRestoreExeption e)
+ {
+ exception = e;
+ status = Response.Status.FORBIDDEN;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (BackupLogNotFoundException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (Throwable e)
+ {
+ exception = e;
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ failMessage = e.getMessage();
+ }
+
+ log.error("Can not start restore the repository '" + "/" +
repository + "' from backup log with id '"
+ + backupId + "'", exception);
+
+ return Response.status(status).entity(
+ "Can not start restore the repository '" + "/" +
repository + "' from backup log with id '"
+ + backupId + "' : " +
failMessage).type(MediaType.TEXT_PLAIN).cacheControl(noCache).build();
+ }
+
+ /**
+ * Restore the repository.
+ *
+ * @param rEntry
+ * RepositoryEntry, the configuration to restored repository
+ * @param repository
+ * String, the repository name
+ * @param backupId
+ * String, the identifier of backup
+ * @param removeExisting
+ * Boolean, if 'true' will be removed fully (db, value storage,
index) existed repository.
+ * @return Response return the response
+ */
+ /*
+ @POST
+ @Produces(MediaType.APPLICATION_JSON)
+ @RolesAllowed("administrators")
+
@Path("/restore-repository-from-backup-set/{backup-set-path:.*}/{remove-Existing}")
+ public Response restoreRepositoryFromBackupSet(@PathParam("backup-set-path")
String backupSetPath,
+ @PathParam("remove-Existing") Boolean removeExisting)
+ {
+ String failMessage;
+ Response.Status status;
+ Throwable exception;
+
+ String repository = null;
+
+ try
+ {
+ File backupSetDir = (new File(backupSetPath));
+
+ if (!backupSetDir.exists())
+ {
+ throw new WorkspaceRestoreException("Backup set directory is not exists
:" + backupSetPath);
+ }
+
+ if (!backupSetDir.isDirectory())
+ {
+ throw new WorkspaceRestoreException("Backup set directory is not directory
:" + backupSetPath);
+ }
+
+ File[] cfs = PrivilegedFileHelper.listFiles(backupSetDir, new
RepositoryBackupLogsFilter());
+
+ if (cfs.length == 0)
+ {
+ throw new BackupConfigurationException("Can not found repository backup log
in directory : "
+ + backupSetPath);
+ }
+
+ if (cfs.length > 1)
+ {
+ throw new BackupConfigurationException(
+ "Backup set directory should contains only one repository backup
log : " + backupSetPath);
+ }
+
+ RepositoryBackupChainLog backupChainLog = new RepositoryBackupChainLog(cfs[0]);
+ repository = backupChainLog.getBackupConfig().getRepository();
+
+ validateOneRepositoryRestoreInstants(repository);
+
+ if (removeExisting)
+ {
+ if (!isRepositoryExist(repository))
+ {
+ throw new RepositoryRestoreExeption("Repository " + repository +
" is not exists!");
+ }
+
+ backupManager.restoreExistingRepository(backupSetDir, true);
+ }
+ else
+ {
+ if (isRepositoryExist(repository))
+ {
+ throw new RepositoryRestoreExeption("Repository " + repository +
" already exists!");
+ }
+
+ backupManager.restoreRepository(backupSetDir, true);
+ }
+
+ // Sleeping. Restore should be initialized by job thread
+ Thread.sleep(100);
+
+ // search necessary restore
+ JobRepositoryRestore restore = backupManager.getLastRepositoryRestore(repository);
+ ShortInfo info =
+ new ShortInfo(ShortInfo.RESTORE, restore.getRepositoryBackupChainLog(),
restore.getStartTime(),
+ restore.getEndTime(), restore.getStateRestore(),
restore.getRepositoryName());
+
+ return Response.ok(info).cacheControl(noCache).build();
+ }
+ catch (RepositoryRestoreExeption e)
+ {
+ exception = e;
+ status = Response.Status.FORBIDDEN;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (RepositoryConfigurationException e)
+ {
+ exception = e;
+ status = Response.Status.NOT_FOUND;
+ failMessage = e.getMessage();
+ }
+ catch (Throwable e)
+ {
+ exception = e;
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ failMessage = e.getMessage();
+ }
+
+ log.error("Can not start restore the repository '" + "/" +
repository + "' from backup set '" + backupSetPath
+ + "'", exception);
+
+ return Response.status(status).entity(
+ "Can not start restore the repository '" + "/" +
repository + "' from backup set '" + backupSetPath
+ + "' : " +
failMessage).type(MediaType.TEXT_PLAIN).cacheControl(noCache).build();
+ }*/
+
+ /**
* The backup stop by 'id'.
*
* @param backupId
Modified:
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/AbstractBackupUseCasesTest.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/AbstractBackupUseCasesTest.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/AbstractBackupUseCasesTest.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -47,9 +47,11 @@
extends AbstractBackupTestCase
{
+ private static volatile long uuIndex;
+
protected static synchronized long getUUIndex()
{
- return System.currentTimeMillis();
+ return uuIndex++;
}
public void testFullBackupRestore() throws Exception
@@ -84,7 +86,8 @@
fail("Can't get fullBackup chain");
// restore
- RepositoryEntry re =
(RepositoryEntry)ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
+ RepositoryEntry re =
+ (RepositoryEntry)
ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
WorkspaceEntry ws1back = makeWorkspaceEntry(workspaceNameToRestore,
dataSourceToWorkspaceRestore);
// BackupChainLog bchLog = new BackupChainLog(backDir, rconfig);
@@ -102,10 +105,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)getReposityToBackup().login(credentials,
workspaceNameToRestore);
+ back1 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToRestore);
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -162,7 +165,8 @@
fail("Can't get fullBackup chain");
// restore
- RepositoryEntry re =
(RepositoryEntry)ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
+ RepositoryEntry re =
+ (RepositoryEntry)
ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
WorkspaceEntry ws1back = makeWorkspaceEntry(workspaceNameToRestore,
dataSourceToWorkspaceRestore);
File backLog = new File(bch.getLogFilePath());
@@ -179,16 +183,16 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)getReposityToBackup().login(credentials,
workspaceNameToRestore);
+ back1 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToRestore);
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
assertFalse("Node should be removed",
ws1backTestRoot.hasNode("node_3"));
assertFalse("Node should be removed",
ws1backTestRoot.hasNode("node_4"));
assertFalse("Node should be removed",
ws1backTestRoot.hasNode("node_5"));
assertEquals("Restored content should be same", "property
#3", ws1backTestRoot.getNode("node #3")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
assertEquals("Restored content should be same", "property
#5", ws1backTestRoot.getNode("node #5")
- .getProperty("exo:extraData").getString());
+ .getProperty("exo:extraData").getString());
assertFalse("Proeprty should be removed",
ws1backTestRoot.getNode("node #5").hasProperty("exo:data"));
}
@@ -250,7 +254,7 @@
ws1TestRoot.addNode("node_102").setProperty("exo:data", new
FileInputStream(tempf));
ws1TestRoot.save(); // log here via listener
- ws1TestRoot.getNode("node_2").setProperty("exo:data",
(Value)null); // remove property
+ ws1TestRoot.getNode("node_2").setProperty("exo:data", (Value)
null); // remove property
ws1TestRoot.getNode("node_3").setProperty("exo:data", new
ByteArrayInputStream("aaa".getBytes())); // set
// aaa
// bytes
@@ -261,7 +265,7 @@
ws1TestRoot.save(); // log here via listener
Lock n107lock = ws1TestRoot.getNode("node_5").lock(true, false);
ws1TestRoot.getSession().move(ws1TestRoot.getNode("node #53").getPath(),
- ws1TestRoot.getNode("node_5").getPath() + "/node #53");
+ ws1TestRoot.getNode("node_5").getPath() + "/node
#53");
ws1TestRoot.save(); // log here via listener
ws1TestRoot.getNode("node_6").addMixin("mix:referenceable");
@@ -269,8 +273,8 @@
ws1TestRoot.save(); // log here via listener
// before(*), log here via listener
- ws1TestRoot.getSession().getWorkspace()
- .move(ws1TestRoot.getNode("node_6").getPath(), ws1TestRoot.getPath() +
"/node_4"); // in place of
+
ws1TestRoot.getSession().getWorkspace().move(ws1TestRoot.getNode("node_6").getPath(),
+ ws1TestRoot.getPath() + "/node_4"); // in place of
// 4 removed
// stop all
@@ -280,7 +284,8 @@
fail("Can't get fullBackup chain");
// restore
- RepositoryEntry re =
(RepositoryEntry)ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
+ RepositoryEntry re =
+ (RepositoryEntry)
ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
WorkspaceEntry ws1back = makeWorkspaceEntry(workspaceNameToRestore,
dataSourceToWorkspaceRestore);
File backLog = new File(bch.getLogFilePath());
@@ -297,12 +302,12 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)getReposityToBackup().login(credentials,
workspaceNameToRestore);
+ back1 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToRestore);
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
assertTrue("Node should exists",
ws1backTestRoot.getNode("node_5").hasNode("node #53"));
assertTrue("Property should exists",
ws1backTestRoot.getNode("node_5")
- .hasProperty("node #53/exo:extraData"));
+ .hasProperty("node #53/exo:extraData"));
assertTrue("Node should exists",
ws1backTestRoot.hasNode("node_7"));
assertTrue("Property should exists",
ws1backTestRoot.hasProperty("node_5/exo:data"));
@@ -310,20 +315,20 @@
assertTrue("Node should exists",
ws1backTestRoot.hasNode("node_102"));
compareStream(new FileInputStream(tempf),
ws1backTestRoot.getNode("node_5").getProperty("exo:data")
- .getStream());
+ .getStream());
compareStream(new FileInputStream(tempf),
ws1backTestRoot.getNode("node_1").getProperty("exo:extraData")
- .getStream());
+ .getStream());
assertFalse("Property should be removed",
ws1backTestRoot.getNode("node_2").hasProperty("exo:data"));
- compareStream(new ByteArrayInputStream("aaa".getBytes()),
-
ws1backTestRoot.getNode("node_3").getProperty("exo:data").getStream());
+ compareStream(new ByteArrayInputStream("aaa".getBytes()),
ws1backTestRoot.getNode("node_3").getProperty(
+ "exo:data").getStream());
assertTrue("Node should be mix:lockable ",
ws1backTestRoot.getNode("node_5").isNodeType("mix:lockable"));
assertFalse("Node should be not locked ",
ws1backTestRoot.getNode("node_5").isLocked());
- assertEquals("Node should be mix:referenceable and UUID should be "
+ id6, id6,
- ws1backTestRoot.getNode("node_4").getUUID());
+ assertEquals("Node should be mix:referenceable and UUID should be "
+ id6, id6, ws1backTestRoot.getNode(
+ "node_4").getUUID());
}
catch (Exception e)
{
@@ -342,9 +347,9 @@
public void testFullBackupRestoreAsync() throws Exception
{
- SessionImpl sessionWS1 = (SessionImpl)getReposityToBackup().login(credentials,
workspaceNameToBackup);
-
sessionWS1.getRootNode().getNode("backupTest").getNode("node_5")
- .setProperty("exo:data", "Restored content should be
same");
+ SessionImpl sessionWS1 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToBackup);
+
sessionWS1.getRootNode().getNode("backupTest").getNode("node_5").setProperty("exo:data",
+ "Restored content should be same");
sessionWS1.save();
// backup
@@ -390,23 +395,23 @@
backup.restore(bchLog, repositoryNameToBackup, ws1back, true);
while (backup.getLastRestore(repositoryNameToBackup,
workspaceNameToRestore).getStateRestore() != JobWorkspaceRestore.RESTORE_SUCCESSFUL
- && backup.getLastRestore(repositoryNameToBackup,
workspaceNameToRestore).getStateRestore() != JobWorkspaceRestore.RESTORE_FAIL)
+ && backup.getLastRestore(repositoryNameToBackup,
workspaceNameToRestore).getStateRestore() != JobWorkspaceRestore.RESTORE_FAIL)
{
Thread.sleep(50);
}
if (backup.getLastRestore(repositoryNameToBackup,
workspaceNameToRestore).getStateRestore() == JobWorkspaceRestore.RESTORE_FAIL)
- throw (Exception)backup.getLastRestore(repositoryNameToBackup,
workspaceNameToRestore)
- .getRestoreException();
+ throw (Exception) backup.getLastRestore(repositoryNameToBackup,
workspaceNameToRestore)
+ .getRestoreException();
// check
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)getReposityToBackup().login(credentials,
workspaceNameToRestore);
+ back1 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToRestore);
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
- assertEquals("Restored content should be same", "Restored
content should be same",
-
ws1backTestRoot.getNode("node_5").getProperty("exo:data").getString());
+ assertEquals("Restored content should be same", "Restored
content should be same", ws1backTestRoot.getNode(
+ "node_5").getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -517,10 +522,10 @@
public void testTwoRestores() throws Exception
{
{
- SessionImpl sessionWS1 = (SessionImpl)getReposityToBackup().login(credentials,
workspaceNameToBackup);
+ SessionImpl sessionWS1 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToBackup);
- sessionWS1.getRootNode().addNode("asdasdasda",
"nt:unstructured")
- .setProperty("data", new
FileInputStream(createBLOBTempFile(1024)));
+ sessionWS1.getRootNode().addNode("asdasdasda",
"nt:unstructured").setProperty("data",
+ new FileInputStream(createBLOBTempFile(1024)));
sessionWS1.save();
// 1-st backup
@@ -553,12 +558,12 @@
backup.restore(bchLog, repositoryNameToBackup, ws1_restore_1, false);
// check
- SessionImpl back1 = (SessionImpl)getReposityToBackup().login(credentials,
workspaceNameToRestore);
+ SessionImpl back1 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToRestore);
assertNotNull(back1.getRootNode().getNode("asdasdasda").getProperty("data"));
// add date to restored workspace
- back1.getRootNode().addNode("gdfgrghfhf",
"nt:unstructured")
- .setProperty("data", new
FileInputStream(createBLOBTempFile(1024)));
+ back1.getRootNode().addNode("gdfgrghfhf",
"nt:unstructured").setProperty("data",
+ new FileInputStream(createBLOBTempFile(1024)));
back1.save();
}
else
@@ -598,7 +603,7 @@
backup.restore(bchLog, repositoryNameToBackup, ws1_restore_2, false);
// check
- SessionImpl back2 = (SessionImpl)getReposityToBackup().login(credentials,
workspaceNameToRestore);
+ SessionImpl back2 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToRestore);
assertNotNull(back2.getRootNode().getNode("gdfgrghfhf").getProperty("data"));
}
else
@@ -713,7 +718,8 @@
fail("Can't get fullBackup chain");
// restore
- RepositoryEntry re =
(RepositoryEntry)ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
+ RepositoryEntry re =
+ (RepositoryEntry)
ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
WorkspaceEntry ws1back = makeWorkspaceEntry(workspaceNameToRestore,
dataSourceToWorkspaceRestore + "NOT_EXIST");
File backLog = new File(bch.getLogFilePath());
@@ -739,10 +745,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)getReposityToBackup().login(credentials,
workspaceNameToRestore);
+ back1 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToRestore);
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -788,8 +794,8 @@
// restore
RepositoryEntry newRepositoryEntry =
- makeRepositoryEntry(repositoryNameToRestore,
getReposityToBackup().getConfiguration(),
- dataSourceToRepositoryRestore, null);
+ makeRepositoryEntry(repositoryNameToRestore,
getReposityToBackup().getConfiguration(),
+ dataSourceToRepositoryRestore, null);
File backLog = new File(bch.getLogFilePath());
if (backLog.exists())
@@ -800,8 +806,8 @@
assertNotNull(bchLog.getFinishedTime());
backup.restore(bchLog, newRepositoryEntry, false);
- assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
-
backup.getLastRepositoryRestore(newRepositoryEntry.getName()).getStateRestore());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
backup.getLastRepositoryRestore(
+ newRepositoryEntry.getName()).getStateRestore());
// check
ManageableRepository restoredRepository =
repositoryService.getRepository(repositoryNameToRestore);
@@ -811,10 +817,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)restoredRepository.login(credentials, wsName);
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -862,8 +868,8 @@
// restore
RepositoryEntry newRepositoryEntry =
- makeRepositoryEntry(repositoryNameToRestore,
getReposityToBackup().getConfiguration(),
- dataSourceToRepositoryRestore, null);
+ makeRepositoryEntry(repositoryNameToRestore,
getReposityToBackup().getConfiguration(),
+ dataSourceToRepositoryRestore, null);
File backLog = new File(bch.getLogFilePath());
if (backLog.exists())
@@ -883,10 +889,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)restoredRepository.login(credentials, wsName);
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -905,7 +911,7 @@
}
public void testRepositoryFullBackupAsynchronusRestore() throws Exception
- {
+ {
// backup
File backDir = new File("target/backup/" + getUUIndex());
backDir.mkdirs();
@@ -933,8 +939,8 @@
// restore
RepositoryEntry newRepositoryEntry =
- makeRepositoryEntry(repositoryNameToRestore,
getReposityToBackup().getConfiguration(),
- dataSourceToRepositoryRestore, null);
+ makeRepositoryEntry(repositoryNameToRestore,
getReposityToBackup().getConfiguration(),
+ dataSourceToRepositoryRestore, null);
File backLog = new File(bch.getLogFilePath());
if (backLog.exists())
@@ -949,7 +955,7 @@
JobRepositoryRestore job =
backup.getLastRepositoryRestore(repositoryNameToRestore);
while (job.getStateRestore() !=
JobRepositoryRestore.REPOSITORY_RESTORE_SUCCESSFUL
- || job.getStateRestore() == JobRepositoryRestore.REPOSITORY_RESTORE_FAIL)
+ || job.getStateRestore() ==
JobRepositoryRestore.REPOSITORY_RESTORE_FAIL)
{
Thread.yield();
Thread.sleep(50);
@@ -963,10 +969,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)restoredRepository.login(credentials, wsName);
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -982,7 +988,7 @@
}
else
fail("There are no backup files in " + backDir.getAbsolutePath());
- }
+ }
public void testRepositoryFullBackupAsynchronusRestoreWorkspaceMapping() throws
Exception
{
@@ -1009,12 +1015,12 @@
// stop fullBackup
- backup.stopBackup(bch);
+ backup.stopBackup(bch);
// restore
RepositoryEntry newRepositoryEntry =
- makeRepositoryEntry(repositoryNameToRestore,
getReposityToBackup().getConfiguration(),
- dataSourceToRepositoryRestore, null);
+ makeRepositoryEntry(repositoryNameToRestore,
getReposityToBackup().getConfiguration(),
+ dataSourceToRepositoryRestore, null);
// create workspace mappingS
Map<String, String> workspaceMapping = new HashedMap();
@@ -1049,7 +1055,7 @@
JobRepositoryRestore job =
backup.getLastRepositoryRestore(repositoryNameToRestore);
while (job.getStateRestore() !=
JobRepositoryRestore.REPOSITORY_RESTORE_SUCCESSFUL
- || job.getStateRestore() == JobRepositoryRestore.REPOSITORY_RESTORE_FAIL)
+ || job.getStateRestore() ==
JobRepositoryRestore.REPOSITORY_RESTORE_FAIL)
{
Thread.yield();
Thread.sleep(50);
@@ -1063,10 +1069,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)restoredRepository.login(credentials,
workspaceMapping.get(wsName));
+ back1 = (SessionImpl) restoredRepository.login(credentials,
workspaceMapping.get(wsName));
Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -1085,7 +1091,7 @@
}
public void testAutoStopRepositoryBackupIncrRepetion() throws Exception
- {
+ {
// backup
File backDir = new File("target/backup/" + getUUIndex());
backDir.mkdirs();
@@ -1100,20 +1106,20 @@
final RepositoryBackupChain bch = backup.startBackup(config);
while (!bch.isFinished())
- {
+ {
Thread.yield();
Thread.sleep(50);
- }
+ }
Thread.sleep(5000);
for (RepositoryBackupChain chain : backup.getCurrentRepositoryBackups())
if (bch.getBackupId().equals(chain.getBackupId()))
fail("The backup with id '" + chain.getBackupId() + "'
should not be active");
- }
+ }
public void testRepositoryRestoreFail() throws Exception
- {
+ {
// backup
File backDir = new File("target/backup/" + getUUIndex());
backDir.mkdirs();
@@ -1144,7 +1150,8 @@
// restore
RepositoryEntry newRepositoryEntry =
- makeRepositoryEntry(repoName, getReposityToBackup().getConfiguration(),
dataSourceToRepositoryRestore, null);
+ makeRepositoryEntry(repoName, getReposityToBackup().getConfiguration(),
dataSourceToRepositoryRestore,
+ null);
//create broken system workspaceEntry
newRepositoryEntry.getWorkspaceEntries().get(0).getQueryHandler().setType("gg");
@@ -1164,8 +1171,8 @@
}
// check
- try
- {
+ try
+ {
ManageableRepository restoredRepository =
repositoryService.getRepository(repoName);
fail("The repository " + repositoryNameToRestore + "shoulde not
exists.");
}
@@ -1202,7 +1209,7 @@
{
Thread.yield();
Thread.sleep(50);
- }
+ }
// add data
ws1Session.getRootNode().addNode("node_101").setProperty("exo:data",
new FileInputStream(tempf));
@@ -1225,7 +1232,7 @@
File backLog = new File(bch.getLogFilePath());
if (backLog.exists())
- {
+ {
BackupChainLog bchLog = new BackupChainLog(backLog);
assertNotNull(bchLog.getStartedTime());
@@ -1237,7 +1244,7 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)getReposityToBackup().login(credentials,
workspaceNameToRestore);
+ back1 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToRestore);
Node node_101 = back1.getRootNode().getNode("node_101");
assertNotNull(node_101);
@@ -1260,10 +1267,10 @@
if (back1 != null)
back1.logout();
}
- }
+ }
else
fail("There are no backup files in " + backDir.getAbsolutePath());
- }
+ }
public void testExistedWorkspaceRestoreMultiDB() throws Exception
{
@@ -1299,7 +1306,8 @@
fail("Can't get fullBackup chain");
// restore
- RepositoryEntry re =
(RepositoryEntry)ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
+ RepositoryEntry re =
+ (RepositoryEntry)
ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
WorkspaceEntry ws1 = null;
for (WorkspaceEntry we : re.getWorkspaceEntries())
{
@@ -1334,7 +1342,7 @@
public void testExistedWorkspaceRestore() throws Exception
{
- SessionImpl ws1Session =
(SessionImpl)repositoryService.getRepository("db7").login(credentials,
"ws1");
+ SessionImpl ws1Session = (SessionImpl)
repositoryService.getRepository("db7").login(credentials, "ws1");
// backup
File backDir = new File("target/backup/" + getUUIndex());
@@ -1366,7 +1374,8 @@
fail("Can't get fullBackup chain");
// restore
- RepositoryEntry re =
(RepositoryEntry)ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
+ RepositoryEntry re =
+ (RepositoryEntry)
ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
WorkspaceEntry ws1 = null;
for (WorkspaceEntry we : re.getWorkspaceEntries())
{
@@ -1391,10 +1400,10 @@
SessionImpl back1 = null;
try
{
- back1 =
(SessionImpl)repositoryService.getRepository("db7").login(credentials,
"ws1");
+ back1 = (SessionImpl)
repositoryService.getRepository("db7").login(credentials, "ws1");
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -1443,7 +1452,8 @@
fail("Can't get fullBackup chain");
// restore
- RepositoryEntry re =
(RepositoryEntry)ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
+ RepositoryEntry re =
+ (RepositoryEntry)
ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
WorkspaceEntry ws1 = null;
for (WorkspaceEntry we : re.getWorkspaceEntries())
{
@@ -1465,7 +1475,7 @@
backup.restoreExistingWorkspace(bchLog, repositoryNameToBackup, ws1, true);
while (backup.getLastRestore(repositoryNameToBackup,
ws1.getName()).getStateRestore() != JobWorkspaceRestore.RESTORE_SUCCESSFUL
- && backup.getLastRestore(repositoryNameToBackup,
ws1.getName()).getStateRestore() != JobWorkspaceRestore.RESTORE_FAIL)
+ && backup.getLastRestore(repositoryNameToBackup,
ws1.getName()).getStateRestore() != JobWorkspaceRestore.RESTORE_FAIL)
{
Thread.sleep(50);
}
@@ -1475,11 +1485,11 @@
try
{
back1 =
-
(SessionImpl)repositoryService.getRepository(repositoryNameToBackup).login(credentials,
- workspaceNameToBackup);
+ (SessionImpl)
repositoryService.getRepository(repositoryNameToBackup).login(credentials,
+ workspaceNameToBackup);
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -1529,7 +1539,8 @@
fail("Can't get fullBackup chain");
// restore
- RepositoryEntry re =
(RepositoryEntry)ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
+ RepositoryEntry re =
+ (RepositoryEntry)
ws1Session.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
WorkspaceEntry ws1 = null;
for (WorkspaceEntry we : re.getWorkspaceEntries())
{
@@ -1551,7 +1562,7 @@
backup.restoreExistingWorkspace(bchLog.getBackupId(), repositoryNameToBackup,
ws1, true);
while (backup.getLastRestore(repositoryNameToBackup,
ws1.getName()).getStateRestore() != JobWorkspaceRestore.RESTORE_SUCCESSFUL
- && backup.getLastRestore(repositoryNameToBackup,
ws1.getName()).getStateRestore() != JobWorkspaceRestore.RESTORE_FAIL)
+ && backup.getLastRestore(repositoryNameToBackup,
ws1.getName()).getStateRestore() != JobWorkspaceRestore.RESTORE_FAIL)
{
Thread.sleep(50);
}
@@ -1561,11 +1572,11 @@
try
{
back1 =
-
(SessionImpl)repositoryService.getRepository(repositoryNameToBackup).login(credentials,
- workspaceNameToBackup);
+ (SessionImpl)
repositoryService.getRepository(repositoryNameToBackup).login(credentials,
+ workspaceNameToBackup);
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -1611,7 +1622,7 @@
// restore
RepositoryEntry re =
- makeRepositoryEntry(repositoryNameToBackup,
getReposityToBackup().getConfiguration(), null, null);
+ makeRepositoryEntry(repositoryNameToBackup,
getReposityToBackup().getConfiguration(), null, null);
File backLog = new File(bch.getLogFilePath());
if (backLog.exists())
@@ -1624,7 +1635,7 @@
backup.restoreExistingRepository(bchLog, re, false);
assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
backup.getLastRepositoryRestore(repositoryNameToBackup)
- .getStateRestore());
+ .getStateRestore());
// check
ManageableRepository restoredRepository =
repositoryService.getRepository(repositoryNameToBackup);
@@ -1634,10 +1645,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)restoredRepository.login(credentials, wsName);
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -1657,8 +1668,8 @@
public void testExistedRepositoryRestoreSingelDB() throws Exception
{
- RepositoryImpl repositoryDB7 =
(RepositoryImpl)repositoryService.getRepository(repositoryNameToBackupSingleDB);
- SessionImpl sessionWS = (SessionImpl)repositoryDB7.login(credentials,
workspaceNameToBackup);
+ RepositoryImpl repositoryDB7 = (RepositoryImpl)
repositoryService.getRepository(repositoryNameToBackupSingleDB);
+ SessionImpl sessionWS = (SessionImpl) repositoryDB7.login(credentials,
workspaceNameToBackup);
// backup
File backDir = new File("target/backup/" + getUUIndex());
@@ -1687,7 +1698,7 @@
// restore
RepositoryEntry baseRE =
-
(RepositoryEntry)sessionWS.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
+ (RepositoryEntry)
sessionWS.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
RepositoryEntry re = makeRepositoryEntry(baseRE.getName(), baseRE, null, null);
File backLog = new File(bch.getLogFilePath());
@@ -1701,7 +1712,7 @@
backup.restoreExistingRepository(bchLog, re, false);
assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
backup.getLastRepositoryRestore(re.getName())
- .getStateRestore());
+ .getStateRestore());
// check
ManageableRepository restoredRepository =
repositoryService.getRepository(repositoryNameToBackupSingleDB);
@@ -1711,10 +1722,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)restoredRepository.login(credentials, wsName);
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -1761,7 +1772,7 @@
// restore
RepositoryEntry re =
- makeRepositoryEntry(repositoryNameToBackup,
getReposityToBackup().getConfiguration(), null, null);
+ makeRepositoryEntry(repositoryNameToBackup,
getReposityToBackup().getConfiguration(), null, null);
File backLog = new File(bch.getLogFilePath());
if (backLog.exists())
@@ -1776,13 +1787,13 @@
JobRepositoryRestore job =
backup.getLastRepositoryRestore(repositoryNameToBackup);
while (job.getStateRestore() !=
JobRepositoryRestore.REPOSITORY_RESTORE_SUCCESSFUL
- && job.getStateRestore() !=
JobRepositoryRestore.REPOSITORY_RESTORE_FAIL)
+ && job.getStateRestore() !=
JobRepositoryRestore.REPOSITORY_RESTORE_FAIL)
{
Thread.sleep(50);
}
- assertEquals(JobRepositoryRestore.REPOSITORY_RESTORE_SUCCESSFUL,
- backup.getLastRepositoryRestore(repositoryNameToBackup).getStateRestore());
+ assertEquals(JobRepositoryRestore.REPOSITORY_RESTORE_SUCCESSFUL,
backup.getLastRepositoryRestore(
+ repositoryNameToBackup).getStateRestore());
// check
ManageableRepository restoredRepository =
repositoryService.getRepository(repositoryNameToBackup);
@@ -1792,10 +1803,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)restoredRepository.login(credentials, wsName);
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -1842,7 +1853,7 @@
// restore
RepositoryEntry re =
- makeRepositoryEntry(repositoryNameToBackup,
getReposityToBackup().getConfiguration(), null, null);
+ makeRepositoryEntry(repositoryNameToBackup,
getReposityToBackup().getConfiguration(), null, null);
File backLog = new File(bch.getLogFilePath());
if (backLog.exists())
@@ -1857,13 +1868,13 @@
JobRepositoryRestore job =
backup.getLastRepositoryRestore(repositoryNameToBackup);
while (job.getStateRestore() !=
JobRepositoryRestore.REPOSITORY_RESTORE_SUCCESSFUL
- && job.getStateRestore() !=
JobRepositoryRestore.REPOSITORY_RESTORE_FAIL)
+ && job.getStateRestore() !=
JobRepositoryRestore.REPOSITORY_RESTORE_FAIL)
{
Thread.sleep(50);
}
assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
backup.getLastRepositoryRestore(repositoryNameToBackup)
- .getStateRestore());
+ .getStateRestore());
// check
ManageableRepository restoredRepository =
repositoryService.getRepository(repositoryNameToBackup);
@@ -1873,10 +1884,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)restoredRepository.login(credentials, wsName);
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -1896,8 +1907,8 @@
public void testExistedWorkspaceRestoreSingelDB() throws Exception
{
- RepositoryImpl repositoryDB7 =
(RepositoryImpl)repositoryService.getRepository(repositoryNameToBackupSingleDB);
- SessionImpl sessionWS = (SessionImpl)repositoryDB7.login(credentials,
workspaceNameToBackup);
+ RepositoryImpl repositoryDB7 = (RepositoryImpl)
repositoryService.getRepository(repositoryNameToBackupSingleDB);
+ SessionImpl sessionWS = (SessionImpl) repositoryDB7.login(credentials,
workspaceNameToBackup);
// backup
File backDir = new File("target/backup/" + getUUIndex());
@@ -1929,7 +1940,7 @@
fail("Can't get fullBackup chain");
// restore
- RepositoryEntry re =
(RepositoryEntry)sessionWS.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
+ RepositoryEntry re = (RepositoryEntry)
sessionWS.getContainer().getComponentInstanceOfType(RepositoryEntry.class);
WorkspaceEntry ws1 = null;
for (WorkspaceEntry we : re.getWorkspaceEntries())
{
@@ -1954,11 +1965,11 @@
SessionImpl back1 = null;
try
{
- repositoryDB7 =
(RepositoryImpl)repositoryService.getRepository(repositoryNameToBackupSingleDB);
- back1 = (SessionImpl)repositoryDB7.login(credentials,
workspaceNameToBackup);
+ repositoryDB7 = (RepositoryImpl)
repositoryService.getRepository(repositoryNameToBackupSingleDB);
+ back1 = (SessionImpl) repositoryDB7.login(credentials,
workspaceNameToBackup);
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -2022,11 +2033,11 @@
try
{
back1 =
-
(SessionImpl)repositoryService.getRepository(repositoryNameToBackup).login(credentials,
- workspaceNameToBackup);
+ (SessionImpl)
repositoryService.getRepository(repositoryNameToBackup).login(credentials,
+ workspaceNameToBackup);
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -2084,7 +2095,7 @@
backup.restoreExistingRepository(bchLog.getBackupId(), false);
assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
backup.getLastRepositoryRestore(repositoryNameToBackup)
- .getStateRestore());
+ .getStateRestore());
// check
ManageableRepository restoredRepository =
repositoryService.getRepository(repositoryNameToBackup);
@@ -2094,10 +2105,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)restoredRepository.login(credentials, wsName);
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -2164,10 +2175,10 @@
SessionImpl back1 = null;
try
{
- back1 =
(SessionImpl)repositoryService.getRepository(repositoryNameToBackup).login(credentials,
"ws1");
+ back1 = (SessionImpl)
repositoryService.getRepository(repositoryNameToBackup).login(credentials,
"ws1");
Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -2227,7 +2238,7 @@
backup.restoreRepository(bchLog.getBackupId(), false);
assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
backup.getLastRepositoryRestore(repositoryNameToBackup)
- .getStateRestore());
+ .getStateRestore());
// check
ManageableRepository restoredRepository =
repositoryService.getRepository(repositoryNameToBackup);
@@ -2237,10 +2248,10 @@
SessionImpl back1 = null;
try
{
- back1 = (SessionImpl)restoredRepository.login(credentials, wsName);
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
- .getProperty("exo:data").getString());
+ .getProperty("exo:data").getString());
}
catch (Exception e)
{
@@ -2257,4 +2268,438 @@
else
fail("There are no backup files in " + backDir.getAbsolutePath());
}
+
+ public void testRepositoryRestoreWithNullConfig() throws Exception
+ {
+ // backup
+ File backDir = new File((File.createTempFile("12123",
"123")).getParent() + File.separator + getUUIndex());
+ backDir.mkdirs();
+
+ RepositoryBackupConfig config = new RepositoryBackupConfig();
+ config.setRepository(repositoryNameToBackup);
+ config.setBackupType(BackupManager.FULL_BACKUP_ONLY);
+
+ config.setBackupDir(backDir);
+
+ backup.startBackup(config);
+
+ RepositoryBackupChain bch = backup.findRepositoryBackup(repositoryNameToBackup);
+
+ // wait till full backup will be stopped
+ while (bch.getState() != RepositoryBackupChain.FINISHED)
+ {
+ Thread.yield();
+ Thread.sleep(50);
+ }
+
+ // stop fullBackup
+
+ backup.stopBackup(bch);
+
+ //TODO
+ super.tearDown();
+ removeRepositoryFully(repositoryNameToBackup);
+
+ // restore
+ File backLog = new File(bch.getLogFilePath());
+ if (backLog.exists())
+ {
+ RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog);
+
+ assertNotNull(bchLog.getStartedTime());
+ assertNotNull(bchLog.getFinishedTime());
+
+ backup.restore(bchLog, null, false);
+
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
backup.getLastRepositoryRestore(repositoryNameToBackup)
+ .getStateRestore());
+
+ // check
+ ManageableRepository restoredRepository =
repositoryService.getRepository(repositoryNameToBackup);
+
+ for (String wsName : restoredRepository.getWorkspaceNames())
+ {
+ SessionImpl back1 = null;
+ try
+ {
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
+ Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
+ assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
+ .getProperty("exo:data").getString());
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ finally
+ {
+ if (back1 != null)
+ back1.logout();
+ }
+ }
+ }
+ else
+ fail("There are no backup files in " + backDir.getAbsolutePath());
+ }
+
+ /*public void testWorkspaceRestoreWithNullConfig() throws Exception
+ {
+ // backup
+ File backDir = new File("target/backup/" + getUUIndex());
+ backDir.mkdirs();
+
+ BackupConfig config = new BackupConfig();
+ config.setRepository(repositoryNameToBackup);
+ config.setWorkspace(workspaceNameToBackup);
+ config.setBackupType(BackupManager.FULL_BACKUP_ONLY);
+
+ config.setBackupDir(backDir);
+
+ backup.startBackup(config);
+
+ BackupChain bch = backup.findBackup(repositoryNameToBackup,
workspaceNameToBackup);
+
+ // wait till full backup will be stopped
+ while (bch.getFullBackupState() != BackupJob.FINISHED)
+ {
+ Thread.yield();
+ Thread.sleep(50);
+ }
+
+ // stop fullBackup
+
+ if (bch != null)
+ backup.stopBackup(bch);
+ else
+ fail("Can't get fullBackup chain");
+
+ //TODO
+ super.tearDown();
+ removeWorkspaceFully(repositoryNameToBackup, workspaceNameToBackup);
+
+ File backLog = new File(bch.getLogFilePath());
+ if (backLog.exists())
+ {
+ BackupChainLog bchLog = new BackupChainLog(backLog);
+
+ assertNotNull(bchLog.getStartedTime());
+ assertNotNull(bchLog.getFinishedTime());
+
+ try
+ {
+ backup.restore(bchLog, repositoryNameToBackup + "not_exists", null,
false);
+ fail("Should be throw exception WorkspaceRestoreException");
+ }
+ catch (WorkspaceRestoreException e)
+ {
+ //ok
+ }
+
+ backup.restore(bchLog, repositoryNameToBackup, null, false);
+
+ // check
+ SessionImpl back1 = null;
+ try
+ {
+ back1 = (SessionImpl) getReposityToBackup().login(credentials,
"ws1");
+ Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
+ assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
+ .getProperty("exo:data").getString());
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ finally
+ {
+ if (back1 != null)
+ back1.logout();
+ }
+ }
+ else
+ fail("There are no backup files in " + backDir.getAbsolutePath());
+ }*/
+
+ public void testExistedWorkspaceRestoreWithConfigBackupSetDir() throws Exception
+ {
+ // backup
+ File backDir = new File("target/backup/" + getUUIndex());
+ backDir.mkdirs();
+
+ BackupConfig config = new BackupConfig();
+ config.setRepository(repositoryNameToBackup);
+ config.setWorkspace(workspaceNameToBackup);
+ config.setBackupType(BackupManager.FULL_BACKUP_ONLY);
+
+ config.setBackupDir(backDir);
+
+ backup.startBackup(config);
+
+ BackupChain bch = backup.findBackup(repositoryNameToBackup,
workspaceNameToBackup);
+
+ // wait till full backup will be stopped
+ while (bch.getFullBackupState() != BackupJob.FINISHED)
+ {
+ Thread.yield();
+ Thread.sleep(50);
+ }
+
+ // stop fullBackup
+ if (bch != null)
+ backup.stopBackup(bch);
+ else
+ fail("Can't get fullBackup chain");
+
+ super.tearDown();
+
+ File backLog = new File(bch.getLogFilePath());
+ if (backLog.exists())
+ {
+ BackupChainLog bchLog = new BackupChainLog(backLog);
+
+ assertNotNull(bchLog.getStartedTime());
+ assertNotNull(bchLog.getFinishedTime());
+
+ backup.restoreExistingWorkspace(bchLog.getBackupConfig().getBackupDir(),
false);
+
+ // check
+ SessionImpl back1 = null;
+ try
+ {
+ back1 = (SessionImpl) getReposityToBackup().login(credentials,
workspaceNameToBackup);
+ Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
+ assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
+ .getProperty("exo:data").getString());
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ finally
+ {
+ if (back1 != null)
+ back1.logout();
+ }
+ }
+ else
+ fail("There are no backup files in " + backDir.getAbsolutePath());
+ }
+
+ public void testExistedRepositoryRestoreWithConfigBackupSetDir() throws Exception
+ {
+ // backup
+ File backDir = new File("target/backup/" + getUUIndex());
+ backDir.mkdirs();
+
+ RepositoryBackupConfig config = new RepositoryBackupConfig();
+ config.setRepository(repositoryNameToBackup);
+ config.setBackupType(BackupManager.FULL_BACKUP_ONLY);
+
+ config.setBackupDir(backDir);
+
+ backup.startBackup(config);
+
+ RepositoryBackupChain bch = backup.findRepositoryBackup(repositoryNameToBackup);
+
+ // wait till full backup will be stopped
+ while (bch.getState() != RepositoryBackupChain.FINISHED)
+ {
+ Thread.yield();
+ Thread.sleep(50);
+ }
+
+ // stop fullBackup
+ backup.stopBackup(bch);
+
+ // check
+ super.tearDown();
+
+ // restore
+ File backLog = new File(bch.getLogFilePath());
+ if (backLog.exists())
+ {
+ RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog);
+
+ assertNotNull(bchLog.getStartedTime());
+ assertNotNull(bchLog.getFinishedTime());
+
+ backup.restoreExistingRepository(bchLog.getBackupConfig().getBackupDir(),
false);
+
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
backup.getLastRepositoryRestore(repositoryNameToBackup)
+ .getStateRestore());
+
+ // check
+ ManageableRepository restoredRepository =
repositoryService.getRepository(repositoryNameToBackup);
+
+ for (String wsName : restoredRepository.getWorkspaceNames())
+ {
+ SessionImpl back1 = null;
+ try
+ {
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
+ Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
+ assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
+ .getProperty("exo:data").getString());
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ finally
+ {
+ if (back1 != null)
+ back1.logout();
+ }
+ }
+ }
+ else
+ fail("There are no backup files in " + backDir.getAbsolutePath());
+ }
+
+ /*public void testWorkspaceRestoreWithConfigBackupSetDir() throws Exception
+ {
+ // backup
+ File backDir = new File((File.createTempFile("12123",
"123")).getParent() + File.separator + getUUIndex());
+ backDir.mkdirs();
+
+ BackupConfig config = new BackupConfig();
+ config.setRepository(repositoryNameToBackup);
+ config.setWorkspace(workspaceNameToBackup);
+ config.setBackupType(BackupManager.FULL_BACKUP_ONLY);
+
+ config.setBackupDir(backDir);
+
+ backup.startBackup(config);
+
+ BackupChain bch = backup.findBackup(repositoryNameToBackup,
workspaceNameToBackup);
+
+ // wait till full backup will be stopped
+ while (bch.getFullBackupState() != BackupJob.FINISHED)
+ {
+ Thread.yield();
+ Thread.sleep(50);
+ }
+
+ // stop fullBackup
+
+ if (bch != null)
+ backup.stopBackup(bch);
+ else
+ fail("Can't get fullBackup chain");
+
+ //TODO
+ super.tearDown();
+ removeWorkspaceFully(repositoryNameToBackup, workspaceNameToBackup);
+
+ File backLog = new File(bch.getLogFilePath());
+ if (backLog.exists())
+ {
+ BackupChainLog bchLog = new BackupChainLog(backLog);
+
+ assertNotNull(bchLog.getStartedTime());
+ assertNotNull(bchLog.getFinishedTime());
+
+ backup.restoreWorkspace(bchLog.getBackupConfig().getBackupDir(), false);
+
+ // check
+ SessionImpl back1 = null;
+ try
+ {
+ back1 = (SessionImpl) getReposityToBackup().login(credentials,
"ws1");
+ Node ws1backTestRoot = back1.getRootNode().getNode("backupTest");
+ assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
+ .getProperty("exo:data").getString());
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ finally
+ {
+ if (back1 != null)
+ back1.logout();
+ }
+ }
+ else
+ fail("There are no backup files in " + backDir.getAbsolutePath());
+ }*/
+
+ public void testRepositoryRestoreWithConfigBackupSetDir() throws Exception
+ {
+ // backup
+ File backDir = new File((File.createTempFile("12123",
"123")).getParent() + File.separator + getUUIndex());
+ backDir.mkdirs();
+
+ RepositoryBackupConfig config = new RepositoryBackupConfig();
+ config.setRepository(repositoryNameToBackup);
+ config.setBackupType(BackupManager.FULL_BACKUP_ONLY);
+
+ config.setBackupDir(backDir);
+
+ backup.startBackup(config);
+
+ RepositoryBackupChain bch = backup.findRepositoryBackup(repositoryNameToBackup);
+
+ // wait till full backup will be stopped
+ while (bch.getState() != RepositoryBackupChain.FINISHED)
+ {
+ Thread.yield();
+ Thread.sleep(50);
+ }
+
+ // stop fullBackup
+
+ backup.stopBackup(bch);
+
+ //TODO
+ super.tearDown();
+ removeRepositoryFully(repositoryNameToBackup);
+
+ // restore
+ File backLog = new File(bch.getLogFilePath());
+ if (backLog.exists())
+ {
+ RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog);
+
+ assertNotNull(bchLog.getStartedTime());
+ assertNotNull(bchLog.getFinishedTime());
+
+ backup.restoreRepository(bchLog.getBackupConfig().getBackupDir(), false);
+
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
backup.getLastRepositoryRestore(repositoryNameToBackup)
+ .getStateRestore());
+
+ // check
+ ManageableRepository restoredRepository =
repositoryService.getRepository(repositoryNameToBackup);
+
+ for (String wsName : restoredRepository.getWorkspaceNames())
+ {
+ SessionImpl back1 = null;
+ try
+ {
+ back1 = (SessionImpl) restoredRepository.login(credentials, wsName);
+ Node ws1backTestRoot =
back1.getRootNode().getNode("backupTest");
+ assertEquals("Restored content should be same",
"property-5", ws1backTestRoot.getNode("node_5")
+ .getProperty("exo:data").getString());
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ finally
+ {
+ if (back1 != null)
+ back1.logout();
+ }
+ }
+ }
+ else
+ fail("There are no backup files in " + backDir.getAbsolutePath());
+ }
}
Modified:
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/TestFileNameProduser.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/TestFileNameProduser.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/TestFileNameProduser.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -41,15 +41,15 @@
public void setUp() throws Exception
{
super.setUp();
-
- tempDir = new File("target" + File.separator + "temp" +
File.separator + "fileProduser");
- tempDir.mkdirs();
backupsetName = String.valueOf(System.currentTimeMillis());
calendar = Calendar.getInstance();
}
public void testGetNextNameJCRBackup() throws Exception
{
+ tempDir = new File("target" + File.separator + "temp" +
File.separator + "fileProduser1");
+ tempDir.mkdirs();
+
FileNameProducer nameProducer =
new FileNameProducer(backupsetName, tempDir.getAbsolutePath(), calendar, true,
false);
File file = nameProducer.getNextFile();
@@ -68,6 +68,9 @@
public void testGetNextNameRDBMSBackup() throws Exception
{
+ tempDir = new File("target" + File.separator + "temp" +
File.separator + "fileProduser2");
+ tempDir.mkdirs();
+
FileNameProducer nameProducer =
new FileNameProducer(backupsetName, tempDir.getAbsolutePath(), calendar, true,
true);
File file = nameProducer.getNextFile();
Modified:
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/server/HTTPBackupAgentTest.java
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/server/HTTPBackupAgentTest.java 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/server/HTTPBackupAgentTest.java 2010-12-21
10:51:58 UTC (rev 3692)
@@ -26,14 +26,16 @@
import org.exoplatform.services.jcr.config.WorkspaceEntry;
import org.exoplatform.services.jcr.core.ManageableRepository;
import org.exoplatform.services.jcr.core.WorkspaceContainerFacade;
-import org.exoplatform.services.jcr.ext.BaseStandaloneTest;
import org.exoplatform.services.jcr.ext.app.SessionProviderService;
import org.exoplatform.services.jcr.ext.app.ThreadLocalSessionProviderService;
+import org.exoplatform.services.jcr.ext.backup.AbstractBackupTestCase;
+import org.exoplatform.services.jcr.ext.backup.BackupChainLog;
import org.exoplatform.services.jcr.ext.backup.BackupJob;
import org.exoplatform.services.jcr.ext.backup.BackupManager;
import org.exoplatform.services.jcr.ext.backup.ContainerRequestUserRole;
+import org.exoplatform.services.jcr.ext.backup.ExtendedBackupManager;
import org.exoplatform.services.jcr.ext.backup.RepositoryBackupChain;
-import org.exoplatform.services.jcr.ext.backup.impl.JobRepositoryRestore;
+import org.exoplatform.services.jcr.ext.backup.RepositoryBackupChainLog;
import org.exoplatform.services.jcr.ext.backup.impl.JobWorkspaceRestore;
import org.exoplatform.services.jcr.ext.backup.server.bean.BackupConfigBean;
import
org.exoplatform.services.jcr.ext.backup.server.bean.response.BackupServiceInfoBean;
@@ -83,7 +85,8 @@
* @author <a href="mailto:alex.reshetnyak@exoplatform.com.ua">Alex
Reshetnyak</a>
* @version $Id: HTTPBackupAgentTest.java 111 2008-11-11 11:11:11Z rainf0x $
*/
-public class HTTPBackupAgentTest extends BaseStandaloneTest
+public class HTTPBackupAgentTest
+ extends AbstractBackupTestCase
{
private String HTTP_BACKUP_AGENT_PATH = HTTPBackupAgent.Constants.BASE_URL;
@@ -99,11 +102,11 @@
{
super.setUp();
- binder =
(ResourceBinder)container.getComponentInstanceOfType(ResourceBinder.class);
- handler =
(RequestHandler)container.getComponentInstanceOfType(RequestHandler.class);
+ binder = (ResourceBinder)
container.getComponentInstanceOfType(ResourceBinder.class);
+ handler = (RequestHandler)
container.getComponentInstanceOfType(RequestHandler.class);
SessionProviderService sessionProviderService =
-
(SessionProviderService)container.getComponentInstanceOfType(ThreadLocalSessionProviderService.class);
+ (SessionProviderService)
container.getComponentInstanceOfType(ThreadLocalSessionProviderService.class);
assertNotNull(sessionProviderService);
sessionProviderService.setSessionProvider(null, new SessionProvider(new
ConversationState(new Identity("root"))));
}
@@ -112,9 +115,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.BACKUP_SERVICE_INFO), new
URI(""), null, new InputHeadersMap(
- headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.BACKUP_SERVICE_INFO),
new URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -123,8 +126,8 @@
assertEquals(200, cres.getStatus());
BackupServiceInfoBean info =
- (BackupServiceInfoBean)getObject(BackupServiceInfoBean.class,
responseWriter.getBody());
- BackupManager backupManager =
(BackupManager)container.getComponentInstanceOfType(BackupManager.class);
+ (BackupServiceInfoBean) getObject(BackupServiceInfoBean.class,
responseWriter.getBody());
+ BackupManager backupManager = (BackupManager)
container.getComponentInstanceOfType(BackupManager.class);
assertNotNull(info);
assertEquals(backupManager.getBackupDirectory().getAbsolutePath(),
info.getBackupLogDir());
@@ -142,9 +145,9 @@
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.DROP_WORKSPACE +
"/db6/ws1/true"), new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.DROP_WORKSPACE +
"/db6/ws1/true"), new URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -183,9 +186,9 @@
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("POST", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.START_BACKUP +
"/db6/ws2"), new URI(""),
- new ByteArrayInputStream(json.toString().getBytes("UTF-8")), new
InputHeadersMap(headers));
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.START_BACKUP +
"/db6/ws2"), new URI(""),
+ new
ByteArrayInputStream(json.toString().getBytes("UTF-8")), new
InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -215,9 +218,9 @@
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("POST", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.START_BACKUP_REPOSITORY +
"/db6"), new URI(""),
- new ByteArrayInputStream(json.toString().getBytes("UTF-8")), new
InputHeadersMap(headers));
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.START_BACKUP_REPOSITORY
+ "/db6"), new URI(""),
+ new
ByteArrayInputStream(json.toString().getBytes("UTF-8")), new
InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -232,9 +235,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- +
HTTPBackupAgent.Constants.OperationType.CURRENT_AND_COMPLETED_BACKUPS_INFO), new
URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_AND_COMPLETED_BACKUPS_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -242,7 +245,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -263,9 +266,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- +
HTTPBackupAgent.Constants.OperationType.CURRENT_AND_COMPLETED_BACKUPS_REPOSITORY_INFO),
new URI(""),
- null, new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_AND_COMPLETED_BACKUPS_REPOSITORY_INFO),
+ new URI(""), null, new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -273,7 +276,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -286,7 +289,7 @@
assertNotNull(info.getFinishedTime());
assertEquals(ShortInfo.CURRENT, info.getType().intValue());
assertTrue(RepositoryBackupChain.WORKING == info.getState().intValue()
- || RepositoryBackupChain.FULL_BACKUP_FINISHED_INCREMENTAL_BACKUP_WORKING ==
info.getState().intValue());
+ || RepositoryBackupChain.FULL_BACKUP_FINISHED_INCREMENTAL_BACKUP_WORKING
== info.getState().intValue());
assertEquals("db6", info.getRepositoryName());
}
@@ -294,9 +297,10 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- +
HTTPBackupAgent.Constants.OperationType.CURRENT_AND_COMPLETED_BACKUPS_INFO_ON_WS +
"/db6/ws2"), new URI(
- ""), null, new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET",
+ new URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_AND_COMPLETED_BACKUPS_INFO_ON_WS
+ + "/db6/ws2"), new URI(""), null,
new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -304,7 +308,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -325,9 +329,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- +
HTTPBackupAgent.Constants.OperationType.CURRENT_AND_COMPLETED_BACKUPS_REPOSITORY_INFO +
"/db6"), new URI(
- ""), null, new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_AND_COMPLETED_BACKUPS_REPOSITORY_INFO
+ + "/db6"), new URI(""), null, new
InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -335,7 +339,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -348,16 +352,16 @@
assertNotNull(info.getFinishedTime());
assertEquals(ShortInfo.CURRENT, info.getType().intValue());
assertTrue(RepositoryBackupChain.WORKING == info.getState().intValue()
- || RepositoryBackupChain.FULL_BACKUP_FINISHED_INCREMENTAL_BACKUP_WORKING ==
info.getState().intValue());
+ || RepositoryBackupChain.FULL_BACKUP_FINISHED_INCREMENTAL_BACKUP_WORKING
== info.getState().intValue());
}
public void testInfoBackupCurrent() throws Exception
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_INFO), new
URI(""), null, new InputHeadersMap(
- headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_INFO),
new URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -365,7 +369,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -386,9 +390,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_REPOSITORY_INFO),
new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_REPOSITORY_INFO), new
URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -396,7 +400,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -409,7 +413,7 @@
assertNotNull(info.getFinishedTime());
assertEquals(ShortInfo.CURRENT, info.getType().intValue());
assertTrue(RepositoryBackupChain.WORKING == info.getState().intValue()
- || RepositoryBackupChain.FULL_BACKUP_FINISHED_INCREMENTAL_BACKUP_WORKING ==
info.getState().intValue());
+ || RepositoryBackupChain.FULL_BACKUP_FINISHED_INCREMENTAL_BACKUP_WORKING
== info.getState().intValue());
assertEquals("db6", info.getRepositoryName());
}
@@ -421,9 +425,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_INFO), new
URI(""), null, new InputHeadersMap(
- headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -431,7 +435,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -446,9 +450,9 @@
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.CURRENT_OR_COMPLETED_BACKUP_INFO +
"/" + id), new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_OR_COMPLETED_BACKUP_INFO + "/" +
id),
+ new URI(""), null, new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -456,7 +460,7 @@
assertEquals(200, cres.getStatus());
- DetailedInfo info = (DetailedInfo)getObject(DetailedInfo.class,
responseWriter.getBody());
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
assertNotNull(info);
assertEquals(BackupManager.FULL_AND_INCREMENTAL, info.getBackupType().intValue());
@@ -477,9 +481,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- +
HTTPBackupAgent.Constants.OperationType.CURRENT_AND_COMPLETED_BACKUPS_REPOSITORY_INFO),
new URI(""),
- null, new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_AND_COMPLETED_BACKUPS_REPOSITORY_INFO),
+ new URI(""), null, new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -487,7 +491,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -501,9 +505,9 @@
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- +
HTTPBackupAgent.Constants.OperationType.CURRENT_OR_COMPLETED_BACKUP_REPOSITORY_INFO +
"/" + id), new URI(
- ""), null, new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_OR_COMPLETED_BACKUP_REPOSITORY_INFO +
"/"
+ + id), new URI(""), null, new
InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -511,7 +515,7 @@
assertEquals(200, cres.getStatus());
- DetailedInfo info = (DetailedInfo)getObject(DetailedInfo.class,
responseWriter.getBody());
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
assertNotNull(info);
assertEquals(BackupManager.FULL_AND_INCREMENTAL, info.getBackupType().intValue());
@@ -519,7 +523,7 @@
assertNotNull(info.getFinishedTime());
assertEquals(ShortInfo.CURRENT, info.getType().intValue());
assertTrue(RepositoryBackupChain.WORKING == info.getState().intValue()
- || RepositoryBackupChain.FULL_BACKUP_FINISHED_INCREMENTAL_BACKUP_WORKING ==
info.getState().intValue());
+ || RepositoryBackupChain.FULL_BACKUP_FINISHED_INCREMENTAL_BACKUP_WORKING
== info.getState().intValue());
assertEquals("db6", info.getRepositoryName());
assertNotNull(info.getBackupConfig());
}
@@ -532,9 +536,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_INFO), new
URI(""), null, new InputHeadersMap(
- headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -542,7 +546,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -557,9 +561,9 @@
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.STOP_BACKUP + "/" + id),
new URI(""), null, new InputHeadersMap(
- headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.STOP_BACKUP +
"/" + id), new URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -575,9 +579,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- +
HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_REPOSITORY_INFO), new
URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -585,7 +589,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -599,9 +603,9 @@
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.STOP_BACKUP_REPOSITORY +
"/" + id), new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.STOP_BACKUP_REPOSITORY
+ "/" + id), new URI(""),
+ null, new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -614,9 +618,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new
URI(""), null, new InputHeadersMap(
- headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -624,7 +628,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -645,9 +649,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO),
new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -655,7 +659,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -679,9 +683,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new
URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -689,7 +693,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -704,9 +708,9 @@
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.CURRENT_OR_COMPLETED_BACKUP_INFO +
"/" + id), new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_OR_COMPLETED_BACKUP_INFO + "/" +
id),
+ new URI(""), null, new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -714,7 +718,7 @@
assertEquals(200, cres.getStatus());
- DetailedInfo info = (DetailedInfo)getObject(DetailedInfo.class,
responseWriter.getBody());
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
assertNotNull(info);
assertEquals(BackupManager.FULL_AND_INCREMENTAL, info.getBackupType().intValue());
@@ -732,9 +736,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -742,7 +746,7 @@
assertEquals(200, cres.getStatus());
- WorkspaceEntry defEntry = (WorkspaceEntry)getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ WorkspaceEntry defEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
assertEquals(repository.getConfiguration().getDefaultWorkspaceName(),
defEntry.getName());
}
@@ -751,9 +755,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_REPOSITORY_CONFIG), new
URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_REPOSITORY_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -761,7 +765,7 @@
assertEquals(200, cres.getStatus());
- RepositoryEntry defEntry = (RepositoryEntry)getObject(RepositoryEntry.class,
responseWriter.getBody());
+ RepositoryEntry defEntry = (RepositoryEntry) getObject(RepositoryEntry.class,
responseWriter.getBody());
assertEquals(repository.getConfiguration().getName(), defEntry.getName());
}
@@ -773,16 +777,16 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG),
new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
handler.handleRequest(creq, cres);
assertEquals(200, cres.getStatus());
- defEntry = (WorkspaceEntry)getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ defEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
}
WorkspaceEntry wEntry = makeWorkspaceEntry(defEntry, "db6",
"ws3", "jdbcjcr24");
@@ -806,7 +810,7 @@
jsonParser.parse(in, jsonHandler);
JsonValue jsonValue = jsonHandler.getJsonObject();
- WorkspaceEntry entry = (WorkspaceEntry)(new
BeanBuilder().createObject(WorkspaceEntry.class, jsonValue));
+ WorkspaceEntry entry = (WorkspaceEntry) (new
BeanBuilder().createObject(WorkspaceEntry.class, jsonValue));
assertNotNull(entry);
@@ -820,9 +824,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new
URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -830,7 +834,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -848,16 +852,16 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG),
new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
handler.handleRequest(creq, cres);
assertEquals(200, cres.getStatus());
- defEntry = (WorkspaceEntry)getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ defEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
}
WorkspaceEntry wEntry = makeWorkspaceEntry(defEntry, "db6",
"ws3", "jdbcjcr24");
@@ -883,9 +887,9 @@
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.RESTORE + "/" +
"db6" + "/" + id), new URI(""),
- new ByteArrayInputStream(json.toString().getBytes("UTF-8")), new
InputHeadersMap(headers));
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE +
"/" + "db6" + "/" + id), new URI(""),
+ new
ByteArrayInputStream(json.toString().getBytes("UTF-8")), new
InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -900,9 +904,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_WS +
"/" + "db6" + "/" + "ws3"),
- new URI(""), null, new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_WS + "/" +
"db6" + "/"
+ + "ws3"), new URI(""), null, new
InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -910,7 +914,7 @@
assertEquals(200, cres.getStatus());
- DetailedInfo info = (DetailedInfo)getObject(DetailedInfo.class,
responseWriter.getBody());
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
assertNotNull(info);
assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
@@ -931,9 +935,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORES), new
URI(""), null, new InputHeadersMap(
- headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORES),
new URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -941,7 +945,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
assertNotNull(infoList);
ShortInfo info = new ArrayList<ShortInfo>(infoList.getBackups()).get(0);
@@ -962,6 +966,889 @@
}
}
+ public void testRestoreExistsTrue() throws Exception
+ {
+ // Get backup id for backup on workspace /db6/ws2
+ String id = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+ assertEquals(info.getWorkspaceName(), "ws2");
+
+ id = info.getBackupId();
+ }
+
+ // Getting default WorkspaceEntry
+ WorkspaceEntry defEntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ }
+
+ WorkspaceEntry wEntry = makeWorkspaceEntry(defEntry, "db6",
"ws3", "jdbcjcr24");
+
+ // Check the workspace /db6/ws3 is exists.
+ try
+ {
+ Session sessin_ws3 =
repositoryService.getRepository("db6").login(credentials, "ws3");
+ // ok
+ }
+ catch (Exception e)
+ {
+ fail("The workspace /db6/ws3 should be exists.");
+ }
+
+ // Restore
+ {
+ // Create JSON to WorkspaceEntry
+ JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
+ JsonValue json = generatorImpl.createJsonObject(wEntry);
+
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE +
"/" + "db6" + "/" + id + "/" + "true"),
+ new URI(""), new
ByteArrayInputStream(json.toString().getBytes("UTF-8")),
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info to workspace /db6/ws3
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_WS + "/" +
"db6" + "/"
+ + "ws3"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertEquals("ws3", info.getWorkspaceName());
+ assertNotNull(info.getBackupConfig());
+
+ Session sessin_ws3 =
repositoryService.getRepository("db6").login(credentials, "ws3");
+ assertNotNull(sessin_ws3);
+ assertNotNull(sessin_ws3.getRootNode());
+ }
+ }
+
+ public void testRestoreExistsFalse() throws Exception
+ {
+ // Get backup id for backup on workspace /db6/ws2
+ String id = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+ assertEquals(info.getWorkspaceName(), "ws2");
+
+ id = info.getBackupId();
+ }
+
+ // Getting default WorkspaceEntry
+ WorkspaceEntry defEntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ }
+
+ WorkspaceEntry wEntry = makeWorkspaceEntry(defEntry, "db6",
"ws3", "jdbcjcr24");
+
+ removeWorkspaceFully("db6", "ws3");
+
+ // Check the workspace /db6/ws3 is not exists.
+ try
+ {
+ Session sessin_ws3 =
repositoryService.getRepository("db6").login(credentials, "ws3");
+ fail("The workspace /db6/ws3 should be not exists.");
+ }
+ catch (Exception e)
+ {
+ // ok
+ }
+
+ // Restore
+ {
+ // Create JSON to WorkspaceEntry
+ JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
+ JsonValue json = generatorImpl.createJsonObject(wEntry);
+
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE +
"/" + "db6" + "/" + id + "/" +
"false"),
+ new URI(""), new
ByteArrayInputStream(json.toString().getBytes("UTF-8")),
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info to workspace /db6/ws3
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_WS + "/" +
"db6" + "/"
+ + "ws3"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertEquals("ws3", info.getWorkspaceName());
+ assertNotNull(info.getBackupConfig());
+
+ Session sessin_ws3 =
repositoryService.getRepository("db6").login(credentials, "ws3");
+ assertNotNull(sessin_ws3);
+ assertNotNull(sessin_ws3.getRootNode());
+ }
+ }
+
+ public void testRestoreExistsByIdOriginalConfigTrue() throws Exception
+ {
+ // Get backup id for backup on workspace /db6/ws2
+ String id = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+ assertEquals(info.getWorkspaceName(), "ws2");
+
+ id = info.getBackupId();
+ }
+
+ // Check the workspace /db6/ws3 is exists.
+ try
+ {
+ Session sessin_ws2 =
repositoryService.getRepository("db6").login(credentials, "ws2");
+ // ok
+ }
+ catch (Exception e)
+ {
+ fail("The workspace /db6/ws2 should be exists.");
+ }
+
+ // Restore
+ {
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE +
"/" + id + "/" + "true"), new URI(""),
+ null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info to workspace /db6/ws2
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_WS + "/" +
"db6" + "/"
+ + "ws2"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertEquals("ws2", info.getWorkspaceName());
+ assertNotNull(info.getBackupConfig());
+
+ Session sessin_ws2 =
repositoryService.getRepository("db6").login(credentials, "ws2");
+ assertNotNull(sessin_ws2);
+ assertNotNull(sessin_ws2.getRootNode());
+ }
+ }
+
+ public void testRestoreExistsByIdOriginalConfigFalse() throws Exception
+ {
+ // Get backup id for backup on workspace /db6/ws2
+ String id = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+ assertEquals(info.getWorkspaceName(), "ws2");
+
+ id = info.getBackupId();
+ }
+
+ removeWorkspaceFully("db6", "ws2");
+
+ // Check the workspace /db6/ws2 is exists.
+ try
+ {
+ Session sessin_ws2 =
repositoryService.getRepository("db6").login(credentials, "ws2");
+ fail("The workspace /db6/ws2 should be not exists.");
+ }
+ catch (Exception e)
+ {
+ // ok
+ }
+
+ // Restore
+ {
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE +
"/" + id + "/" + "false"), new URI(""),
+ null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info to workspace /db6/ws2
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_WS + "/" +
"db6" + "/"
+ + "ws2"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertEquals("ws2", info.getWorkspaceName());
+ assertNotNull(info.getBackupConfig());
+
+ Session sessin_ws2 =
repositoryService.getRepository("db6").login(credentials, "ws2");
+ assertNotNull(sessin_ws2);
+ assertNotNull(sessin_ws2.getRootNode());
+ }
+ }
+
+ public void testRestoreBackupSetExistsTrue() throws Exception
+ {
+ // Get backup id for backup on workspace /db6/ws2
+ String id = null;
+ String backupSetPath = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+ assertEquals(info.getWorkspaceName(), "ws2");
+
+ id = info.getBackupId();
+
+ for (BackupChainLog bcl : backup.getBackupsLogs())
+ {
+ if (bcl.getBackupId().equals(id))
+ {
+ backupSetPath = bcl.getBackupConfig().getBackupDir().getCanonicalPath();
+ break;
+ }
+ }
+ }
+
+ // Getting default WorkspaceEntry
+ WorkspaceEntry defEntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ }
+
+ WorkspaceEntry wEntry = makeWorkspaceEntry(defEntry, "db6",
"ws3", "jdbcjcr24");
+
+ // Check the workspace /db6/ws3 is exists.
+ try
+ {
+ Session sessin_ws3 =
repositoryService.getRepository("db6").login(credentials, "ws3");
+ // ok
+ }
+ catch (Exception e)
+ {
+ fail("The workspace /db6/ws3 should be exists.");
+ }
+
+ // Restore
+ {
+ // Create JSON to WorkspaceEntry
+ JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
+ JsonValue json = generatorImpl.createJsonObject(wEntry);
+
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_BACKUP_SET +
"/" + "db6" + "/"
+ + backupSetPath + "/" + "true"), new
URI(""), new ByteArrayInputStream(json.toString()
+ .getBytes("UTF-8")), new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info to workspace /db6/ws3
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_WS + "/" +
"db6" + "/"
+ + "ws3"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertEquals("ws3", info.getWorkspaceName());
+ assertNotNull(info.getBackupConfig());
+
+ Session sessin_ws3 =
repositoryService.getRepository("db6").login(credentials, "ws3");
+ assertNotNull(sessin_ws3);
+ assertNotNull(sessin_ws3.getRootNode());
+ }
+ }
+
+ public void testRestoreOriginalConfigBackupSetExistsTrue() throws Exception
+ {
+ // Get backup id for backup on workspace /db6/ws2
+ String id = null;
+ String backupSetPath = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+ assertEquals(info.getWorkspaceName(), "ws2");
+
+ id = info.getBackupId();
+
+ for (BackupChainLog bcl : backup.getBackupsLogs())
+ {
+ if (bcl.getBackupId().equals(id))
+ {
+ backupSetPath = bcl.getBackupConfig().getBackupDir().getCanonicalPath();
+ break;
+ }
+ }
+ }
+
+ // Check the workspace /db6/ws2 is exists.
+ try
+ {
+ Session sessin_ws2 =
repositoryService.getRepository("db6").login(credentials, "ws2");
+ // ok
+ }
+ catch (Exception e)
+ {
+ fail("The workspace /db6/ws2 should be exists.");
+ }
+
+ // Restore
+ {
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_BACKUP_SET +
"/" + backupSetPath + "/"
+ + "true"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info to workspace /db6/ws2
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_WS + "/" +
"db6" + "/"
+ + "ws2"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertEquals("ws2", info.getWorkspaceName());
+ assertNotNull(info.getBackupConfig());
+
+ Session sessin_ws2 =
repositoryService.getRepository("db6").login(credentials, "ws2");
+ assertNotNull(sessin_ws2);
+ assertNotNull(sessin_ws2.getRootNode());
+ }
+ }
+
+ public void testRestoreOriginalConfigBackupSetExistsFalse() throws Exception
+ {
+ // Get backup id for backup on workspace /db6/ws2
+ String id = null;
+ String backupSetPath = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+ assertEquals(info.getWorkspaceName(), "ws2");
+
+ id = info.getBackupId();
+
+ for (BackupChainLog bcl : backup.getBackupsLogs())
+ {
+ if (bcl.getBackupId().equals(id))
+ {
+ backupSetPath = bcl.getBackupConfig().getBackupDir().getCanonicalPath();
+ break;
+ }
+ }
+ }
+
+ removeWorkspaceFully("db6", "ws2");
+ // Check the workspace /db6/ws2 is exists.
+ try
+ {
+ Session sessin_ws2 =
repositoryService.getRepository("db6").login(credentials, "ws2");
+ fail("The workspace /db6/ws2 should be not exists.");
+ }
+ catch (Exception e)
+ {
+ // ok
+ }
+
+ // Restore
+ {
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_BACKUP_SET +
"/" + backupSetPath + "/"
+ + "false"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info to workspace /db6/ws2
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_WS + "/" +
"db6" + "/"
+ + "ws2"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertEquals("ws2", info.getWorkspaceName());
+ assertNotNull(info.getBackupConfig());
+
+ Session sessin_ws2 =
repositoryService.getRepository("db6").login(credentials, "ws2");
+ assertNotNull(sessin_ws2);
+ assertNotNull(sessin_ws2.getRootNode());
+ }
+ }
+
+ public void testRestoreBackupSetExistsFalse() throws Exception
+ {
+ // Get backup id for backup on workspace /db6/ws2
+ String id = null;
+ String backupSetPath = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_INFO), new URI(""),
null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+ assertEquals(info.getWorkspaceName(), "ws2");
+
+ id = info.getBackupId();
+
+ for (BackupChainLog bcl : backup.getBackupsLogs())
+ {
+ if (bcl.getBackupId().equals(id))
+ {
+ backupSetPath = bcl.getBackupConfig().getBackupDir().getCanonicalPath();
+ break;
+ }
+ }
+ }
+
+ // Getting default WorkspaceEntry
+ WorkspaceEntry defEntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ }
+
+ WorkspaceEntry wEntry = makeWorkspaceEntry(defEntry, "db6",
"ws3", "jdbcjcr24");
+
+ removeWorkspaceFully("db6", "ws3");
+
+ // Check the workspace /db6/ws3 is not exists.
+ try
+ {
+ Session sessin_ws3 =
repositoryService.getRepository("db6").login(credentials, "ws3");
+ fail("The workspace /db6/ws3 should be not exists.");
+ }
+ catch (Exception e)
+ {
+ // ok
+ }
+
+ // Restore
+ {
+ // Create JSON to WorkspaceEntry
+ JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
+ JsonValue json = generatorImpl.createJsonObject(wEntry);
+
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_BACKUP_SET +
"/" + "db6" + "/"
+ + backupSetPath + "/" + "false"), new
URI(""), new ByteArrayInputStream(json.toString()
+ .getBytes("UTF-8")), new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info to workspace /db6/ws3
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_WS + "/" +
"db6" + "/"
+ + "ws3"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertEquals("ws3", info.getWorkspaceName());
+ assertNotNull(info.getBackupConfig());
+
+ Session sessin_ws3 =
repositoryService.getRepository("db6").login(credentials, "ws3");
+ assertNotNull(sessin_ws3);
+ assertNotNull(sessin_ws3.getRootNode());
+ }
+ }
+
public void testRestoreRepository() throws Exception
{
// Get backup id for backup on workspace /db6/ws2
@@ -970,9 +1857,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -980,7 +1867,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
assertEquals(1, list.size());
@@ -997,16 +1884,16 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_REPOSITORY_CONFIG),
new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_REPOSITORY_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
handler.handleRequest(creq, cres);
assertEquals(200, cres.getStatus());
- defREntry = (RepositoryEntry)getObject(RepositoryEntry.class,
responseWriter.getBody());
+ defREntry = (RepositoryEntry) getObject(RepositoryEntry.class,
responseWriter.getBody());
}
// Getting default WorkspaceEntry
@@ -1014,27 +1901,28 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG),
new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
handler.handleRequest(creq, cres);
assertEquals(200, cres.getStatus());
- defWEntry = (WorkspaceEntry)getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ defWEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
}
ArrayList<WorkspaceEntry> wsEntries = new ArrayList<WorkspaceEntry>();
- wsEntries.add(makeWorkspaceEntry(defWEntry, "db7", "ws",
"jdbcjcr24"));
- wsEntries.add(makeWorkspaceEntry(defWEntry, "db7", "ws2",
"jdbcjcr24"));
- RepositoryEntry rEntry = makeRepositoryEntry(defREntry, "db7",
wsEntries);
+ wsEntries.add(makeWorkspaceEntry(defWEntry, "db6backup", "ws",
"jdbcjcr27"));
+ wsEntries.add(makeWorkspaceEntry(defWEntry, "db6backup", "ws2",
"jdbcjcr27"));
+ RepositoryEntry rEntry = makeRepositoryEntry(defREntry, "db6backup",
wsEntries);
- // Check the workspace /db6/ws3 not exists.
+ // Check the repository /db6backup.
try
{
- repositoryService.getRepository("db7");
+ repositoryService.getRepository("db6backup");
+ fail("The repository /db6backup should be not exists.");
}
catch (Exception e)
{
@@ -1051,9 +1939,9 @@
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY +
"/" + id), new URI(""),
- new ByteArrayInputStream(json.toString().getBytes("UTF-8")), new
InputHeadersMap(headers));
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY +
"/" + id), new URI(""),
+ new
ByteArrayInputStream(json.toString().getBytes("UTF-8")), new
InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -1068,9 +1956,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_REPOSITORY + "/"
+ "db7"),
- new URI(""), null, new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_REPOSITORY +
"/"
+ + "db6backup"), new URI(""), null, new
InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -1078,7 +1966,7 @@
assertEquals(200, cres.getStatus());
- DetailedInfo info = (DetailedInfo)getObject(DetailedInfo.class,
responseWriter.getBody());
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
assertNotNull(info);
assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
@@ -1086,11 +1974,11 @@
assertNotNull(info.getFinishedTime());
assertEquals(ShortInfo.RESTORE, info.getType().intValue());
assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
- assertEquals("db7", info.getRepositoryName());
+ assertEquals("db6backup", info.getRepositoryName());
assertNotNull(info.getBackupConfig());
- assertNotNull(repositoryService.getRepository("db7"));
- Session sessin_ws =
repositoryService.getRepository("db7").login(credentials, "ws");
+ assertNotNull(repositoryService.getRepository("db6backup"));
+ Session sessin_ws =
repositoryService.getRepository("db6backup").login(credentials,
"ws");
assertNotNull(sessin_ws);
assertNotNull(sessin_ws.getRootNode());
}
@@ -1099,9 +1987,9 @@
{
MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
ContainerRequestUserRole creq =
- new ContainerRequestUserRole("GET", new URI(HTTP_BACKUP_AGENT_PATH
- + HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORES_REPOSITORY),
new URI(""), null,
- new InputHeadersMap(headers));
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORES_REPOSITORY), new
URI(""), null,
+ new InputHeadersMap(headers));
ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
ContainerResponse cres = new ContainerResponse(responseWriter);
@@ -1109,7 +1997,7 @@
assertEquals(200, cres.getStatus());
- ShortInfoList infoList = (ShortInfoList)getObject(ShortInfoList.class,
responseWriter.getBody());
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
assertNotNull(infoList);
ShortInfo info = new ArrayList<ShortInfo>(infoList.getBackups()).get(0);
@@ -1120,16 +2008,971 @@
assertNotNull(info.getFinishedTime());
assertEquals(ShortInfo.RESTORE, info.getType().intValue());
assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
- assertEquals("db7", info.getRepositoryName());
+ assertEquals("db6backup", info.getRepositoryName());
assertNotNull(info.getBackupId());
- assertNotNull(repositoryService.getRepository("db7"));
- Session sessin_ws =
repositoryService.getRepository("db7").login(credentials, "ws");
+ assertNotNull(repositoryService.getRepository("db6backup"));
+ Session sessin_ws =
repositoryService.getRepository("db6backup").login(credentials,
"ws");
assertNotNull(sessin_ws);
assertNotNull(sessin_ws.getRootNode());
}
}
+ public void testRestoreRepositoryExistsTrue() throws Exception
+ {
+ // Get backup id for backup on workspace /db6
+ String id = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+
+ id = info.getBackupId();
+ }
+
+ // Getting default RepositoryEntry
+ RepositoryEntry defREntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_REPOSITORY_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defREntry = (RepositoryEntry) getObject(RepositoryEntry.class,
responseWriter.getBody());
+ }
+
+ // Getting default WorkspaceEntry
+ WorkspaceEntry defWEntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defWEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ }
+
+ ArrayList<WorkspaceEntry> wsEntries = new ArrayList<WorkspaceEntry>();
+ wsEntries.add(makeWorkspaceEntry(defWEntry, "db6backup", "ws",
"jdbcjcr27"));
+ wsEntries.add(makeWorkspaceEntry(defWEntry, "db6backup", "ws2",
"jdbcjcr27"));
+ RepositoryEntry rEntry = makeRepositoryEntry(defREntry, "db6backup",
wsEntries);
+
+ // Check the repository /db6backup.
+ try
+ {
+ repositoryService.getRepository("db6backup");
+ // ok
+ }
+ catch (Exception e)
+ {
+ fail("The repository /db6backup should be exists.");
+ }
+
+ // Restore
+ {
+ // Create JSON to WorkspaceEntry
+ JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
+ JsonValue json = generatorImpl.createJsonObject(rEntry);
+
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY +
"/" + id + "/" + "true"),
+ new URI(""),
+ new
ByteArrayInputStream(json.toString().getBytes("UTF-8")), new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_REPOSITORY +
"/"
+ + "db6backup"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6backup", info.getRepositoryName());
+ assertNotNull(info.getBackupConfig());
+
+ assertNotNull(repositoryService.getRepository("db6backup"));
+ Session sessin_ws =
repositoryService.getRepository("db6backup").login(credentials,
"ws");
+ assertNotNull(sessin_ws);
+ assertNotNull(sessin_ws.getRootNode());
+ }
+ }
+
+ public void testRestoreRepositoryExistsFalse() throws Exception
+ {
+ // Get backup id for backup on workspace /db6
+ String id = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+
+ id = info.getBackupId();
+ }
+
+ // Getting default RepositoryEntry
+ RepositoryEntry defREntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_REPOSITORY_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defREntry = (RepositoryEntry) getObject(RepositoryEntry.class,
responseWriter.getBody());
+ }
+
+ // Getting default WorkspaceEntry
+ WorkspaceEntry defWEntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defWEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ }
+
+ ArrayList<WorkspaceEntry> wsEntries = new ArrayList<WorkspaceEntry>();
+ wsEntries.add(makeWorkspaceEntry(defWEntry, "db6backup", "ws",
"jdbcjcr27"));
+ wsEntries.add(makeWorkspaceEntry(defWEntry, "db6backup", "ws2",
"jdbcjcr27"));
+ RepositoryEntry rEntry = makeRepositoryEntry(defREntry, "db6backup",
wsEntries);
+
+ removeRepositoryFully("db6backup");
+ // Check the repository /db6backup.
+ try
+ {
+ repositoryService.getRepository("db6backup");
+ fail("The repository /db6backup should be not exists.");
+ }
+ catch (Exception e)
+ {
+ // ok
+ }
+
+ // Restore
+ {
+ // Create JSON to WorkspaceEntry
+ JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
+ JsonValue json = generatorImpl.createJsonObject(rEntry);
+
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY +
"/" + id + "/" + "false"),
+ new URI(""), new
ByteArrayInputStream(json.toString().getBytes("UTF-8")),
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_REPOSITORY +
"/"
+ + "db6backup"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6backup", info.getRepositoryName());
+ assertNotNull(info.getBackupConfig());
+
+ assertNotNull(repositoryService.getRepository("db6backup"));
+ Session sessin_ws =
repositoryService.getRepository("db6backup").login(credentials,
"ws");
+ assertNotNull(sessin_ws);
+ assertNotNull(sessin_ws.getRootNode());
+ }
+ }
+
+ public void testRestoreRepositoryByIdOriginalConfigExistsTrue() throws Exception
+ {
+ // Get backup id for backup on workspace /db6
+ String id = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+
+ id = info.getBackupId();
+ }
+
+ // Check the repository /db6backup.
+ try
+ {
+ repositoryService.getRepository("db6");
+ // ok
+ }
+ catch (Exception e)
+ {
+ fail("The repository /db6 should be exists.");
+ }
+
+ // Restore
+ {
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY +
"/" + id + "/" + "true"),
+ new URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_REPOSITORY + "/"
+ "db6"),
+ new URI(""), null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertNotNull(info.getBackupConfig());
+
+ assertNotNull(repositoryService.getRepository("db6"));
+ Session sessin_ws =
repositoryService.getRepository("db6").login(credentials, "ws");
+ assertNotNull(sessin_ws);
+ assertNotNull(sessin_ws.getRootNode());
+ }
+ }
+
+ public void testRestoreRepositoryByIdOriginalConfigExistsFalse() throws Exception
+ {
+ // Get backup id for backup on workspace /db6
+ String id = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+
+ id = info.getBackupId();
+ }
+
+ removeRepositoryFully("db6");
+ // Check the repository /db6backup.
+ try
+ {
+ repositoryService.getRepository("db6");
+ fail("The repository /db6 should be not exists.");
+ }
+ catch (Exception e)
+ {
+ // ok
+ }
+
+ // Restore
+ {
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY +
"/" + id + "/" + "false"),
+ new URI(""), null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_REPOSITORY + "/"
+ "db6"),
+ new URI(""), null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertNotNull(info.getBackupConfig());
+
+ assertNotNull(repositoryService.getRepository("db6"));
+ Session sessin_ws =
repositoryService.getRepository("db6").login(credentials, "ws");
+ assertNotNull(sessin_ws);
+ assertNotNull(sessin_ws.getRootNode());
+ }
+ }
+
+ public void testRestoreRepositoryChangeConfigBackupSetExistsTrue() throws Exception
+ {
+ // Get backup id for backup on workspace /db6
+ String id = null;
+ String backupSetPath = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+
+ id = info.getBackupId();
+
+ for (RepositoryBackupChainLog bcl : backup.getRepositoryBackupsLogs())
+ {
+ if (bcl.getBackupId().equals(id))
+ {
+ backupSetPath = bcl.getBackupConfig().getBackupDir().getCanonicalPath();
+ break;
+ }
+ }
+ }
+
+ // Getting default RepositoryEntry
+ RepositoryEntry defREntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_REPOSITORY_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defREntry = (RepositoryEntry) getObject(RepositoryEntry.class,
responseWriter.getBody());
+ }
+
+ // Getting default WorkspaceEntry
+ WorkspaceEntry defWEntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defWEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ }
+
+ ArrayList<WorkspaceEntry> wsEntries = new ArrayList<WorkspaceEntry>();
+ wsEntries.add(makeWorkspaceEntry(defWEntry, "db6backup", "ws",
"jdbcjcr27"));
+ wsEntries.add(makeWorkspaceEntry(defWEntry, "db6backup", "ws2",
"jdbcjcr27"));
+ RepositoryEntry rEntry = makeRepositoryEntry(defREntry, "db6backup",
wsEntries);
+
+ // Check the repository /db6backup.
+ try
+ {
+ repositoryService.getRepository("db6backup");
+ // ok
+ }
+ catch (Exception e)
+ {
+ fail("The repository /db6backup should be exists.");
+ }
+
+ // Restore
+ {
+ // Create JSON to WorkspaceEntry
+ JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
+ JsonValue json = generatorImpl.createJsonObject(rEntry);
+
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY_BACKUP_SET + "/"
+ + backupSetPath + "/"
+ + "true"),
+ new URI(""), new
ByteArrayInputStream(json.toString().getBytes("UTF-8")),
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_REPOSITORY +
"/"
+ + "db6backup"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6backup", info.getRepositoryName());
+ assertNotNull(info.getBackupConfig());
+
+ assertNotNull(repositoryService.getRepository("db6backup"));
+ Session sessin_ws =
repositoryService.getRepository("db6backup").login(credentials,
"ws");
+ assertNotNull(sessin_ws);
+ assertNotNull(sessin_ws.getRootNode());
+ }
+ }
+
+ public void testRestoreRepositoryChangeConfigBackupSetExistsFalse() throws Exception
+ {
+ // Get backup id for backup on workspace /db6
+ String id = null;
+ String backupSetPath = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+
+ id = info.getBackupId();
+
+ for (RepositoryBackupChainLog bcl : backup.getRepositoryBackupsLogs())
+ {
+ if (bcl.getBackupId().equals(id))
+ {
+ backupSetPath = bcl.getBackupConfig().getBackupDir().getCanonicalPath();
+ break;
+ }
+ }
+ }
+
+ // Getting default RepositoryEntry
+ RepositoryEntry defREntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_REPOSITORY_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defREntry = (RepositoryEntry) getObject(RepositoryEntry.class,
responseWriter.getBody());
+ }
+
+ // Getting default WorkspaceEntry
+ WorkspaceEntry defWEntry;
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.GET_DEFAULT_WORKSPACE_CONFIG), new
URI(""), null,
+ new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ defWEntry = (WorkspaceEntry) getObject(WorkspaceEntry.class,
responseWriter.getBody());
+ }
+
+ ArrayList<WorkspaceEntry> wsEntries = new ArrayList<WorkspaceEntry>();
+ wsEntries.add(makeWorkspaceEntry(defWEntry, "db6backup", "ws",
"jdbcjcr27"));
+ wsEntries.add(makeWorkspaceEntry(defWEntry, "db6backup", "ws2",
"jdbcjcr27"));
+ RepositoryEntry rEntry = makeRepositoryEntry(defREntry, "db6backup",
wsEntries);
+
+ removeRepositoryFully("db6backup");
+ // Check the repository /db6backup.
+ try
+ {
+ repositoryService.getRepository("db6backup");
+ fail("The repository /db6backup should be not exists.");
+ }
+ catch (Exception e)
+ {
+ // ok
+ }
+
+ // Restore
+ {
+ // Create JSON to WorkspaceEntry
+ JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
+ JsonValue json = generatorImpl.createJsonObject(rEntry);
+
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ headers.putSingle("Content-Type", "application/json;
charset=UTF-8");
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("POST", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.RESTORE_REPOSITORY_BACKUP_SET + "/"
+ + backupSetPath + "/" + "false"), new
URI(""), new ByteArrayInputStream(json.toString()
+ .getBytes("UTF-8")), new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_REPOSITORY +
"/"
+ + "db6backup"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6backup", info.getRepositoryName());
+ assertNotNull(info.getBackupConfig());
+
+ assertNotNull(repositoryService.getRepository("db6backup"));
+ Session sessin_ws =
repositoryService.getRepository("db6backup").login(credentials,
"ws");
+ assertNotNull(sessin_ws);
+ assertNotNull(sessin_ws.getRootNode());
+ }
+ }
+
+ public void testRestoreRepositoryBackupSetExistsTrue() throws Exception
+ {
+ // Get backup id for backup on workspace /db6
+ String id = null;
+ String backupSetPath = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+
+ id = info.getBackupId();
+
+ for (RepositoryBackupChainLog bcl : backup.getRepositoryBackupsLogs())
+ {
+ if (bcl.getBackupId().equals(id))
+ {
+ backupSetPath = bcl.getBackupConfig().getBackupDir().getCanonicalPath();
+ break;
+ }
+ }
+ }
+
+ // Check the repository /db6.
+ try
+ {
+ repositoryService.getRepository("db6");
+ // ok
+ }
+ catch (Exception e)
+ {
+ fail("The repository /db6 should be exists.");
+ }
+
+ // Restore
+ {
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_BACKUP_SET +
"/" + backupSetPath + "/"
+ + "true"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_REPOSITORY + "/"
+ "db6"),
+ new URI(""), null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertNotNull(info.getBackupConfig());
+
+ assertNotNull(repositoryService.getRepository("db6"));
+ Session sessin_ws =
repositoryService.getRepository("db6").login(credentials, "ws");
+ assertNotNull(sessin_ws);
+ assertNotNull(sessin_ws.getRootNode());
+ }
+ }
+
+ public void testRestoreRepositoryBackupSetExistsFalse() throws Exception
+ {
+ // Get backup id for backup on workspace /db6
+ String id = null;
+ String backupSetPath = null;
+
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.COMPLETED_BACKUPS_REPOSITORY_INFO), new
URI(""),
+ null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ ShortInfoList infoList = (ShortInfoList) getObject(ShortInfoList.class,
responseWriter.getBody());
+ List<ShortInfo> list = new
ArrayList<ShortInfo>(infoList.getBackups());
+
+ assertEquals(1, list.size());
+
+ ShortInfo info = list.get(0);
+
+ assertEquals(info.getRepositoryName(), "db6");
+
+ id = info.getBackupId();
+
+ for (RepositoryBackupChainLog bcl : backup.getRepositoryBackupsLogs())
+ {
+ if (bcl.getBackupId().equals(id))
+ {
+ backupSetPath = bcl.getBackupConfig().getBackupDir().getCanonicalPath();
+ break;
+ }
+ }
+ }
+
+ removeRepositoryFully("db6");
+ // Check the repository /db6.
+ try
+ {
+ repositoryService.getRepository("db6");
+ fail("The repository /db6 should be not exists.");
+ }
+ catch (Exception e)
+ {
+ // ok
+ }
+
+ // Restore
+ {
+ // Execute restore
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ + HTTPBackupAgent.Constants.OperationType.RESTORE_BACKUP_SET +
"/" + backupSetPath + "/"
+ + "false"), new URI(""), null, new
InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+ }
+
+ Thread.sleep(2000);
+
+ // Get restore info
+ {
+ MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
+ ContainerRequestUserRole creq =
+ new ContainerRequestUserRole("GET", new
URI(HTTP_BACKUP_AGENT_PATH
+ +
HTTPBackupAgent.Constants.OperationType.CURRENT_RESTORE_INFO_ON_REPOSITORY + "/"
+ "db6"),
+ new URI(""), null, new InputHeadersMap(headers));
+
+ ByteArrayContainerResponseWriter responseWriter = new
ByteArrayContainerResponseWriter();
+ ContainerResponse cres = new ContainerResponse(responseWriter);
+ handler.handleRequest(creq, cres);
+
+ assertEquals(200, cres.getStatus());
+
+ DetailedInfo info = (DetailedInfo) getObject(DetailedInfo.class,
responseWriter.getBody());
+
+ assertNotNull(info);
+ assertEquals(BackupManager.FULL_AND_INCREMENTAL,
info.getBackupType().intValue());
+ assertNotNull(info.getStartedTime());
+ assertNotNull(info.getFinishedTime());
+ assertEquals(ShortInfo.RESTORE, info.getType().intValue());
+ assertEquals(JobWorkspaceRestore.RESTORE_SUCCESSFUL,
info.getState().intValue());
+ assertEquals("db6", info.getRepositoryName());
+ assertNotNull(info.getBackupConfig());
+
+ assertNotNull(repositoryService.getRepository("db6"));
+ Session sessin_ws =
repositoryService.getRepository("db6").login(credentials, "ws");
+ assertNotNull(sessin_ws);
+ assertNotNull(sessin_ws.getRootNode());
+ }
+ }
+
public void testDropRepository() throws Exception
{
@@ -1149,18 +2992,18 @@
}
private int forceCloseSession(String repositoryName, String workspaceName) throws
RepositoryException,
- RepositoryConfigurationException
+ RepositoryConfigurationException
{
ManageableRepository mr = repositoryService.getRepository(repositoryName);
WorkspaceContainerFacade wc = mr.getWorkspaceContainer(workspaceName);
- SessionRegistry sessionRegistry =
(SessionRegistry)wc.getComponent(SessionRegistry.class);
+ SessionRegistry sessionRegistry = (SessionRegistry)
wc.getComponent(SessionRegistry.class);
return sessionRegistry.closeSessions(workspaceName);
}
protected WorkspaceEntry makeWorkspaceEntry(WorkspaceEntry defWEntry, String repoNmae,
String wsName,
- String sourceName)
+ String sourceName)
{
WorkspaceEntry ws1back = new WorkspaceEntry();
ws1back.setName(wsName);
@@ -1174,7 +3017,7 @@
// Indexer
ArrayList qParams = new ArrayList();
- qParams.add(new SimpleParameterEntry("indexDir", "target" +
File.separator + wsName));
+ qParams.add(new SimpleParameterEntry("index-dir", "target" +
File.separator + wsName));
QueryHandlerEntry qEntry = new
QueryHandlerEntry(defWEntry.getQueryHandler().getType(), qParams);
ws1back.setQueryHandler(qEntry);
@@ -1182,7 +3025,7 @@
ArrayList params = new ArrayList();
for (Iterator i = defWEntry.getContainer().getParameters().iterator();
i.hasNext();)
{
- SimpleParameterEntry p = (SimpleParameterEntry)i.next();
+ SimpleParameterEntry p = (SimpleParameterEntry) i.next();
SimpleParameterEntry newp = new SimpleParameterEntry(p.getName(),
p.getValue());
if (newp.getName().equals("source-name"))
@@ -1202,7 +3045,7 @@
}
protected RepositoryEntry makeRepositoryEntry(RepositoryEntry defREntry, String
repoName,
- ArrayList<WorkspaceEntry> wsEntries)
+ ArrayList<WorkspaceEntry> wsEntries)
{
RepositoryEntry rEntry = new RepositoryEntry();
rEntry.setAccessControl(defREntry.getAccessControl());
@@ -1238,4 +3081,12 @@
return new BeanBuilder().createObject(cl, jsonValue);
}
+
+ /**
+ * {@inheritDoc}
+ */
+ protected ExtendedBackupManager getBackupManager()
+ {
+ return (ExtendedBackupManager)
container.getComponentInstanceOfType(BackupManager.class);
+ }
}
Modified:
jcr/trunk/exo.jcr.component.ext/src/test/resources/conf/standalone/test-jcr-ext-config.xml
===================================================================
---
jcr/trunk/exo.jcr.component.ext/src/test/resources/conf/standalone/test-jcr-ext-config.xml 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.component.ext/src/test/resources/conf/standalone/test-jcr-ext-config.xml 2010-12-21
10:51:58 UTC (rev 3692)
@@ -348,6 +348,83 @@
</workspace>
</workspaces>
</repository>
+ <repository name="db6" system-workspace="ws"
default-workspace="ws">
+ <security-domain>exo-domain</security-domain>
+ <access-control>optional</access-control>
+
<authentication-policy>org.exoplatform.services.jcr.impl.core.access.JAASAuthenticator</authentication-policy>
+ <workspaces>
+ <workspace name="ws">
+ <!-- for system storage -->
+ <container
class="org.exoplatform.services.jcr.impl.storage.jdbc.optimisation.CQJDBCWorkspaceDataContainer">
+ <properties>
+ <property name="source-name"
value="jdbcjcr24" />
+ <property name="dialect" value="hsqldb"
/>
+ <property name="multi-db" value="false"
/>
+ <property name="update-storage" value="true"
/>
+ <property name="max-buffer-size" value="200k"
/>
+ <property name="swap-directory"
value="target/temp/swap/db6_ws" />
+ </properties>
+ </container>
+ <cache enabled="true">
+ <properties>
+ <property name="max-size" value="5k" />
+ <property name="live-time" value="1h" />
+ </properties>
+ </cache>
+ <query-handler
class="org.exoplatform.services.jcr.impl.core.query.lucene.SearchIndex">
+ <properties>
+ <property name="index-dir"
value="target/temp/index/db6_ws" />
+ </properties>
+ </query-handler>
+ </workspace>
+ <workspace name="ws1">
+ <container
class="org.exoplatform.services.jcr.impl.storage.jdbc.optimisation.CQJDBCWorkspaceDataContainer">
+ <properties>
+ <property name="source-name"
value="jdbcjcr25" />
+ <property name="dialect" value="hsqldb"
/>
+ <property name="multi-db" value="false"
/>
+ <property name="update-storage" value="true"
/>
+ <property name="max-buffer-size" value="200k"
/>
+ <property name="swap-directory"
value="target/temp/swap/db6_ws1" />
+ </properties>
+ </container>
+ <cache enabled="true">
+ <properties>
+ <property name="max-size" value="5k" />
+ <property name="live-time" value="1h" />
+ </properties>
+ </cache>
+ <query-handler
class="org.exoplatform.services.jcr.impl.core.query.lucene.SearchIndex">
+ <properties>
+ <property name="index-dir"
value="target/temp/index/db6_ws1" />
+ </properties>
+ </query-handler>
+ </workspace>
+ <workspace name="ws2">
+ <container
class="org.exoplatform.services.jcr.impl.storage.jdbc.optimisation.CQJDBCWorkspaceDataContainer">
+ <properties>
+ <property name="source-name"
value="jdbcjcr26" />
+ <property name="dialect" value="hsqldb"
/>
+ <property name="multi-db" value="false"
/>
+ <property name="update-storage" value="true"
/>
+ <property name="max-buffer-size" value="200k"
/>
+ <property name="swap-directory"
value="target/temp/swap/db6_ws2" />
+ </properties>
+ </container>
+ <cache enabled="true">
+ <properties>
+ <property name="max-size" value="5k" />
+ <property name="live-time" value="1h" />
+ </properties>
+ </cache>
+ <query-handler
class="org.exoplatform.services.jcr.impl.core.query.lucene.SearchIndex">
+ <properties>
+ <property name="index-dir"
value="target/temp/index/db6_ws2" />
+ </properties>
+ </query-handler>
+ </workspace>
+ </workspaces>
+ </repository>
<repository name="db7" system-workspace="ws"
default-workspace="ws">
<security-domain>exo-domain</security-domain>
<access-control>optional</access-control>
Modified:
jcr/trunk/exo.jcr.docs/exo.jcr.docs.developer/en/src/main/docbook/en-US/modules/jcr/backup/backup-client.xml
===================================================================
---
jcr/trunk/exo.jcr.docs/exo.jcr.docs.developer/en/src/main/docbook/en-US/modules/jcr/backup/backup-client.xml 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.docs/exo.jcr.docs.developer/en/src/main/docbook/en-US/modules/jcr/backup/backup-client.xml 2010-12-21
10:51:58 UTC (rev 3692)
@@ -1005,7 +1005,7 @@
stop <backup_id>
status <backup_id>
restores <repo[/ws]>
- restore <repo[/ws]> <backup_id>
<pathToConfigFile>
+ restore [remove-exists] [<repo[/ws]>]
{<backup_id>|<backup_set_path>}
[<pathToConfigFile>]
list [completed]
info
drop [force-close-session] <repo[/ws]>
@@ -1025,8 +1025,10 @@
<repo[/ws]> -
/<reponsitory-name>[/<workspace-name>] the repository or
workspace
<backup_dir> - path to folder for backup on remote server
<backup_id> - the identifier for backup
+ <backup_set_dir> - path to folder with backup set on remote server
<incr> - incemental job period
<pathToConfigFile> - path (local) to repository or workspace
configuration
+ remove-exists - removed fully (db, value storage, index) existed
repository/workspace
force-close-session - close opened sessions on repositpry or
workspace.</programlisting>
</section>
@@ -1227,6 +1229,259 @@
path to backup folder :
/home/rainf0x/java/exo-working/JCR-839/exo-tomcat/bin/../temp/backup
restore state : successful</programlisting>
</section>
+
+ <section>
+ <title>Restoring workspace and remove exists workspace</title>
+
+ <para>Restore to workspace "backup" and remove fully (will be
removed
+ content from db, value storage, index) exists workspace, for restore
+ need the <backup_id> of completed backup and path to file with
+ workspace configuration:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
remove-exists /repository/backup 6c302adc7f00010100df88d29535c6ee
/home/rainf0x/java/exo-working/JCR-839/exo-jcr-config_backup.xml</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring workspace from backup set</title>
+
+ <para>Restore to workspace "backup", for restore need the
+ <backup_set_path> (<backup_set_path> is path to backup
set
+ folder on server side) of completed backup and path to file with
+ workspace configuration:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
/repository/backup /tmp/123/repository_backup-20101220_114156
/home/rainf0x/java/exo-working/JCR-839/exo-jcr-config_backup.xml</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring workspace from backup set and remove exists
+ workspace</title>
+
+ <para>Restore to workspace "backup" and remove fully (will be
removed
+ content from db, value storage, index) exists workspace, for restore
+ need the <backup_set_path> (<backup_set_path> is path
to
+ backup set folder on server side) of completed backup and path to file
+ with workspace configuration:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
remove-exists /repository/backup /repository/backup
/tmp/123/repository_backup-20101220_114156
/home/rainf0x/java/exo-working/JCR-839/exo-jcr-config_backup.xml</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring workspace with original configuation </title>
+
+ <para>Restore to workspace "backup" with original configuration of
+ workspace (the original configuration was stored in backup set), for
+ restore need the <backup_id> of completed backup:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
6c302adc7f00010100df88d29535c6ee</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring workspace with original configuation and remove exists
+ workspace</title>
+
+ <para>Restore to workspace "backup" with original configuration of
+ workspace (the original configuration was stored in backup set) and
+ remove fully (will be removed content from db, value storage, index)
+ exists workspace, for restore need the <backup_id> of completed
+ backup:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
remove-exists 6c302adc7f00010100df88d29535c6ee</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring workspace from backup set with original
+ configuation</title>
+
+ <para>Restore to workspace "backup" with original configuration of
+ workspace (the original configuration was stored in backup set), for
+ restore need the <backup_set_path> (<backup_set_path>
is
+ path to backup set folder on server side) of completed backup:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
/tmp/123/repository_backup-20101220_114156</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring workspace from backup set with original configuation
+ and remove exists workspace</title>
+
+ <para>Restore to workspace "backup" and remove fully (will be
removed
+ content from db, value storage, index) exists workspace with original
+ configuration of workspace (the original configuration was stored in
+ backup set), for restore need the <backup_set_path>
+ (<backup_set_path> is path to backup set folder on server side) of
+ completed backup:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
remove-exists /tmp/123/repository_backup-20101220_114156</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring repository</title>
+
+ <para>Restore to repository "repository" , for restore need the
+ <backup_id> of completed backup and path to file with repository
+ configuration:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
remove-exists /repository 6c302adc7f00010100df88d29535c6ee
/home/rainf0x/java/exo-working/JCR-839/exo-jcr-config.xml</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring repository and remove exists repository</title>
+
+ <para>Restore to repositoy "repository" and remove fully (will be
+ removed content from db, value storage, index) exists repository, for
+ restore need the <backup_id> of completed backup and path to file
+ with repository configuration:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
remove-exists /repository 6c302adc7f00010100df88d29535c6ee
/home/rainf0x/java/exo-working/JCR-839/exo-jcr-config.xml</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring repository from backup set</title>
+
+ <para>Restore to repository "repository", for restore need the
+ <backup_set_path> (<backup_set_path> is path to backup
set
+ folder on server side) of completed backup and path to file with
+ repository configuration:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore /repository
/tmp/123/repository_repository_backup_1292833493681
/home/rainf0x/java/exo-working/JCR-839/exo-jcr-config.xml</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring repository from backup set and remove exists
+ repository</title>
+
+ <para>Restore to repository "repository" and remove fully (will be
+ removed content from db, value storage, index) exists repository, for
+ restore need the <backup_set_path> (<backup_set_path>
is
+ path to backup set folder on server side) of completed backup and path
+ to file with repository configuration:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
remove-exists /repository /repository/backup
/tmp/123/repository_repository_backup_1292833493681
/home/rainf0x/java/exo-working/JCR-839/exo-jcr-config.xml</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring repository with original configuation</title>
+
+ <para>Restore to repository "repository" with original
configuration of
+ repository (the original configuration was stored in backup set), for
+ restore need the <backup_id> of completed backup:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
6c302adc7f00010100df88d29535c6ee</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring repository with original configuation and remove exists
+ repository</title>
+
+ <para>Restore to repository "repository" with original
configuration of
+ repository (the original configuration was stored in backup set) and
+ remove fully (will be removed content from db, value storage, index)
+ exists repository, for restore need the <backup_id> of completed
+ backup:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
remove-exists 6c302adc7f00010100df88d29535c6ee</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring repository from backup set with original
+ configuation</title>
+
+ <para>Restore to repository "repository" with original
configuration of
+ repository (the original configuration was stored in backup set), for
+ restore need the <backup_set_path> (<backup_set_path>
is
+ path to backup set folder on server side) of completed backup:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
/tmp/123/repository_repository_backup_1292833493681</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
+
+ <section>
+ <title>Restoring repository from backup set with original configuation
+ and remove exists repository</title>
+
+ <para>Restore to repository "repository" and remove fully (will be
+ removed content from db, value storage, index) exists repository with
+ original configuration of repository (the original configuration was
+ stored in backup set), for restore need the <backup_set_path>
+ (<backup_set_path> is path to backup set folder on server side) of
+ completed backup:</para>
+
+ <programlisting>jcrbackup
http://root:exo@127.0.0.1:8080 restore
remove-exists /tmp/123/repository_repository_backup_1292833493681</programlisting>
+
+ <para>Return:</para>
+
+ <programlisting>Successful :
+ status code = 200</programlisting>
+ </section>
</section>
<section>
Modified:
jcr/trunk/exo.jcr.docs/exo.jcr.docs.developer/en/src/main/docbook/en-US/modules/jcr/backup/exojcr-backup-service.xml
===================================================================
---
jcr/trunk/exo.jcr.docs/exo.jcr.docs.developer/en/src/main/docbook/en-US/modules/jcr/backup/exojcr-backup-service.xml 2010-12-21
09:43:31 UTC (rev 3691)
+++
jcr/trunk/exo.jcr.docs/exo.jcr.docs.developer/en/src/main/docbook/en-US/modules/jcr/backup/exojcr-backup-service.xml 2010-12-21
10:51:58 UTC (rev 3692)
@@ -664,6 +664,72 @@
* if configuration exception occurred
*/
void restoreRepository(String repositoryBackupIdentifier, boolean asynchronous) throws
BackupOperationException,
+ BackupConfigurationException;
+
+ /**
+ * Restore existing workspace. Previous data will be deleted.
+ * For getting status of workspace restore can use
+ * BackupManager.getLastRestore(String repositoryName, String workspaceName) method
+ * WorkspaceEntry for restore should be contains in BackupChainLog.
+ *
+ * @param workspaceBackupSetDir
+ * the directory with backup set
+ * @param asynchronous
+ * if 'true' restore will be in asynchronous mode (i.e. in separated
thread)
+ * @throws BackupOperationException
+ * if backup operation exception occurred
+ * @throws BackupConfigurationException
+ * if configuration exception occurred
+ */
+ void restoreExistingWorkspace(File workspaceBackupSetDir, boolean asynchronous)
+ throws BackupOperationException, BackupConfigurationException;
+
+ /**
+ * Restore existing repository. Previous data will be deleted.
+ * For getting status of repository restore can use
+ * BackupManager.getLastRestore(String repositoryName) method.
+ * ReprositoryEntry for restore should be contains in BackupChainLog.
+ *
+ * @param repositoryBackupSetDir
+ * the directory with backup set
+ * @param asynchronous
+ * if 'true' restore will be in asynchronous mode (i.e. in separated
thread)
+ * @throws BackupOperationException
+ * if backup operation exception occurred
+ * @throws BackupConfigurationException
+ * if configuration exception occurred
+ */
+ void restoreExistingRepository(File repositoryBackupSetDir, boolean asynchronous)
+ throws BackupOperationException, BackupConfigurationException;
+
+ /**
+ * WorkspaceEntry for restore should be contains in BackupChainLog.
+ *
+ * @param workspaceBackupSetDir
+ * the directory with backup set
+ * @param asynchronous
+ * if 'true' restore will be in asynchronous mode (i.e. in separated
thread)
+ * @throws BackupOperationException
+ * if backup operation exception occurred
+ * @throws BackupConfigurationException
+ * if configuration exception occurred
+ */
+ void restoreWorkspace(File workspaceBackupSetDir, boolean asynchronous) throws
BackupOperationException,
+ BackupConfigurationException;
+
+ /**
+ * ReprositoryEntry for restore should be contains in BackupChainLog.
+ *
+ * @param repositoryBackupSetDir
+ * the directory with backup set
+ * @param asynchronous
+ * if 'true' restore will be in asynchronous mode (i.e. in separated
thread)
+ * @throws BackupOperationException
+ * if backup operation exception occurred
+ * @throws BackupConfigurationException
+ * if configuration exception occurred
+ */
+ void restoreRepository(File repositoryBackupSetDir, boolean asynchronous) throws
BackupOperationException,
BackupConfigurationException;</programlisting>
</section>