I am new to couchbase lite implementation, i am working on Android platform and i have created a database,saved a simple document in it. Now i want to extract the database and view the document saved in it. I placed a sample json in raw folder, read from raw and converted to hashmap.
Below are all the details
CODE
DatabaseManager class to create database
package com.example.couchbasesample;
import android.content.Context;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.DatabaseConfiguration;
import java.io.File;
public class DatabaseManager {
private final static String DATABASE_NAME = "couchbase_test";
public Database database;
private static DatabaseManager instance = null;
public DatabaseManager(Context context) {
// Set database configuration
try {
// Set Database configuration
DatabaseConfiguration config = new DatabaseConfiguration(context);
File dir = context.getDir("COUCH_ANDROID",Context.MODE_PRIVATE);
config.setDirectory(dir.toString());
// Create / Open a database with specified name and configuration
database = new Database(DATABASE_NAME, config);
}
catch (CouchbaseLiteException e) {
e.printStackTrace();
}
}
public static DatabaseManager getSharedInstance(Context context) {
if (instance == null) {
instance = new DatabaseManager(context);
}
return instance;
}
}
MainActivity
package com.example.couchbasesample;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.couchbase.lite.MutableDocument;
import com.google.gson.Gson;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.HashMap;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
private DatabaseManager dbMgr;
#BindView(R.id.btnSave)
Button btnSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// Initialize couchbase lite database manager
dbMgr = new DatabaseManager(this);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
JSONObject customerJSON = new JSONObject(getFileFromResources(MainActivity.this, "samplecustomer"));
/* HashMap<String, JSONObject> customerTest = new HashMap<>();
customerTest.put("1", customerJSON);*/
HashMap<String, Object> yourHashMap = new Gson().fromJson(customerJSON.toString(), HashMap.class);
MutableDocument doc = new MutableDocument(yourHashMap);
// 3. Save document to database.
dbMgr.database.save(doc);
Toast.makeText(MainActivity.this, "saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
public static String getFileFromResources(Context context, String fileName) {
String json = null;
try {
InputStream is = context.getResources().openRawResource(
context.getResources().getIdentifier(fileName,
"raw", context.getPackageName()));
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
return json;
}
}
WHAT I TRIED
I extracted the database using "Device file explorer" from android studio, when i save the app_COUCH_ANDROID folder and open .sqlite file in DB Browser for SQLite couldn't view the saved document instead it just shows up with random data i am unable to understand.
*Other than this i researched and found the following viewer,but unable to use this as its for MAC OS.
https://github.com/couchbaselabs/CouchbaseLiteViewer*
How i can view the couchbase lite database. Can somebody please help me out with this? Any help will be appreciated.
If you need to lookup documents stored in the database, use the getDocument or any of the Query APIs from within your app.
If you want to query the database outside of the content of the app, then you can use the cblite tool. This is a command line tool that will allow you to open and introspect the cblite2 database.
Any reason why you are trying to look up documents outside the context of the app that is embedding the database? You cannot view the data with a standard sqlite browser because the data is binary encoded and stored in Fleece format.
Related
So as a homework from collage i have to make a simple login app using fingerprint, i followed this video: How to Make a FingerPrint Authentication System in Android Studio and Java
But im getting some error that aren't explained and i can't find a answer form, this is my code:
package com.example.actividad14;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.graphics.Color;
import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.Executor;
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView msg_txt = findViewById(R.id.txt_msg);
Button login_btn = findViewById(R.id.login_btn);
BiometricManager biometricManager = BiometricManager.from(this);
switch (biometricManager.canAuthenticate()){
case BiometricManager.BIOMETRIC_SUCCESS:
msg_txt.setText("You can use the fingerprint sensor to login");
msg_txt.setTextColor(Color.parseColor("#Fafafa"));
break;
case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
msg_txt.setText("The device doesn't have a fingerprint sensor");
login_btn.setVisibility(View.GONE);
break;
case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
msg_txt.setText("The biometric sensor is currently unavailable");
login_btn.setVisibility(View.GONE);
break;
case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
msg_txt.setText("Your device doesn't have any fingerprint saved, please check your security settings");
login_btn.setVisibility(View.GONE);
break;
}
Executor executor = ContextCompat.getMainExecutor(this);
BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this, executor, new androidx.biometric.BiometricPrompt.AuthenticationCallback() {
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
}
#Override
public void onAuthenticationSucceeded(#NonNull androidx.biometric.BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Toast.makeText(getApplicationContext(),"Login Succes!", Toast.LENGTH_SHORT).show();
}
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
}
});
final BiometricPrompt.PrompInfo prompInfo = BiometricPrompt.PrompInfo.Builder()
.setTitle("Login")
.setDescription("Use your fingerprint to login in your app")
.setNegativeButtonText("Cancel")
.build();
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
biometricPrompt.authenticate(prompInfo);
}
});
}
}
At BiometricManager biometricManager = BiometricManager.from(this); im getting "cannot resolve method 'from' in 'biometricmanager'", but every video i have seen says that you create your BiometricManager this way.
At BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this, executor, new androidx.biometric.BiometricPrompt.AuthenticationCallback() { im getting "'BiometricPrompt' has private access in 'android.hardware.biometrics.BiometricPrompt'".
At final BiometricPrompt.PrompInfo prompInfo = BiometricPrompt.PrompInfo.Builder() im getting "cannot resolve PromptInfo"
And finally at biometricPrompt.authenticate(prompInfo); im getting "cannot resolve method '(authenticate(BiometricPrompt.PrompInfo))'"
Sorry for the inconvinience, i fount out what was wrong, instead of using:
import android.hardware.biometrics.BiometricManager;
import android.hardware.biometrics.BiometricPrompt;
use
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
in the build.gradle i used
implementation 'androidx.biometric:biometric:1.2.0-alpha04'
But this can depend on new updates, so try with the newer ones also:
https://mvnrepository.com/artifact/androidx.biometric/biometric?repo=google
And finally i had PrompInfo instead of PromptInfo
This other post really helped me:
Android BiometricPrompt: Cannot resolve symbol PromptInfo
I am trying to create a simple utility application but have issues with merging two word documents with images.
Pls find my below code (i am using Apache POI). The code works fine for Text and other information but fails to merge documents with Images.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
public class WordMerge {
private final OutputStream result;
private final List<InputStream> inputs;
private XWPFDocument first;
public WordMerge(OutputStream result) {
this.result = result;
inputs = new ArrayList<>();
}
public void add(InputStream stream) throws Exception{
inputs.add(stream);
OPCPackage srcPackage = OPCPackage.open(stream);
XWPFDocument src1Document = new XWPFDocument(srcPackage);
if(inputs.size() == 1){
first = src1Document;
} else {
CTBody srcBody = src1Document.getDocument().getBody();
first.getDocument().addNewBody().set(srcBody);
}
}
public void doMerge() throws Exception{
first.write(result);
}
public void close() throws Exception{
result.flush();
result.close();
for (InputStream input : inputs) {
input.close();
}
}
public static void main(String[] args) throws Exception {
FileOutputStream faos = new FileOutputStream("C:/temp/result.docx");
WordMerge wm = new WordMerge(faos);
wm.add( new FileInputStream("C:\\temp\\test.docx") );
wm.add( new FileInputStream("C:\\temp\\word_images.docx") );
wm.doMerge();
wm.close();
}
}
How to read password protected .doc file using java code??
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
public class MsFileReader
{
public static void readDocFile(String fileName)
{
try
{
File file = new File(fileName);
InputStream fis = new FileInputStream(file);
HWPFDocument doc = new HWPFDocument(fis);
WordExtractor we = new WordExtractor(doc);
String[] paragraphs = we.getParagraphText();
System.out.println("Total no of paragraph "+paragraphs.length);
for (String para : paragraphs)
{
System.out.println(para.toString());
}
fis.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
//Test.doc is password encrypted file
//after running this code it throws exception
//EncryptedDocumentException
readDocFile("C:\\Test.doc");
}
}
I want java code to read password encrypted .doc file.
I get EncryptedDocumentException at HWPFDocument doc = new HWPFDocument(fis);
I compile single groovy source module "in fly" using GroovyClassLoader.parseClass(src) and all is ok.
But problem is when this source module imports other classes, these are not compiled yet. Traditional compiling when I start compilation of one source but other are required and ready on source path, are compiled too.
How can I use GroovyClassLoader with target to compile all other required sources NOT FROM FILESYSYSTEM.
My sources are for example in database, remote http via URI etc.
The key is to make custom URL handling -- you have to implement a URLStreamHandler and a URLConnection.
If you google around, there's some good documentation on how to implement the stream handler and connection classes -- but for what you're doing, you really only need dummy implementations.
Here's some source code to bootstrap you -- it demonstrates how to connect the pieces up. If you provide some implementation of lookupScriptCodeWithJDBCorWhatever you'll be good to go.
import groovy.lang.GroovyResourceLoader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
public class CustomGroovyResourceLoader implements GroovyResourceLoader {
private final GroovyResourceLoader parentLoader;
public CustomGroovyResourceLoader(GroovyResourceLoader parentLoader) {
this.parentLoader = parentLoader;
}
#Override
public URL loadGroovySource(String filename) throws MalformedURLException {
URL resourceURL = null;
if (parentLoader != null) {
resourceURL = parentLoader.loadGroovySource(filename);
}
if (resourceURL == null) {
resourceURL = createURL(filename);
}
return resourceURL;
}
public URL createURL(String resourceName) throws MalformedURLException {
String scriptSourceCode = lookupScriptCodeWithJDBCorWhatever(resourceName);
return new URL(null, "groovy:///" + resourceName,
new GroovyResourceStreamHandler(scriptSourceCode));
}
private String lookupScriptCodeWithJDBCorWhatever(String resourceName) {
//TODO: blah blah blah
return null;
}
class GroovyResourceConnection extends URLConnection {
private final String urlData;
protected GroovyResourceConnection(URL url, String logic) {
super(url);
this.urlData = logic;
}
#Override
public void connect() throws IOException {}
#Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(urlData.getBytes());
}
}
class GroovyResourceStreamHandler extends URLStreamHandler {
private final String scriptSource;
public GroovyResourceStreamHandler(String scriptSource) {
this.scriptSource = scriptSource;
}
#Override
protected URLConnection openConnection(URL u) throws IOException {
GroovyResourceConnection connection = new GroovyResourceConnection(u, scriptSource);
return connection;
}
}
}
You then install this thing with some code that looks like this:
GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
groovyClassLoader.setResourceLoader( new CustomGroovyResourceLoader( groovyClassLoader.getResourceLoader() ) );
I have to link an excel file with a application software which I am developing.The excel file will contain questionnaire for conducting surveys.I have this code which is only able to open a Jpanel to select the file.After I select the file nothing is happening.I wanted to be able to generate a template based on the questions that are in the excel file (like extracting the questions from the excel file and creating a template from it) and which I have to upload on the web later.could you please help me with this?
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
public class SelectFile extends JFrame{
public static void main(String[]args){
JFrame frame = new JFrame();
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Select File for Linking");
frame.setSize(400, 100);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
final JTextField text=new JTextField(20);
JButton b=new JButton("Select File");
text.setBounds(20,20,120,20);
b.setBounds(150,20,80,20);
// b.setText("<html><font color='blue'><u>Select File</u></font></html>");
b.setHorizontalAlignment(SwingConstants.LEFT);
//b.setBorderPainted(false);
//b.setOpaque(false);
// b.setBackground(Color.lightGray);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new OnlyExt());
int returnval = fc.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
text.setText(file.getPath());
}
}
});
container.add(text);
container.add(b);
frame.setVisible(true);
}
}
class OnlyExt extends javax.swing.filechooser.FileFilter{
public boolean accept(File file) {
if (file.isDirectory()) return false;
String name = file.getName().toLowerCase();
return (name.endsWith(".xls"));
}
public String getDescription() { return "Excel ( *.xls)"; }
}
Apache POI http://poi.apache.org/ provides an API for reading / writing Excel Files.
Look over this source for some tips.
import java.io.File;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.border.EmptyBorder;
public class SelectFile {
public static void main(String[]args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFrame frame = new JFrame("Select File for Linking");
// don't use null layouts.
//frame.setLayout(null);
// create a panel so we can add a border
JPanel container = new JPanel(new FlowLayout(3));
container.setBorder(new EmptyBorder(10,10,10,10));
frame.setContentPane(container);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// instead call pack() after components are added
//frame.setSize(400, 100);
final JTextField text=new JTextField(20);
JButton b=new JButton("Select File");
// irrelevant unless button stretched by layout
//b.setHorizontalAlignment(SwingConstants.LEFT);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
String desc = "Excel ( *.xls)";
String[] types = {".xls"};
fc.addChoosableFileFilter(
new FileNameExtensionFilter(desc, types));
int returnval = fc.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
text.setText(file.getPath());
try {
// 1.6+
Desktop.getDesktop().edit(file);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
});
container.add(text);
container.add(b);
frame.pack();
frame.setVisible(true);
}
});
}
}
BTW - The JFrame here would probably be better converted to a JDialog or JOptionPane.