Unable to Backup my database file in Storage directory. Using Room - sqlite

I am trying to back up my database file in to the storage directory. But as soon as I click the save button the application crashes. Saying it cannot open the database.
This the DB helper class.
public abstract class DBHelper extends RoomDatabase {
private static final String DB_NAME = "MyDatabase";
private static String DB_PATH = "/storage/emulated/0/documents/Expenses.db";
private static DBHelper instance;
// public static final String DB_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/appName/database/" ;
public static synchronized DBHelper getDB(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context, DBHelper.class, DB_PATH + DB_NAME)
.fallbackToDestructiveMigration()
.allowMainThreadQueries()
.setJournalMode(JournalMode.TRUNCATE)
.build();
}
return instance;
}
public abstract ExpenseDao expenseDao();
}
I have given all the permissions in the manifest files. So that is not an issue.
Logcat error
2023-01-30 12:11:17.972 10418-10418/com.example.roomlibrary E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.roomlibrary, PID: 10418
android.database.sqlite.SQLiteCantOpenDatabaseException: Cannot open database '/storage/emulated/0/Documentsmnt/sdcard/documents/expenses.dbMyDatabase': Directory /storage/emulated/0/Documentsmnt/sdcard/documents doesn't exist
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:254)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:205)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:505)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:206)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:198)

Is /storage/emulated/0/Documentsmnt/sdcard/documents really expected to exist?
Should it not be /storage/emulated/0/documents i.e. it appears that you may be inadvertently concatenating mnt/sdcard/documents

Related

After accidentally deleting Data Dictionary (app:dictionary) Alfresco doesn't start

One operator deleted Data Dictionary and restarted Alfresco 3.4.12 Enterprise Edition. The context /alfresco doesn't start with the following exception:
17:43:11,100 INFO [STDOUT] 17:43:11,097 ERROR [web.context.ContextLoader] Context initialization failed
org.alfresco.error.AlfrescoRuntimeException: 08050000 Failed to find 'app:dictionary' node
at org.alfresco.repo.action.scheduled.ScheduledPersistedActionServiceImpl.locatePersistanceFolder(ScheduledPersistedActionServiceImpl.java:132)
Looking at the source code in org.alfresco.repo.action.scheduled.ScheduledPersistedActionServiceImpl.java, the path is hardwired.
Then we followed the tip from https://community.alfresco.com/thread/202859-error-failed-to-find-appdictionary-node, editing bootstrap-context.xml, comment out the class.
After the change the error went over, now the RenditionService couldn't start.
We're looking for a way to recover the deleted node, since we can obtain the nodeid from the database. So we created a small class and invoke it through spring in bootstrap-context.xml, but it's failing due to permissions. Could you take a look at the code and tell us what's wrong. The code is:
package com.impulseit.test;
import javax.transaction.UserTransaction;
import org.alfresco.repo.node.archive.NodeArchiveService;
import org.alfresco.repo.node.archive.RestoreNodeReport;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
public class RestoreNode {
private NodeArchiveService nodeArchiveService;
private ServiceRegistry serviceRegistry;
private String nodeName ="archive://SpacesStore/adfc0cfe-e20b-467f-ad71-253aea8f9ac9";
public void setNodeArchiveService(NodeArchiveService value)
{
this.nodeArchiveService = value;
}
public void setServiceRegistry(ServiceRegistry value)
{
this.serviceRegistry = value;
}
public void doRestore() {
RunAsWork<Void> runAsWork = new RunAsWork<Void>()
{
public Void doWork() throws Exception
{
NodeRef nodeRef = new NodeRef(nodeName);
//RestoreNodeReport restoreNodeReport =
UserTransaction trx_A = serviceRegistry.getTransactionService().getUserTransaction();
trx_A.begin();
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
RestoreNodeReport restored = nodeArchiveService.restoreArchivedNode(nodeRef);
trx_A.commit();
return null;
}
};
AuthenticationUtil.runAs(runAsWork,AuthenticationUtil.getSystemUserName());
}
public RestoreNode() {
}
}
The exception is:
19:31:21,747 User:admin ERROR [node.archive.NodeArchiveServiceImpl] An unhandled exception stopped the restore
java.lang.NullPointerException
at org.alfresco.repo.security.permissions.impl.model.PermissionModel.getPermissionReference(PermissionModel.java:1315)
at org.alfresco.repo.security.permissions.impl.PermissionServiceImpl.getPermissionReference(PermissionServiceImpl.java:956)
at org.alfresco.repo.security.permissions.impl.PermissionServiceImpl.hasPermission(PermissionServiceImpl.java:976)
Thank you in advance.
Luis

ExtentReports: detachReporter() method

I am using a suite file with multiple suites inside the testng.xml file as follows:
<suite-files>
<suite-file path="suite1"></suite-file>
<suite-file path="suite2"></suite-file>
</suite-files>
I am initializing ExtentReport in BeforeSuite.
private static void initializeExtentReport(Configuration config) {
if (extent == null) {
extent = new ExtentReports();
htmlReporter = new ExtentHtmlReporter("reportLocation");
ClassLoader classLoader = ExtentReportService.class.getClassLoader();
File extentConfigFile = new File(classLoader.getResource("extent-config.xml").getFile());
htmlReporter.loadXMLConfig(extentConfigFile);
extent.attachReporter(htmlReporter);
extent.setSystemInfo("Environment", config.getAutomationServer());
}
}
In AfterSuite, I am calling flush().
So basically the issue is, when the before suite is called for the second suite, The check (extent==null), is coming false. I also went through the JavaDocs for ExtentReports and I found a method detachReporter() there. But I am not able to access by my IDE. Tried many variations but to no fruition.
EDIT:
Right now what really happens is, I am using custom names for reports, so that no two report names are the same. And, when I was using with the same name, the results would be over written in the same file for the suites.
A better approach here is to use a singleton like so:
public class Extent
implements Serializable {
private static final long serialVersionUID = 1L;
private static class ExtentReportsLoader {
private static final ExtentReports INSTANCE = new ExtentReports();
static {
}
}
public static synchronized ExtentReports getInstance() {
return ExtentReportsLoader.INSTANCE;
}
#SuppressWarnings("unused")
private ExtentReports readResolve() {
return ExtentReportsLoader.INSTANCE;
}
}
Usage:
ExtentReports extent = Extent.getInstance();
So your code becomes:
private static void initializeExtentReport(Configuration config) {
extent = Extent.getInstance();
if (extent.getStartedReporters().isEmpty()) {
htmlReporter = new ExtentHtmlReporter("reportLocation");
ClassLoader classLoader = ExtentReportService.class.getClassLoader();
File extentConfigFile = new File(classLoader.getResource("extent-config.xml").getFile());
htmlReporter.loadXMLConfig(extentConfigFile);
extent.attachReporter(htmlReporter);
extent.setSystemInfo("Environment", config.getAutomationServer());
}
}
I would further recommend getting rid of all shared variables for extent/htmlReporter and directly use the Singleton

What is the correct path string I need for saving files to Azure Apps virtual applications and directories?

I'm using ASP.NET5 / MVC 6. I am trying to use a SQL logger on an app running in Azure Apps. Locally, I can access the directory I want, so I am pretty sure its not a syntax or system agnostic error. This is the part that fails while stepping through on remote debugging. Again, locally it runs and logs normally.
//Local path
private static readonly string _logFilePath = #"C\temp\DatabaseLog.sql";
//Azure App path
private static readonly string _logFilePath = #"\templog\DatabaseLog.sql";
public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)
{
var message = string.Format(
"\n\n--{0}\n{1}",
DateTime.Now,
formatter(state, exception));//.Replace(", [", ",\n ["));
File.AppendAllText(_logFilePath, message); // <-- FAILS HERE
}
I have set \templog as a virtual directory in the Azure portal. See image:
I have also created the folder in the project. See image:
The Azure App storage is mapped to d:\home so I would try to change:
//Azure App path
private static readonly string _logFilePath = #"\templog\DatabaseLog.sql";
to
//Azure App path
private static readonly string _logFilePath = #"d:\site\templog\DatabaseLog.sql";
Wouldn't you still have to map the virtual path to physical?
using either of
private static readonly string _logFilePath = Server.MapPath(#"/templog/DatabaseLog.sql");
or
private static readonly string _logFilePath = HostingEnvironment.MapPath(#"/templog/DatabaseLog.sql");
Have you tried writing to /App_Data?
Does the folder exist on azure?
Maybe there are permissions on the folder that need to be set?

Hazelcast IMap.get() throws HazelcastSerializationException, but IMap.put() works fine

I have an Hazelcast server instance running on a VM. Data is supposed to be stored in a MAP<Integer, User>, where the User class is as following:
public class User implements com.hazelcast.nio.serialization.DataSerializable{
private Integer id;
private String name;
private String nick;
private Boolean sex;
//getters & setters
#Override
public void writeData(ObjectDataOutput out) throws IOException{
out.writeInt(id.intValue());
out.writeUTF(name);
out.writeUTF(nick);
out.writeBoolean(sex);
}
#Override
public void readData(ObjectDataInput in) throws IOException{
id = (Integer) in.readInt();
name = in.readUTF();
nick = in.readUTF();
sex = in.readBoolean();
}
I connect to this server with a client instance and try to add an object to that map:
System.out.println("Map Size: " + map.size());
map.put(1, user);
System.out.println("Map Size: " + map.size());
System.out.println(map.containsKey(1) ? "yes":"no");
System.out.println(map.containsValue(user) ? "yes":"no");
User queried = (User) map.get(1); /*this is line 64*/
System.out.println(queried.toString());
The upper code gives me the following console output:
Map Size: 0
Map Size: 1
yes
yes
And the following Exception for the line User queried = (User) map.get(1);:
Problem while reading DataSerializable, namespace: 0, id: 0, class: com.blabla.User, exception: com.blabla.User.<init>()
What is here the problem? Why can't I read the data I just put in the Map?
Here are the exception details:
com.hazelcast.nio.serialization.DataSerializer.read(DataSerializer.java:114)
com.hazelcast.nio.serialization.DataSerializer.read(DataSerializer.java:36)
com.hazelcast.nio.serialization.StreamSerializerAdapter.read(StreamSerializerAdapter.java:59)
com.hazelcast.nio.serialization.SerializationServiceImpl.toObject(SerializationServiceImpl.java:218)
com.hazelcast.client.spi.impl.ClientClusterServiceImpl._sendAndReceive(ClientClusterServiceImpl.java:172)
com.hazelcast.client.spi.impl.ClientClusterServiceImpl.sendAndReceive(ClientClusterServiceImpl.java:137)
com.hazelcast.client.spi.impl.ClientInvocationServiceImpl.invokeOnTarget(ClientInvocationServiceImpl.java:42)
com.hazelcast.client.spi.impl.ClientInvocationServiceImpl.invokeOnKeyOwner(ClientInvocationServiceImpl.java:53)
com.hazelcast.client.proxy.ClientMapProxy.invoke(ClientMapProxy.java:492)
com.hazelcast.client.proxy.ClientMapProxy.get(ClientMapProxy.java:83)
com.blabla.HazelcastFactory.insertUser(HazelcastFactory.java:64)
java.lang.NoSuchMethodException: com.dileky.User.<init>()
java.lang.Class.getConstructor0(Class.java:2800)
java.lang.Class.getDeclaredConstructor(Class.java:2043)
com.hazelcast.nio.ClassLoaderUtil.newInstance(ClassLoaderUtil.java:54)
com.hazelcast.nio.ClassLoaderUtil.newInstance(ClassLoaderUtil.java:50)
com.hazelcast.nio.serialization.DataSerializer.read(DataSerializer.java:103)
com.hazelcast.nio.serialization.DataSerializer.read(DataSerializer.java:36)
com.hazelcast.nio.serialization.StreamSerializerAdapter.read(StreamSerializerAdapter.java:59)
com.hazelcast.nio.serialization.SerializationServiceImpl.toObject(SerializationServiceImpl.java:218)
com.hazelcast.client.spi.impl.ClientClusterServiceImpl._sendAndReceive(ClientClusterServiceImpl.java:172)
com.hazelcast.client.spi.impl.ClientClusterServiceImpl.sendAndReceive(ClientClusterServiceImpl.java:137)
com.hazelcast.client.spi.impl.ClientInvocationServiceImpl.invokeOnTarget(ClientInvocationServiceImpl.java:42)
com.hazelcast.client.spi.impl.ClientInvocationServiceImpl.invokeOnKeyOwner(ClientInvocationServiceImpl.java:53)
com.hazelcast.client.proxy.ClientMapProxy.invoke(ClientMapProxy.java:492)
com.hazelcast.client.proxy.ClientMapProxy.get(ClientMapProxy.java:83)
com.blabla.HazelcastFactory.insertUser(HazelcastFactory.java:64)
From the stacktrace it seems like your class does not have a default constructor (a constructor without a parameter). If you have defined a constructor with a parameter set the default constructor is not created by the compiler automatically and you would have to define it explicitly.
Alternatively your class or constructor might not be public scoped but package-private or private.
public class User {
// Fields
public User() {
}
// Getters / Setters
}

How to modify folder permissions in a web setup project?

I am using a web setup project to install my ASP.NET app which needs to write to a folder that exists under the main virtual directory folder. How do I configure the setup project to grant the ASPNET user permissions to that folder?
The way to do it is to create a class derived from System.Configuration.Install.Installer. Override the Install() method. The following is an example that changes permissions on a directory and a file, you probably don't want to be so permissive, but it depends on your security context. In order for this to work, the setup project has to run this as a custom action. Add the "Primary Output" from whatever project this class is in. You will also need to pass the directory to the custom action in its properties. The first variable name has to match the code. Like this: /targetdir="[TARGETDIR]\"
[RunInstaller(true)]
public partial class SetPermissions : Installer
{
private const string STR_targetdir = "targetdir";
private const string STR_aspnetUser = "ASPNET";
public SetPermissions()
{
InitializeComponent();
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
Context.LogMessage(
Context.Parameters
.Cast<DictionaryEntry>()
.Select(entry => String.Format("String = {0} Value = {1}", entry.Key, entry.Value))
.Aggregate(new StringBuilder("From install\n"), (accumulator, next) => accumulator.AppendLine(next))
.ToString()
);
string targetDir = Context.Parameters[STR_targetdir];
string dbDir = Path.Combine(targetDir, "db");
AddFullControlPermissionToDir(dbDir, STR_aspnetUser);
string rimdbSqliteFilename = Path.Combine(dbDir, "db.sqlite");
AddFullControlPermissionToFile(rimdbSqliteFilename, STR_aspnetUser);
string logsDir = Path.Combine(targetDir, "logs");
AddFullControlPermissionToDir(logsDir, STR_aspnetUser);
}
private static void AddFullControlPermissionToDir(string dir, string user)
{
DirectorySecurity directorySecurity = Directory.GetAccessControl(dir);
directorySecurity.AddAccessRule(
new FileSystemAccessRule(
user,
FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
Directory.SetAccessControl(dir, directorySecurity);
}
private static void AddFullControlPermissionToFile(string filename, string user)
{
FileSecurity fileSecurity = File.GetAccessControl(filename);
fileSecurity.AddAccessRule(
new FileSystemAccessRule(
user,
FileSystemRights.FullControl,
AccessControlType.Allow));
File.SetAccessControl(filename, fileSecurity);
}
}

Resources