is there any better way to import database from .realm file to device? - realm

I have a pre-initialized realm. I am going to copy into where it should be on device using snip of code below.
//import from assets
public static RealmConfiguration importDatabase(Context context, String realm_file_name){
RealmConfiguration defaultRealm = new RealmConfiguration.Builder(context).build();
String dir = defaultRealm.getPath();
AssetManager assetManager = context.getAssets();
try {
InputStream is;
is = assetManager.open(realm_file_name);
File dest = new File(dir);
if (dest.exists())
dest.delete();
copy(is,dest);
}catch (IOException e){
Log.e(LOG_TAG,"import database error");
}
return defaultRealm;
}
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public static void copy(InputStream in, File dst) throws IOException {
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
So it will overwrite old realm file them write new realm file in same place.
Is it right ways to import database.
If not, how can I make it better ?

Related

JavaFX FileChooser dir and file name passed to FileOutputStream

I have a download file button which once clicked will download a file from a website and save it to a location and name selected via FileChooser but I'm struggling to pass the file location and name to the FileOutputStream.
Does anybody have any suggestions please?
Thank you,
Paul
Here is my code:
public void GetFile()
{
try
{
URL url = new URL("https://www.myURL.com/MyFile.xlsx");
FileChooser saveAs = new FileChooser();
saveAs.setInitialFileName("MyFile.xlsx");
saveAs.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx"));
saveAs.showSaveDialog(null);
System.out.println("File name and location set");
saveFile(url,saveAs.getInitialDirectory());
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void saveFile(URL url, File saveAs) throws IOException {
System.out.println("opening connection");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(saveAs);
System.out.println("Reading file...");
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
System.out.println("File downloaded");
}
Use the return value of FileChooser.showSaveDialog instead of the initialDirectory property value:
File outputFile = saveAs.showSaveDialog(null);
if (outputFile != null) {
System.out.println("File name and location set");
saveFile(url, outputFile);
}

Spring MVC - Display a PDF file into web browser

I am trying to display a PDF file in a web browser with spring MVC.
public void displayActiviteFiles (Activite activite, HttpServletResponse response) throws IOException {
File file = new File(activite.getLienUploadUn());
FileInputStream inputStream = new FileInputStream(file);
IOUtils.copy(inputStream, response.getOutputStream());
response.setHeader("Content-Disposition", "attachment; filename="+file.getName());
response.setContentType("application/pdf");
response.flushBuffer();
}
But I am getting weird characters instead of the pdf content.
Where am I wrong?
To answer my question and help some others in my case, this works :
File file = new File(activite.getLienUploadUn());
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
response.setHeader("Content-Disposition","inline; filename=\""+file.getName()+"\"");
response.setContentType("application/pdf");
ServletOutputStream outputStream = response.getOutputStream();
baos.writeTo(outputStream);
outputStream.flush();
You can display including this code.
#GetMapping(value = "/pdf")
public void showPdf(HttpServletResponse response) throws IOException {
response.setContentType("application/pdf");
InputStream inputStream = new FileInputStream(new File("/sample.pdf"));
int nRead;
while ((nRead = inputStream.read()) != -1) {
response.getWriter().write(nRead);
}
}
If it matters to anyone, then this is the 100% working solution in spring boot 1.5.11. Haven't run on manual Spring MVC projects. Maybe with some minor tweaks, can make it work.
#GetMapping(value = "/downloadFile")
public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws URISyntaxException {
File file = new File(getClass().getClassLoader().getResource("templates/more/si.pdf").toURI());
//viewing in web browser
response.setContentType("application/pdf");
//for downloading the file directly if viewing is not possible
response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
file = null;
//put the directory architecture according to your target directory
// generated during compilation in maven spring boot
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("templates/more/si.pdf");
return outputStream -> {
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
inputStream.close();
};
}

Pdf Download but not Opening decoding error

This is my jsp we are calling an java method
<%
PDFFileUploader.generatePDcFile(); //Calls the PDF method;
%>
This is my PDFFileUploader code
public class PDFFileUploader {
static final String UPLOAD_URL = "http://localhost:7080/pdf/GetPDFFile";
static final int BUFFER_SIZE = 4096;
public static void generatePDcFile() throws IOException
{
System.out.println("Inside generatePDC File");
// takes file path from first program's argument
String filePath = "H:/report1.pdf";
File uploadFile = new File("H:/report1.pdf");
System.out.println("File to upload: " + filePath);
// creates a HTTP connection
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
// sets file name as a HTTP header
httpConn.setRequestProperty("fileName", uploadFile.getName());
// opens output stream of the HTTP connection for writing data
OutputStream outputStream = httpConn.getOutputStream();
// Opens input stream of the file for reading data
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Start writing data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data was written.");
outputStream.close();
inputStream.close();
//Read pdc file
//FileOutputStream test = new FileOutputStream("test");
// always check HTTP response code from server
InputStream test = null;
File pdcFile = new File("H:/report123.pdf");
FileOutputStream outputStreamTest = new FileOutputStream(pdcFile);
//byte[] bufferTest = new byte[BUFFER_SIZE];
//int bytesReadTest = -1;
//final OutputStream ostream = new FileOutputStream("/tmp/data.pdc");
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// reads server's response
/* BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));*/
test = httpConn.getInputStream();
String message= httpConn.getResponseMessage();
System.out.println("Message is///"+message);
System.out.println("Header :: "+httpConn.getHeaderField(0));
final byte[] bufferTest = new byte[1024*14];
while (true) {
int len = test.read(bufferTest);
if (len <= 0) {
break;
}
outputStreamTest.write(bufferTest, 0, len);
}
outputStreamTest.close();
test.close();
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
System.out.println("Get File Name"+fileName);
/* Map<String, List<String>> map = httpConn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() +
" ,Value : " + entry.getValue());
}*/
// String response = reader.readLine();
//System.out.println("Server's response: " + response);
} else {
System.out.println("Server returned non-OK code: " + responseCode);
}
}
from here a servlet is called through the URL provided above the code for doPost method for the getPDFFile Servlet is
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// Gets file name for HTTP header
String fileName = request.getHeader("fileName");
File saveFile = new File(SAVE_DIR + fileName);
// prints out all header values
System.out.println("===== Begin headers =====");
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String headerName = names.nextElement();
System.out.println(headerName + " = " + request.getHeader(headerName));
}
System.out.println("===== End headers =====\n");
// opens input stream of the request for reading data
InputStream inputStream = request.getInputStream();
// opens an output stream for writing file
/*FileOutputStream outputStream = new FileOutputStream(saveFile);*/
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Receiving data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data received.");
outputStream.close();
inputStream.close();
System.out.println("File written to: " + saveFile.getAbsolutePath());
int processStatus = 0;
//temp file (used for conversion)
/* boolean success = (new File
(saveFile.getAbsolutePath())).delete();
System.out.println("File deleted :: "+success);
//delete pdc file too
boolean successtemp = (new File
(recentlyConvertedFile.getAbsolutePath())).delete();
System.out.println("File deleted :: "+successtemp);*/
response.setContentType("application/octet-stream" );
response.setHeader("Content-Disposition","inline;filename=\"" + saveFile.getName() + "\"");
response.setContentLength((int) saveFile.length());
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(saveFile);
//op.write(response.toString().getBytes(Charset.forName("utf-8")));
//op.flush();
try {
int byteRead = 0;
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
os.flush();
} catch (Exception excp) {
excp.printStackTrace();
} finally {
os.close();
fis.close();
}
// sends response to client
//response.getWriter().print("UPLOAD DONE");
}
The file is getting downloaded but not opening the generated pdf have the same size of the original and I have taken a text file and printed the content to another file it seems to read only first line of the text file taken as input
Your final loop returning a file from the servlet to the client looks like this:
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
You seem to have forgotten to use buffer in the fis.read() which should look like this:
while ((byteRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
Thus, you send back as many copies of the buffer contents as fis returns numbers != -1.
BTW: Your servlet puts the data it receives into the ByteArrayOutputStream outputStream and drops that, but it claims to have written them into the file it eventually attempts to return to the caller.

Writing mp3 file to response output stream

I am new to Servlets and following Headfirst. It has an example to download jar file with mime type "application/jar". I changed it to "audio/mpeg3" to download an mp3 file. I get the player on the browser but it doesn't play. Here is the code:
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("audio/mpeg3");
ServletContext ctx=this.getServletContext();
InputStream is=ctx.getResourceAsStream("/RaOne.mp3");
int read=0;
byte[] bytes=new byte[1024];
OutputStream os=resp.getOutputStream();
while((read=is.read(bytes))!=-1)
{
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
Can someone please help to figure out the problem?
you can try out something like this
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
stream = response.getOutputStream();
File mp3 = new File("/myCollectionOfSongs" + "/" + fileName);
//set response headers
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentLength((int) mp3.length());
FileInputStream input = new FileInputStream(mp3);
buf = new BufferedInputStream(input);
int readBytes = 0;
//read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
if (stream != null)
stream.close();
if (buf != null)
buf.close();
}

wait() in asp.net (showing uploaded image)

I want to force my program to wait some moments after doing something, and then do somwthing else, in asp.net and silverlight.
(In Detail, I want to upload an image by silverlight program, and then show it in my page by an Image control. But when I upload images which their size is about 6KB or upper, the image doesn't show, however it has been uplaoded successfully. I think that waiting some moments may solve the problem)
May anyone guide me?
thank you
I use the code in this page
This is the code in MyPage.Xaml:
private void UploadBtn_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = UPLOAD_DIALOG_FILTER;
if ((bool)dlg.ShowDialog())
{
progressBar.Visibility = Visibility.Visible;
progressBar.Value = 0;
_fileName = dlg.File.Name;
UploadFile(_fileName, dlg.File.OpenRead());
}
else
{
//user clicked cancel
}
}
private void UploadFile(string fileName, Stream data)
{
// Just kept here
progressBar.Maximum = data.Length;
UriBuilder ub = new UriBuilder("http://mysite.com/receiver.ashx");
ub.Query = string.Format("fileName={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
try
{
c.OpenWriteAsync(ub.Uri);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[input.Length];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, buffer.Length);
}
progressBar.Value += input.Length;
if (progressBar.Value >= progressBar.Maximum)
{
progressBar.Visibility = System.Windows.Visibility.Collapsed;
loadImage();
}
}
private void loadImage()
{
Uri ur = new Uri("http://mysite.com/upload/" + _fileName);
img1.Source = new BitmapImage(ur);
}
And this is receiver.ashx:
public void ProcessRequest(HttpContext context)
{
string filename = context.Request.QueryString["filename"].ToString(); using (FileStream fs = File.Create(context.Server.MapPath("~/upload/" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}
private void SaveFile(Stream stream, FileStream fs)
{
byte[] buffer = new byte[stream.Length];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}

Resources