How to download a file instead of opening it - html

Tried every solution from >https://stackoverflow.com/questions/10069050/download-file-inside-webview
but every time it just opens the text file instead of downloading it. The text file is just temporary; when I try it with an apk it just crashes.
Incae you were wondering here is the HTML text
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="head">
<h1>FisheStore</h1>
</div>
<a href="drawable/text.txt" download>Install</a>
</body>
</html>
And here is whats in MainActivity.Java
package com.example.project;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("file:///android_asset/index.html");
webView.setDownloadListener(new DownloadListener()
{
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition,
mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
}});
}
}

Related

Postman output "status":404,"error":"Not Found","path":"/api/employees"

the spring boot REST app with MySQL
I am trying to add record to DB and expect the record added and postman got it as output instead of the output "status":404,"error":"Not Found","path":"/api/employees" following is the classes
package com.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.service.EmployeeService;
import com.model.Employee;
#RestController
#RequestMapping("/api")
public class EmployeeController {
private EmployeeService employeeservice;
public EmployeeController(EmployeeService employeeservice) {
super();
this.employeeservice = employeeservice;
}
//build create Employee REST API
#PostMapping("/employees")
public ResponseEntity<Employee> saveEmployee(#RequestBody Employee employee)
{
return new ResponseEntity<Employee>(employeeservice.saveEmployee(employee), HttpStatus.CREATED);
}
}
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories(
basePackages = {"com.model"})
#SpringBootApplication(scanBasePackages = {"service.impl"})
public class RestapimysqlApplication {
public static void main(String[] args) {
SpringApplication.run(RestapimysqlApplication.class, args);
}
}
It doesn't look like you're scanning the package that contains your REST controller (i.e. com.controller), seems like you're only scanning the service.impl package on your RestapimysqlApplication class.
You should probably add the com.controller to the list of packages being scanned by Spring here:
#EnableJpaRepositories(basePackages = {"com.repository"})
#SpringBootApplication(scanBasePackages = {"service.impl", "com"})
#EntityScan({"com.model"})
public class RestapimysqlApplication {
...
}

Error: javax.net.ssl.SSLHandshakeException when accesing to HTTPS site from Lambda

I'm developing a custom skill to Alexa (Amazon), and I coded the skill in lambda AWS service in JAVA 8. I'm trying to get a simple response from my ask2decide API and it's not working.
Basically I'm executing the following code:
String questiont = "casco"
String queryString =
String.format("https://www.ask2decide.com/api/prod/search.php?s=%s", questiont);
InputStreamReader inputStream = null;
BufferedReader bufferedReader = null;
StringBuilder builder = new StringBuilder();
try {
String line;
URL url = new URL(queryString);
inputStream = new InputStreamReader(url.openStream(), Charset.forName("US-ASCII"));
bufferedReader = new BufferedReader(inputStream);
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
System.out.println(line);
}
} catch (IOException e) {
// reset builder to a blank string
System.out.print("ERROR:");
System.out.println(e);
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(bufferedReader);
}
The result of executing it is the following
error:"javax.net.ssl.SSLHandshakeException: Remote host closed
connection during handshake"
Note: I get a JSON standard array if I execute the URL in Chrome without any error.
Note2: The imports:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.*;
import javax.net.ssl.*;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazon.speech.slu.Intent;
import com.amazon.speech.slu.Slot;
import com.amazon.speech.speechlet.IntentRequest;
import com.amazon.speech.speechlet.LaunchRequest;
import com.amazon.speech.speechlet.Session;
import com.amazon.speech.speechlet.SessionEndedRequest;
import com.amazon.speech.speechlet.SessionStartedRequest;
import com.amazon.speech.speechlet.SpeechletV2;
import com.amazon.speech.speechlet.SpeechletResponse;
import com.amazon.speech.json.SpeechletRequestEnvelope;
import com.amazon.speech.ui.OutputSpeech;
import com.amazon.speech.ui.PlainTextOutputSpeech;
import com.amazon.speech.ui.SsmlOutputSpeech;
import com.amazon.speech.ui.Reprompt;
import com.amazon.speech.ui.SimpleCard;
import com.amazonaws.util.json.JSONArray;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.amazonaws.util.json.JSONTokener;

App crashes everytime run with error "Unfortunately MyApplication1 has stopped"

I am using Volley library for fetching the json data. I have also modified the Manifest adding the necessary Internet permission . But when I run the app it crashes.
Main activity.java
package com.example.sans.myapplication1;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView listView;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
listView=(ListView)findViewById(R.id.list);
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, "http://api.themoviedb.org/3/movie/popular?api_key=fa468af9e769ba5fbc027e9e933130ed",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Movie> movieList= new ArrayList<Movie>();
try{
JSONArray jsonArray=response.getJSONArray("results");
for (int i=0;i< jsonArray.length();i++){
JSONObject jsonObject= jsonArray.getJSONObject(i);
String title= jsonObject.getString("title");
movieList.add(new Movie(title));
MovieAdapter adapter= new MovieAdapter(getApplicationContext(),movieList);
listView.setAdapter(adapter);
}
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error getting data", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
$ MovieAdapter.java
package com.example.sans.myapplication1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by sans on 13/7/16.
*/
public class MovieAdapter extends ArrayAdapter<Movie> {
public MovieAdapter(Context context, List<Movie> objects) {
super(context,0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Movie movie=getItem(position);
if(convertView==null){
convertView= LayoutInflater.from(getContext()).inflate(R.layout.list_row, parent);
}
TextView title=(TextView)convertView.findViewById(R.id.title);
title.setText(movie.getTitle());
return convertView;
}
}
$ Movie.java
package com.example.sans.myapplication1;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by sans on 13/7/16.
*/
public class Movie {
private String title;
public Movie(String title){
this.title=title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
$ list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/listPreferredItemHeight"
android:id="#+id/title"/>
</LinearLayout>
$ content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.sans.myapplication1.MainActivity"
tools:showIn="#layout/activity_main">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list" />
</RelativeLayout>
Log error
FATAL EXCEPTION: main
Process: com.example.sans.myapplication1, PID: 4252
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.sans.myapplication1.MovieAdapter.getView(MovieAdapter.java:29)
at android.widget.AbsListView.obtainView(AbsListView.java:2346)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1280)
at android.widget.ListView.onMeasure(ListView.java:1188)
at android.view.View.measure(View.java:18788)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:735)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
at android.view.View.measure(View.java:18788)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-13 17:37:39.746 1532-1903/? W/ActivityManager: Force finishing activity com.example.sans.myapplication1/.MainActivity
In MovieAdapter.java class change convertView!=null to convertView==null
& in list_row.xml file
instead of android:minHeight="?attr/listPreferredItemHeight"
change it to android:minHeight="?android:attr/listPreferredItemHeight"

unable to upload file to mysql using struts1

I am trying to upload a file into mysql database using struts1.But unable to doso,I am getting the error:FileNotFoundException.Here is my code...
1.JSP Page:
<%# taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<body>
<html:form action="upload" enctype="multipart/form-data">
Select a File :<html:file property="file"/>
<html:submit/>
</html:form>
</body>
</html:html>
2.My Action Form
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm{
private FormFile file;
public FormFile getFile(){
return this.file;
}
public void setFile(FormFile file){
this.file=file;
}
}
3.Action Class
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.sql.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
public class UploadAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception{
UploadForm file=(UploadForm)form;
System.out.print("Executed");
FormFile formFile=file.getFile();
System.out.print("Executed1");
String fileName=formFile.getFileName();
System.out.print(fileName);
File file1=new File(formFile.getFileName());
System.out.print(">>>>");
FileInputStream fin=new FileInputStream(file1);
System.out.print("*****");
Integer fileSize=formFile.getFileSize();
int insert=0;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded.");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/test","root","");
System.out.println("Connection Opened.");
PreparedStatement pst=con.prepareStatement("insert into upload values(?)");
pst.setBinaryStream(1,fin,fileSize);
insert=pst.executeUpdate();
System.out.print("File Uploaded.");
}
catch(Exception e){System.out.println(e);}
if(insert!=0){
return mapping.findForward("success");
}
else{
return mapping.findForward("error");
}
}
}
I am getting error at this line in my Action Class:FileInputStream fin=new FileInputStream(file1);
Please help me to resolve this problem.

Converting a Jpeg into an uncompressed tiff image

I found this code on StackOverflow
import java.io.File;
import java.io.FileOutputStream;
import java.awt.image.RenderedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;
public class Main {
public static void main(String args[]) {
File file = new File("input.tif");
try {
SeekableStream s = new FileSeekableStream(file);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
RenderedImage op = new NullOpImage(dec.decodeAsRenderedImage(0),
null,
OpImage.OP_IO_BOUND,
null);
FileOutputStream fos = new FileOutputStream("output.jpg");
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(fos);
jpeg.encode(op.getData());
fos.close();
}
catch (java.io.IOException ioe) {
System.out.println(ioe);
}
}
}
I have been trying to reverse this process - convert jpg to uncompressed tiff but but I cant seem to get it to work.
Any ideas?