Uploading local .csv to Firebase Storage - java

I'm creating an app for schoolproject that reads data from firebase database, converts it to a .csv file and then I want to upload this file to firebase storage so that the user then can share it with just the downloadUrl.
Below is the class for creating a csvfile and then upload it to firebase storage.
see csvUploader.
import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.CancellableTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageMetadata;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class CsvHandler {
private MainActivity mainActivity;
public CsvHandler(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
/**
* Method that writes a two-dimensional array with strings, to a .csv-file with a specified
* date as the filename.
*
* #param dataArray array to write to a .csv
* #param callDate specified date that gets passed to the filename
*/
public void writeFileFromArray(String callDate, String[][] dataArray) {
String filename = callDate + ".csv";
//Creates the String which will make up the text for the .csv
String csvText = "";
//Adds all elements in Array to the string
//TODO: Make sure this parses the text correctly to .csv-file format (dependent on Sara & Annies method)
for (int i = 0; i < dataArray.length; i++) {
for (int j = 0; j < dataArray[0].length; j++) {
csvText = csvText + dataArray[i][j];
}
}
//Creates a FileOutputStream for writing the file to internal storage
FileOutputStream outputStream;
try {
//Opens a FileOutputStream to a file with the specified filename.
//Creates file if it doesn't exist.
outputStream = mainActivity.openFileOutput(filename, Context.MODE_PRIVATE);
//Writes the string to the specified file
outputStream.write(csvText.getBytes());
//Closes the FileOutputStream to produce a file
outputStream.close();
} catch (FileNotFoundException e) {
Toast.makeText(mainActivity, "Internal Error: No such file found", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(mainActivity, "Internal Error: IOException", Toast.LENGTH_SHORT).show();
}
}
/**
* TESTMETOD
* TODO: Ta bort innan merge med master. Låt stå till develop
*/
public void readCsvFile(String callDate) {
try {
String Message;
FileInputStream fileInputStream = mainActivity.openFileInput(callDate + ".csv");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((Message = bufferedReader.readLine()) != null) {
stringBuffer.append(Message + "\n");
}
Toast.makeText(mainActivity, stringBuffer.toString(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Method to extract a filePath for a specified date.
*
* #param callDate a String with the date to return a filepath for
* #return the filepath for the specified date
*/
public String getFilePath(String callDate) {
String filePath = mainActivity.getFilesDir().getAbsolutePath() + callDate + ".csv";
Log.e("LOG", "Output from getFilePath " + filePath);
return filePath;
}
public void csvUploader(String filePath, final String callDate) {
StorageReference mStorageReference = FirebaseStorage.getInstance().getReference();
Log.e("LOG", "Entering CSVUPLOADER");
Uri file = Uri.fromFile(new File(filePath));
Log.e("csvUploader Uri File:", filePath.toString());
// Create the file metadata
StorageMetadata metadata = new StorageMetadata.Builder().setContentType("text/csv").build();
Log.e("LOG","Metadata: " + metadata.toString());
// Upload file and metadata to the path 'reports/date.csv'
CancellableTask uploadTask = mStorageReference.child("reports/" + file.getLastPathSegment()).putFile(file, metadata);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//System.out.println("Upload is " + progress + "% done");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Log.e("LOG", "Unsucessfull in CSVUPLOADER");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Handle successful uploads on complete
//Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
//mainActivity.setDownloadLink(downloadUrl);
Log.e("LOG", "Successfull in CSVUPLOADER");
mainActivity.getUrlAsync(callDate);
}
});
}
}
Most of this are the example code from firebase.google.com But i don't get it to work.
Logs:
E/LOG: Output from getFilePath: /data/user/0/com.example.eliasvensson.busify/files2016-05-18.csv
E/LOG: Entering CSVUPLOADER
E/LOG: Metadata: com.google.firebase.storage.StorageMetadata#7fd93a9
E/LOG: Unsucessfull in CSVUPLOADER
Whats wrong?
I gather that I "reserve" the path on my storage bucket, and then place the file in that place. Is that correct?
Any help would be appreciated.

It all actually almost worked.
the filePath was wrong, outputing /data/user/0/com.example.eliasvensson.busify/files2016-05-18.csv
when expecting
/data/user/0/com.example.eliasvensson.busify/files/2016-05-18.csv (notice the slash between files and date)

Related

unzipping files in /data/data/ folder - Android Java Programming

How would I programmatically unzip backed up data directly into a /data/data/com.appname folder from the SD Card?
I am able to directly unzip folders in the /data/data/com.appname folder using ES File Explorer, however I need to automate this via the app I'm developing.
I've tried the following code, Unfortunately I am only able to unzip to the SD Card and data folder of my app.
I'm guessing this is due to some form of app/folder security?
MainActivity.java
package fb.ziptester;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonOnClick(View v) {
TextView zipSource = (TextView)findViewById(R.id.zip_source);
TextView zipDest = (TextView)findViewById(R.id.zip_dest);
String sZipSource = "/storage/sdcard1/ACC/BU.zip";
String sZipDest = "/data/data/com.appname/";
zipSource.setText(sZipSource);
zipDest.setText(sZipDest);
UnzipUtility zipUtil = new UnzipUtility();
try {
zipUtil.unzip(sZipSource, sZipDest);
} catch(Exception ex) {
//TODO
}
}
}
package fb.ziptester;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
UnzipUtility.java
public class UnzipUtility {
/**
* Size of the buffer to read/write data
*/
private static final int BUFFER_SIZE = 4096;
/**
* Extracts a zip file specified by the zipFilePath to a directory specified by
* destDirectory (will be created if does not exists)
* #param zipFilePath
* #param destDirectory
* #throws IOException
*/
public void unzip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
// iterates over entries in the zip file
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
extractFile(zipIn, filePath);
} else {
// if the entry is a directory, make the directory
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
/**
* Extracts a zip entry (file entry)
* #param zipIn
* #param filePath
* #throws IOException
*/
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
}
Any help would be much appreciated.
Thank you.

Couldn't append the text onto a Google Drive File

I am trying to append text to a text file on the Google Drive. But when I write, it whole file is overwritten. Why can't I just add the text in the end of the file?
DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, id);
file.open(mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult driveContentsResult) {
msg.Log("ContentsOpenedCallBack");
if (!driveContentsResult.getStatus().isSuccess()) {
Log.i("Tag", "On Connected Error");
return;
}
final DriveContents driveContents = driveContentsResult.getDriveContents();
try {
msg.Log("onWrite");
OutputStream outputStream = driveContents.getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
writer.append(et.getText().toString());
writer.close();
driveContents.commit(mGoogleApiClient, null);
} catch (IOException e) {
e.printStackTrace();
}
}
});
Finally I've found the answer to append the text on the drive document.
DriveContents contents = driveContentsResult.getDriveContents();
try {
String input = et.getText().toString();
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("\n"+input);
writer.close();
driveContentsResult.getDriveContents().commit(mGoogleApiClient, null);
} catch (IOException e) {
e.printStackTrace();
}
SO
The reason is that commit's default resolution strategy is to overwrite existing files. Check the API docs and see if there is a way to append changes.
For anyone facing this problem in 2017 :
Google has some methods to append data Here's a link!
Though copying the method from google didn't worked entirely for me , so here is the class which would append data : ( Please note this is a modified version of this code link )
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveApi.DriveIdResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
/**
* An activity to illustrate how to edit contents of a Drive file.
*/
public class EditContentsActivity extends BaseDemoActivity {
private static final String TAG = "EditContentsActivity";
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
final ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
#Override
public void onResult(DriveIdResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Cannot find DriveId. Are you authorized to view this file?");
return;
}
DriveId driveId = result.getDriveId();
DriveFile file = driveId.asDriveFile();
new EditContentsAsyncTask(EditContentsActivity.this).execute(file);
}
};
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(EditContentsActivity.this);
Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
.setResultCallback(idCallback);
}
public class EditContentsAsyncTask extends ApiClientAsyncTask<DriveFile, Void, Boolean> {
public EditContentsAsyncTask(Context context) {
super(context);
}
#Override
protected Boolean doInBackgroundConnected(DriveFile... args) {
DriveFile file = args[0];
SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(EditContentsActivity.this);
System.out.println("0"+sp.getString("drive_id","1"));
DriveContentsResult driveContentsResult=file.open(getGoogleApiClient(), DriveFile.MODE_READ_WRITE, null).await();
System.out.println("1");
if (!driveContentsResult.getStatus().isSuccess()) {
return false;
}
DriveContents driveContents = driveContentsResult.getDriveContents();
try {
System.out.println("2");
ParcelFileDescriptor parcelFileDescriptor = driveContents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
System.out.println("3");
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("hello world");
writer.close();
System.out.println("4");
driveContents.commit(getGoogleApiClient(), null).await();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
};
#Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
}
Existing_File_id is the resource id. Here is one link if you need resource id a link

Calling Java Method from Javascript in Android Project - PhoneGap

I have the following Java Class
package com.phonegap.plugins.video;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
public class VideoPlayer extends CordovaPlugin {
private static final String YOU_TUBE = "youtube.com";
private static final String ASSETS = "file:///android_asset/";
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
//this.greatMethod();
try {
if (action.equals("playVideo")) {
playVideo(args.getString(0));
}
else {
status = PluginResult.Status.INVALID_ACTION;
}
callbackContext.sendPluginResult(new PluginResult(status, result));
} catch (JSONException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
} catch (IOException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION));
}
return true;
}
private void playVideo(String url) throws IOException {
if (url.contains("bit.ly/") || url.contains("goo.gl/") || url.contains("tinyurl.com/") || url.contains("youtu.be/")) {
//support for google / bitly / tinyurl / youtube shortens
URLConnection con = new URL(url).openConnection();
con.connect();
InputStream is = con.getInputStream();
//new redirected url
url = con.getURL().toString();
is.close();
}
// Create URI
Uri uri = Uri.parse(url);
Intent intent = null;
// Check to see if someone is trying to play a YouTube page.
if (url.contains(YOU_TUBE)) {
// If we don't do it this way you don't have the option for youtube
uri = Uri.parse("vnd.youtube:" + uri.getQueryParameter("v"));
if (isYouTubeInstalled()) {
intent = new Intent(Intent.ACTION_VIEW, uri);
} else {
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.google.android.youtube"));
}
} else if(url.contains(ASSETS)) {
// get file path in assets folder
String filepath = url.replace(ASSETS, "");
// get actual filename from path as command to write to internal storage doesn't like folders
String filename = filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
// Don't copy the file if it already exists
File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + filename);
if (!fp.exists()) {
this.copy(filepath, filename);
}
// change uri to be to the new file in internal storage
uri = Uri.parse("file://" + this.cordova.getActivity().getFilesDir() + "/" + filename);
//return uri; /*NEED TO RETUNRN THE URI TO THE CALLED TO GIVE THEMENEW LOCATION OF THE FILE CREATED BY THIS CLASS*/
// Display video player
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/mp4");
} else {
// Display video player
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/mp4");
}
this.cordova.getActivity().startActivity(intent);
}
private void copy(String fileFrom, String fileTo) throws IOException {
// get file to be copied from assets
InputStream in = this.cordova.getActivity().getAssets().open(fileFrom);
// get file where copied too, in internal storage.
// must be MODE_WORLD_READABLE or Android can't play it
FileOutputStream out = this.cordova.getActivity().openFileOutput(fileTo, Context.MODE_WORLD_READABLE);
// Transfer bytes from in to out
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.flush();
out.close();
}
private boolean isYouTubeInstalled() {
PackageManager pm = this.cordova.getActivity().getPackageManager();
try {
pm.getPackageInfo("com.google.android.youtube", PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
public String greatMethod(){
System.out.println("Great Method return");
return "great";
}
}
I have following in my config.xml file
<plugin name="VideoPlayer" value="com.phonegap.plugins.video.VideoPlayer"/>
I want to call say the 'greatMethod' from the javascript file. how do I do that. calling the play method like following works but calling other methods do not work and the play method is not even in the given class.
WORKS:
window.plugins.videoPlayer.play("file:///android_asset/www/videos/myVideo.mp4")
DOES NOT WORK:
alert(window.plugins.videoPlayer.greatMethod());
Any help will be much appreciated.
Have you add greatMethod method into JavaScript PhoneGap object?
Just like following JavaScript code
var videoPlayer=function(){};
videoPlayer.prototype.greatMethod = function(params, success, fail){
return PhoneGap.exec(
function(args){
success(args);
},
function(args){
fail(args);
},
'VideoPlayer',
'greatMethod'
);
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin('videoPlayer', new videoPlayer());
});

file upload in FileNet?

I'm writing code to upload a file in FileNet.
A standalone java program to take the some inputs, and upload it in FileNet. I'm new to FileNet. Can you help me out, How to do it?
You can use Document.java provided by IBM for your activities and many other Java classes
package fbis.apitocasemanager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import com.user.DocumentUtil;
public class Addfilescasemanager {
/**
* #param args
*/
public static void addfiles_toicm(String directory, String lFolderPath)
{
try {
DocumentUtil.initialize();
String path = directory;
System.out.println("This is the path:..............................."
+ path);
String file_name;
File folder = new File(directory);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
file_name = listOfFiles[i].getName();
System.out.println(file_name);
String filePaths = directory + file_name;
// File file = new File("C:\\FNB\\att.jpg");
File file = new File(filePaths);
InputStream attStream = null;
attStream = new FileInputStream(file);
DocumentUtil.addDocumentWithStream(lFolderPath, attStream,
"image/jpeg", file_name, "Document");
}
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}//end of method
public static void addfile_toicm(File file_name, String lFolderPath)
{
try {
DocumentUtil.initialize();
InputStream attStream = null;
attStream = new FileInputStream(file_name);
DocumentUtil.addDocumentWithStream(lFolderPath, attStream,
"image/jpeg", file_name.getName(), "Document");
System.out.println("File added successfully");
} catch (Exception e)
{
System.out.println(e.getMessage());
}
}//end of method
public static void main(String nag[])
{
addfiles_toicm("E:\\FSPATH1\\BLR_14122012_001F1A\\","/IBM Case Manager/Solution Deployments/Surakshate Solution for form 2/Case Types/FISB_FactoriesRegistration/Cases/2012/12/06/16/000000100103");
}
}
and my DocumentUtil class is
package com.user;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.security.auth.Subject;
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.constants.AutoClassify;
import com.filenet.api.constants.AutoUniqueName;
import com.filenet.api.constants.CheckinType;
import com.filenet.api.constants.DefineSecurityParentage;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Connection;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Document;
import com.filenet.api.core.Domain;
import com.filenet.api.core.Factory;
import com.filenet.api.core.Folder;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.ReferentialContainmentRelationship;
import com.filenet.api.util.UserContext;
public class DocumentUtil {
public static ObjectStore objectStore = null;
public static Domain domain = null;
public static Connection connection = null;
public static void main(String[] args)
{
initialize();
/*
addDocumentWithPath("/FNB", "C:\\Users\\Administrator\\Desktop\\Sample.txt.txt",
"text/plain", "NNN", "Document");
*/
File file = new File("E:\\Users\\Administrator\\Desktop\\TT.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addDocumentWithStream("/FNB", fis, "text/plain", "My New Doc", "Document");
}
public static void initialize()
{
System.setProperty("WASP.LOCATION", "C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear \\cews.war\\WEB-INF\\classes\\com\\filenet\\engine\\wsi");
System.setProperty("SECURITY.AUTH.LOGIN.CONFIG",
"C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear\\client-download.war\\FileNet\\Download\\dap501.153\\jaas.conf.wsi");
System.setProperty(":SECURITY.AUTH.LOGIN.CONFIG",
"C:\\Progra~1\\IBM\\WebSphere\\AppServer\\profiles\\AppSrv01\\installedApps\\P8Node01Cell\\FileNetEngine.ear\\client-download.war\\FileNet\\Download\\dap501.153\\jaas.conf.wsi");
System.setProperty("java.security.auth.login.config","C:\\Progra~1\\IBM\\WebSphere\\AppServer\\java\\jre");
connection = Factory.Connection.getConnection(CEConnection.uri);
Subject sub = UserContext.createSubject(connection,
com.user.CEConnection.username, CEConnection.password,
CEConnection.stanza);
UserContext.get().pushSubject(sub);
domain = Factory.Domain.getInstance(connection, null);
objectStore = Factory.ObjectStore.fetchInstance(domain, "TARGET", null);
System.out.println("\n\n objectStore--> " + objectStore.get_DisplayName());
}
public static void addDocumentWithPath(String folderPath, String filePath,
String mimeType, String docName, String docClass) {
Folder folder = Factory.Folder.fetchInstance(objectStore,
folderPath, null);
System.out.println("\n\n Folder ID: " + folder.get_Id());
// Document doc = Factory.Document.createInstance(os, classId);
Document doc = CEUtil.createDocWithContent(new File(filePath), mimeType,
objectStore, docName, docClass);
doc.save(RefreshMode.REFRESH);
doc = CEUtil.createDocNoContent(mimeType, objectStore, docName, docClass);
doc.save(RefreshMode.REFRESH);
CEUtil.checkinDoc(doc);
ReferentialContainmentRelationship rcr = CEUtil.fileObject(objectStore, doc, folderPath);
rcr.save(RefreshMode.REFRESH);
}
public static void addDocumentWithStream(String folderPath,
InputStream inputStream, String mimeType,
String docName, String docClass) {
Folder folder = Factory.Folder.fetchInstance(objectStore,
folderPath, null);
System.out.println("\n\n Folder ID: " + folder.get_Id());
// Document doc = Factory.Document.createInstance(os, classId);
Document doc = Factory.Document.createInstance(objectStore, null);
ContentElementList contEleList = Factory.ContentElement.createList();
ContentTransfer ct = Factory.ContentTransfer.createInstance();
ct.setCaptureSource(inputStream);
ct.set_ContentType(mimeType);
ct.set_RetrievalName(docName);
contEleList.add(ct);
doc.set_ContentElements(contEleList);
doc.getProperties().putValue("DocumentTitle", docName);
doc.set_MimeType(mimeType);
doc.checkin(AutoClassify.AUTO_CLASSIFY, CheckinType.MAJOR_VERSION);
doc.save(RefreshMode.REFRESH);
ReferentialContainmentRelationship rcr = folder.file(doc,
AutoUniqueName.AUTO_UNIQUE, docName,
DefineSecurityParentage.DO_NOT_DEFINE_SECURITY_PARENTAGE);
rcr.save(RefreshMode.REFRESH);
/*
doc.save(RefreshMode.REFRESH);
doc = CEUtil.createDocNoContent(mimeType, objectStore, docName, docClass);
CEUtil.checkinDoc(doc);
ReferentialContainmentRelationship rcr = CEUtil.fileObject(objectStore, doc, folderPath);
rcr.save(RefreshMode.REFRESH);
*/
}
public static ObjectStore getObjecctStore()
{
if (objectStore != null) {
return objectStore;
}
// Make connection.
com.filenet.api.core.Connection conn = Factory.Connection
.getConnection(CEConnection.uri);
Subject subject = UserContext.createSubject(conn,
CEConnection.username, CEConnection.password, null);
UserContext.get().pushSubject(subject);
try {
// Get default domain.
Domain domain = Factory.Domain.getInstance(conn, null);
// Get object stores for domain.
objectStore = Factory.ObjectStore.fetchInstance(domain, "TARGET",
null);
System.out.println("\n\n Connection to Content Engine successful !!");
} finally {
UserContext.get().popSubject();
}
return objectStore;
}
}
The above answer is extremely good. Just wanted to save people some time but I don't have the points to comment so am adding this as an answer.
Eclipse wasted a lot of my time getting the above to work because it suggested the wrong classes to import. Here's the list of correct ones:
import com.filenet.api.collection.ContentElementList;
import com.filenet.api.constants.AutoClassify;
import com.filenet.api.constants.AutoUniqueName;
import com.filenet.api.constants.CheckinType;
import com.filenet.api.constants.DefineSecurityParentage;
import com.filenet.api.constants.RefreshMode;
import com.filenet.api.core.Document;
import com.filenet.api.core.ObjectStore;
import com.filenet.api.core.ContentTransfer;
import com.filenet.api.core.Folder;
import com.filenet.api.core.Factory;
import com.filenet.api.core.ReferentialContainmentRelationship;

Vaadin Upload component - directly upload to mongo repository

I want to use a vaadin upload component in my webapplication and directly upload files to mongo db in gridfs format.
My current implementation use a temporary storage location to first upload file and then store in mongo converting to gridfs.
here is my upload component code: I have implement Receiver interface method recieveUpload
private File file;
private String tempFilePath;
public class HandleUploadImpl extends CustomComponent
implements Upload.SucceededListener,
Upload.FailedListener,
Upload.ProgressListener,
Upload.Receiver { ........
public OutputStream receiveUpload(String filename, String MIMEType) {
logger.debug("File information {} {}", filename, MIMEType);
this.filename = filename;
FileOutputStream fos;
file = new File(tempFilePath + filename);
try {
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
logger.error("Error occurred while opening the file {}", e);
return null;
}
return fos;
}
Here is my code to store in mongo repository
private void saveBuildFile(Map<String, Object> buildFileInfo, String key) {
if (buildFileInfo.containsKey(key)) {
GridFS gridFS = new GridFS(mongoTemplate.getDb(), COLLECTION_NAME);
File file = (File) buildFileInfo.get(key);
buildFileInfo.remove(key);
try {
GridFSInputFile savedFile = gridFS.createFile(file);
savedFile.put(idK, buildFileInfo.get(key + "-id"));
savedFile.save();
} catch (Exception e) {
logger.error("Something went wrong when saving the file in the db {}", e);
}
}
}
Is there a way I can omit the use of temporary storage and set the output stream of upload component to mongo repository gridfs file.
This works for me:
package ch.domain.vaadin;
import ch.domain.vaadin.mongo.MongoItem;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.Upload.SucceededListener;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
/**
*
* #author eric
*/
class ImageUploader implements Receiver, SucceededListener {
private String filename;
private DB db;
private ByteArrayOutputStream fos;
private FieldGroup fieldGroup;
public void setFieldGroup(FieldGroup fieldGroup) {
this.fieldGroup = fieldGroup;
}
public ImageUploader(DB db)
{
this.db = db;
}
public OutputStream receiveUpload(String filename,
String mimeType) {
// Create upload stream
this.fos = new ByteArrayOutputStream();
this.filename = filename;
return this.fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(this.fos.toByteArray());
MongoItem parentId = (MongoItem) fieldGroup.getItemDataSource();
gfsFile.setMetaData(new BasicDBObject().append("parentId", parentId.getItemProperty("_id").getValue().toString()));
gfsFile.setFilename(this.filename);
gfsFile.save();
this.fos = null;
gfsFile = null;
// Show the uploaded file in the image viewer
// image.setVisible(true);
// image.setSource(new FileResource(file));
}
}

Categories

Resources