uploading imageI am trying to make a program using http to upload a picture directly to the server from glass but i am not able to do it the code I have can only upload one picture that is already there but not the picture i have taken in the glass can someone please verify the code and tell me how to change it in such a way that i can upload the pictures i have taken directly
logcat:
06-10 15:07:43.813: D/GCM(718): GcmService start Intent { act=com.google.android.checkin.CHECKIN_COMPLETE flg=0x10 cmp=com.google.android.gms/.gcm.GcmService (has extras) } com.google.android.checkin.CHECKIN_COMPLETE
06-10 15:07:43.844: I/GlassUserEventService[42357a28](1071): Performance stats: [object: com.google.common.logging.GlassExtensionsNano$GlassUserEventPerformanceStats { batteryChargeWhenFullUah_: 604000 totalKernelMs_: 8848030 totalBytesSent_: 1218965 bitField0_: 16383 boardTemperatureMilliCentigrade_: 40970 frequencyScalingGovernor_: 0 availableMemoryKb_: 989140 isLowMemory_: false networkType_: 1 qpassedFractional_: 46921 qpassedInteger_: 17182 reportedSoc_: 99 batteryTemperatureMilliCentigrade_: 26800 batteryStateOfChargeUah_: 595000 totalMemoryKb_: 1475504 unknownFieldData: null cachedSize: -1}]
06-10 15:07:53.836: I/NativeAppVoiceMenuHelper(865): Installed packages changed; invalidating trigger cache
06-10 15:07:53.836: V/FormattingLoggers(865): TimingData [count=780, sinceCreation=14174171ms, spentLogging=272ms].
06-10 15:07:53.836: W/Searchables(498): No global search activity found
06-10 15:07:53.852: I/InputReader(498): Reconfiguring input devices. changes=0x00000010
06-10 15:07:53.860: V/GmsNetworkLocationProvi(1181): DISABLE
06-10 15:07:53.860: D/PackageBroadcastService(816): Received broadcast action=android.intent.action.PACKAGE_CHANGED and uri=com.google.android.gms
06-10 15:07:53.906: E/GCoreFlp(1181): Bound FusedProviderService with LocationManager
06-10 15:07:53.906: V/GmsNetworkLocationProvi(1181): ENABLE
06-10 15:07:53.914: V/GmsNetworkLocationProvi(1181): onSetRequest: ProviderRequestUnbundled, reportLocation is true and interval is 86400000
06-10 15:07:53.914: V/GmsNetworkLocationProvi(1181): SET-REQUEST
06-10 15:07:53.914: V/GmsNetworkLocationProvi(1181): in Handler: ProviderRequestUnbundled, reportLocation is true and interval is 86400000
06-10 15:07:56.149: W/BluetoothAdapter(773): getBluetoothService() called with no BluetoothManagerCallback
06-10 15:07:56.149: D/BluetoothSocket(773): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[97]}
package com.morkout.nbsocial;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class HTTPRequestActivity extends Activity {
public final static String TAG = "HTTPRequestActivity";
TextView mTvInfo;
String mWhat;
HttpURLConnection mUrlConnection;
String mResult;
protected void onResume () {
super.onResume();
}
protected void onPause () {
super.onPause();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTvInfo = (TextView) findViewById(R.id.info);
Intent intent = getIntent();
mWhat = intent.getStringExtra("WHAT");
Log.i(TAG, "WHAT="+mWhat);
mTvInfo.setText("Making HTTP "+ mWhat + " request...");
new HTTPRequest().execute();
}
// Async task class to make HTTP Get, Post and upload
private class HTTPRequest extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
if (mWhat.equalsIgnoreCase("GET")) {
Log.w(TAG, "GET");
// get json via YouTube API
URL url = new URL("http://Google.com");
mUrlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(mUrlConnection.getInputStream());
int ch;
StringBuffer b = new StringBuffer();
while ((ch = in.read()) != -1) {
b.append((char) ch);
}
mResult = new String(b);
in.close();
}
else if (mWhat.equalsIgnoreCase("POST")) {
URL url = new URL("http://morkout.com/glass/posttest.php");
mUrlConnection = (HttpURLConnection) url.openConnection();
mUrlConnection.setRequestMethod("POST");
String urlParameters = "email=kandyala.komal-chowdary#stud.th-deg.de&name=komal chowdary&pwd=1234567&vcode=2014";
OutputStreamWriter writer = new OutputStreamWriter(mUrlConnection.getOutputStream());
writer.write(urlParameters);
writer.flush();
InputStream in = new BufferedInputStream(mUrlConnection.getInputStream());
int ch;
StringBuffer b = new StringBuffer();
while ((ch = in.read()) != -1) {
b.append((char) ch);
}
mResult = new String(b);
in.close();
writer.close();
}
else if (mWhat.equalsIgnoreCase("UPLOAD")) {
int serverResponseCode = 0;
File sourceFile = new File(copyAsset("marchmadness.png"));
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :" +sourceFile.getAbsolutePath());
}
else
{
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("http://www.morkout.com/glass/upload.php");
mUrlConnection = (HttpURLConnection) url.openConnection();
mUrlConnection.setRequestMethod("POST");
mUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
mUrlConnection.setRequestProperty("Filedata", sourceFile.getName());
dos = new DataOutputStream(mUrlConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=Filedata;filename="+ sourceFile.getName() + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = mUrlConnection.getResponseCode();
String serverResponseMessage = mUrlConnection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200) {
Log.v(TAG, "File Upload Completed.");
InputStream is = mUrlConnection.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
final String uploadedFilename = b.toString();
Log.v(TAG, "uploaded file at http://www.morkout.com/glass/uploads/" + uploadedFilename);
mResult = "uploaded file at http://www.morkout.com/glass/uploads/" + uploadedFilename;
is.close();
}
fileInputStream.close();
dos.close();
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
finally {
if (mUrlConnection != null)
mUrlConnection.disconnect();
}
return null;
}
String copyAsset(String filename) {
final String PATH = Environment.getExternalStorageDirectory().toString() + "/nbsocial/";
File dir = new File(PATH);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + PATH + " on sdcard failed");
return null;
} else {
Log.v(TAG, "Created directory " + PATH + " on sdcard");
}
}
if (!(new File( PATH + filename).exists())) {
Log.v(TAG, "copying file " + filename);
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open(filename);
OutputStream out = new FileOutputStream(PATH + filename);
// 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();
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + filename + e.toString());
return null;
}
}
return PATH + filename;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.w(TAG, "onPostExecute");
mTvInfo.setText(mResult);
}
}
}
Related
control.java
public class control {
public static void main(String[] args) {
boolean success = true;
String timestamp = "1659072666";
String base = "USD";
String date = "2022-07-29";
double GBP = 0.82011;
double JPY = 133.000499;
double EUR = 0.979105;
excJSON vwJson = new excJSON();
exc vw = vwJson.getexc(success, timestamp, base, date, GBP, JPY, EUR);
excDAO vwDao = new excDAO();
vwDao.intertexc(1, vw);
}
}
exc.java
public class exc {
String base;
String date;
String timestamp;
public String getbase() {
return base;
}
public void setbase(String base) {
this.base = base;
}
public String getdate() {
return date;
}
public void setdate(String date) {
this.date = date;
}
public String gettimestamp() {
return timestamp;
}
public void settimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
excDAO.java
import java.sql.Statement;
import java.sql.Connection;
//import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.util.Enumeration;
public class excDAO {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false";
static final String USERNAME = "root"; // DB ID
static final String PASSWORD = "************"; // DB Password
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public void intertVillageWeather(int id, exc v) {
String query = "INSERT INTO exchangerate"
+ " VALUE(" + id +",'"+v.gettimestamp() + "','" + v.getbase() + "','" + v.getdate() + "');";
System.out.print("Your Database in : ");
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USERNAME,PASSWORD);
if (conn != null){System.out.println("good");}
else{System.out.println("bad");}
System.out.println(query);
stmt = conn.createStatement();
stmt.executeUpdate(query);
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exection");
} catch (SQLException e) {
System.out.println("SQL Exception : " + e.getMessage());
}
}
public void intertexc(int i, exc vw) {
}
}
excJSON.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
final static String apiKey = "tUxsDwwjT72GgMLoJRprXlqc34wmOzX4";
public exc getexc(boolean success, String timestamp, String base, String date, double GBP, double JPY, double EUR) {
String urlStr = "https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD"
+ "&apiKey=" + apiKey + "&success=" + success + "×tamp=" + timestamp
+ "&base="+ base + "&date=" + date + "&GBP=" + GBP + "&JPY=" + JPY + "&EUR=" + EUR + "&_type=json";
exc vl = new exc(); // 결과 데이터를 저장할 객체를 만듭니다.
try {
URL url = new URL(urlStr);
BufferedReader bf = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
String result="";
while((line=bf.readLine())!=null){
result=result.concat(line);
}
//System.out.println(result);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObj = (JSONObject) jsonParser.parse(result);
JSONObject parse_response = (JSONObject) jsonObj.get("response");
JSONObject obj;
String category;
vl.timestamp = timestamp;
vl.base = base;
vl.date = date;
for(int i = 0; i < parse_response.size(); i++) {
obj = (JSONObject) parse_response.get(i);
category = (String)obj.get("category");
switch(category) {
case "timestamp":
vl.timestamp = (obj.get("fcstValue")).toString();
break;
case "base":
vl.base = (obj.get("fcstValue")).toString();
break;
case "date":
vl.date = (obj.get("fcstValue")).toString();
break;
}
}
} catch (MalformedURLException e) {
System.out.println("MalformedURLException : " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException : " + e.getMessage());
} catch (ParseException e) {
System.out.println("ParseException : " + e.getMessage());
}
return vl;
}
}
*Help me please. I think error in excJSON.java. I want make exchangerate program.
I want fix error.
error code : IOException : Server returned HTTP response code: 403 for URL: https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD&apiKey=tUxsDwwjT72GgMLoJRprXlqc34wmOzX4&success=true×tamp=1659072666&base=USD&date=2022-07-29&GBP=0.82011&JPY=133.000499&EUR=0.979105&_type=json
I assess "https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD&apiKey=tUxsDwwjT72GgMLoJRprXlqc34wmOzX4&success=true×tamp=1659072666&base=USD&date=2022-07-29&GBP=0.82011&JPY=133.000499&EUR=0.979105&_type=json"
but http say {"message":"No API key found in request"}
but i surely receive apikey and api.*
For encrypting files I use PKCS # 7 and the Javascript bundle forge.pki.
var forge = require('node-forge');
var contentBuffer = forge.util.createBuffer( forge.util.decode64( "fasdasd asdasdasda" ));
var cert = forge.pki.certificateFromPem(certPem);
var p7 = forge.pkcs7.createEnvelopedData();
p7.addRecipient(cert);
p7.content = contentBuffer;
console.log("Encrypt...");
p7.encrypt();
var asn1Cert = p7.toAsn1();
var derBuffer = forge.asn1.toDer(asn1Cert);
var p7mContent = derBuffer.toHex();
console.log(p7mContent);
I copy the hex value into my Java class as a string constant. Java saves then converts this into a .p7m file and stores it locally for me.
public void writeDocumentContent(String filename) throws Exception {
byte[] encryptedMessage = getP7MBytes(hex);
InputStream inputStream = new ByteArrayInputStream(encryptedMessage);
handleTransfer(inputStream, TransferKanal.HTML5);
}
private static byte[] getP7MBytes(String p7m) {
int len = p7m.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(p7m.charAt(i), 16) << 4) + Character.digit(p7m.charAt(i + 1), 16));
}
return data;
}
private void handleTransfer(InputStream inputStream, TransferKanal kanal) throws Exception {
String path = "C:TEMP/padline";
createDirectory(path);
String filename = "example." + kanal.getFileExtension();
File targetFile = new File(path, filename);
provideTransferData(inputStream, targetFile);
}
private void provideTransferData(InputStream inputStream, File targetFile) throws Exception {
try (InputStream bInputStream = new BufferedInputStream(inputStream, 20 * 8192)) {
provide(bInputStream, targetFile);
} catch (IOException e) {
throw new Exception("error while reading/writing transfer data", e);
}
}
private boolean createDirectory(String directory) {
File file = new File(directory);
if (!file.exists()) {
file.mkdirs();
return true;
}
return false;
}
private void provide(InputStream is, File finalFile) throws Exception {
try {
File destFile = new File(finalFile.getAbsolutePath());
FileOutputStream buffer = null;
try {
buffer = new FileOutputStream(destFile);
int nRead;
byte[] buf = new byte[2 * 16384];
while ((nRead = is.read(buf, 0, buf.length)) != -1) {
buffer.write(buf, 0, nRead);
}
} catch (Exception e) {
throw new Exception("provision location corrupted", e);
} finally {
if (buffer != null) {
buffer.close();
}
}
} catch (IOException e) {
throw new Exception("error copying file", e);
}
}
Before, I create a bundle of the certificate and the private key via openSSL with following command:
openssl pkcs12 -export -inkey private.key -in public.cert -out certificate.pfx
and imported it into Kleopatra as a .pfx file. Then I have the generated (encrypted) p7m file to decrypt in Cleopatra and pushed the following error message:
Decryption failed: invalid data
I have a website that is navigated from within a webview. One of the pages generates a ZIP file that is downloaded via a BLOB URL. I discovered that this is not supported by webview, so I have tried implementing this solution:
Download Blob file from Website inside Android WebViewClient
However, it is not working for me. Breakpoints in convertBase64StringToZipAndStoreIt are never hit.
UPDATE: I've found that I'm getting an HTTP 404. I've tried using blobUrl and blobUrl.substring(5) and the result is the same either way. The BLOBs are downloading fine in Chrome, though.
Webview setup:
private void launchWV() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
setContentView(R.layout.activity_self_service_launcher);
mWebView = (WebView) findViewById(R.id.activity_launcher_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setUserAgentString("Mozilla/5.0 (Android; X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.34 Safari/534.24" + getClientVersionInfo());
webSettings.setDomStorageEnabled(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.setWebViewClient(new MyWebViewClient(this));
mWebView.setWebChromeClient(new MyWebChromeClient(this));
mWebView.addJavascriptInterface(new JavaScriptInterface(getApplicationContext()), "Android");
}
Function called from shouldOverrideUrlLoading() (only the else condition for BLOB URLs is of concern):
private boolean handleRequest(WebView view, String url) {
String filename;
if (!checkInternetConnection()) {
ShowNetworkUnavailableDialog(false);
return true;
}
else {
if (url.contains("view/mys") || url.contains("view/myy") || url.contains("blob") || url.contains("view/mye")) {
if (url.contains("view/mys")) {
filename = getResources().getString(R.string.mys_file_name).concat(".pdf");
} else if (url.contains("view/myy")) {
filename = getResources().getString(R.string.form_file_name).concat(".pdf");
} else if (url.contains("blob")) {
filename = getResources().getString(R.string.mys_file_name).concat(".zip");
} else {
filename = getResources().getString(R.string.mye_file_name).concat(".pdf");
}
if (!url.contains("blob")) {
String cookies = CookieManager.getInstance().getCookie(url);
DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(url));
downloadRequest.addRequestHeader("cookie", cookies);
downloadRequest.allowScanningByMediaScanner();
downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
try {
dm.enqueue(downloadRequest);
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.connection_unavailable), Toast.LENGTH_LONG).show();
return false;
}
} else {
String blobURL = JavaScriptInterface.getBase64StringFromBlobUrl(url);
mWebView.loadUrl(blobURL);
}
Toast.makeText(getApplicationContext(), getResources().getString(R.string.download_message), Toast.LENGTH_LONG).show();
return true;
} else if (!url.contains(getMetadata(getApplicationContext(), HOSTNAME))) {
//Navigate to external site outside of webview e.g. Help site
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
} else if(url.contains(getResources().getString(R.string.about_url))) {
mWebView.loadUrl(url);
return false;
} else {
if (savedInstanceState == null) {
mWebView.loadUrl(url);
}
return false;
}
}
}
JavaScriptInterface class:
public class JavaScriptInterface {
private Context context;
private NotificationManager nm;
public JavaScriptInterface(Context context) {
this.context = context;
}
#JavascriptInterface
public void getBase64FromBlobData(String base64Data) throws IOException {
convertBase64StringToZipAndStoreIt(base64Data);
}
public static String getBase64StringFromBlobUrl(String blobUrl){
if(blobUrl.startsWith("blob")){
return "javascript: var xhr = new XMLHttpRequest();" +
"xhr.open('GET', '" + blobUrl.substring(5) + "', true);" +
"xhr.setRequestHeader('Content-type','application/zip');" +
"xhr.responseType = 'blob';" +
"xhr.onload = function(e) {" +
" if (this.status == 200) {" +
" var blobZip = this.response;" +
" var reader = new FileReader();" +
" reader.readAsDataURL(blobZip);" +
" reader.onloadend = function() {" +
" base64data = reader.result;" +
" Android.getBase64FromBlobData(base64data);" +
" }" +
" }" +
"};" +
"xhr.send();";
}
return "javascript: console.log('It is not a Blob URL');";
}
private void convertBase64StringToZipAndStoreIt(String base64Zip) throws IOException {
final int notificationId = 1;
String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
final File dwldsPath = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + "/YourFileName_" + currentDateTime + "_.zip");
byte[] zipAsBytes = Base64.decode(base64Zip.replaceFirst("^data:application/zip;base64,", ""), 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(zipAsBytes);
os.flush();
if(dwldsPath.exists()) {
NotificationCompat.Builder b = new NotificationCompat.Builder(context, "MY_DL")
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("MY TITLE")
.setContentText("MY TEXT CONTENT");
nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
if(nm != null) {
nm.notify(notificationId, b.build());
Handler h = new Handler();
long delayInMilliseconds = 5000;
h.postDelayed(new Runnable() {
public void run() {
nm.cancel(notificationId);
}
}, delayInMilliseconds);
}
}
}
}
One thing I know I am unclear on is what URL should be going into the call to xhr.open in the class.
I also tried using onDownloadStart with the same result.
Any insight is greatly appreciated!
I have an image stored in a database table, with primary key for a particular number. That image below the database to a folder of the java project by means of a servlet.
So far, so good.
My problem is that I need to download that image to the user and I can not do it.
My steps are as follows:
JSP:
$scope.downloadFile = function(){
var tkAct = $scope.ticketActual.tknum;
var param = {
nroTk: tkAct
};
var res = $http.post($scope.testHost +"/downloadAttachment",JSON.stringify(param));
});
res.error(function(data, status, headers, config) {
alert("failure message: " + JSON.stringify({data: data}));
});
}
SERVLET:
#WebServlet("/downloadAttachment")
public class downloadAttachment extends HttpServlet {
// size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;
private final int BYTES_DOWNLOAD=1024;
public static final String FILE_SEPARATOR = System.getProperty("file.separator");
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession sess = request.getSession();
Controller ctrl = Controller.get();
ServletContext sc = getServletContext();
//int nroTicket=-1;
//nroTicket = 104;
System.out.println(request.getParameter("NroTk"));
System.out.println(request.getAttribute("NroTk"));
JSONObject joParam = getParametrosJo(request);
Long lNroTk = (Long) joParam.get("nroTk");
int nroTicket = lNroTk.intValue();
Vector<String> vNamesFile = ctrl.getFile(nroTicket,sc.getRealPath("/downloads"));
if(vNamesFile.size()==1){
String archivo = vNamesFile.get(0);
File downloadFile = new File(archivo);
String nombreFile = getNombreFileEnvio(nroTicket,downloadFile.getName());
// if you want to use a relative path to context root:
String relativePath = getServletContext().getRealPath("/downloads/");
System.out.println("relativePath = " + relativePath);
// obtains ServletContext
ServletContext context = getServletContext();
String mimeType = context.getMimeType(nombreFile);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setHeader("Content-Disposition","attachment;filename="+nombreFile);
System.out.println("Obteniendo el Stream...");
System.out.println("nombre del file es: "+nombreFile);
InputStream is = sc.getResourceAsStream("/downloads/" + downloadFile.getName());
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream(relativePath+downloadFile.getName());
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}else{
byte[] zip = zipFiles(getServletContext().getRealPath("/downloads/"),vNamesFile, 95);
ServletOutputStream sos = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=AdjuntosTicket95" + ".ZIP");
sos.write(zip);
sos.flush();
}
}
private JSONObject getParametrosJo(HttpServletRequest request) throws IOException{
StringBuilder buffer = new StringBuilder();
BufferedReader joParam = request.getReader();
String texto="";
String str = null;
while ((str = joParam.readLine()) != null) {
buffer.append(str);
//texto+=str;
}
texto = buffer.toString();
System.out.println(texto);
if(!texto.equalsIgnoreCase("")){
JSONObject obj = JSONObject.parse(texto);
return obj;
}else{
return null;
}
}
private byte[] zipFiles(String path, Vector<String> vNamesFile, int nroTk) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
byte bytes[] = new byte[2048];
for (String fileName : vNamesFile) {
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(getNombreFileEnvio(nroTk,fileName)));
int bytesRead;
while ((bytesRead = bis.read(bytes)) != -1) {
zos.write(bytes, 0, bytesRead);
}
zos.closeEntry();
bis.close();
fis.close();
}
zos.flush();
baos.flush();
zos.close();
baos.close();
return baos.toByteArray();
}
private String getNombreFileEnvio(int nroTk, String nombreEnFS){
String[] aNombreFile = nombreEnFS.split("%");
String nombreFile = aNombreFile[1];
return nombreFile;
}
}
How do I recover that image from the database to the folder / downloads / and deliver it to the user?
Thank you
I have a program where a text file is read in and then each word in the file is outputted, followed by the # of times it is repeated throughout the file.
Use the following code.
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:\\Users\\Desktop\\formate.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
//Close the input stream
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try this code:
public static void main(String[] args) throws Throwable
{
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
Scanner scanner = new Scanner(inputFile);
HashMap<String, Integer> count = new HashMap<String, Integer>();
while (scanner.hasNext())
{
String word = scanner.next();
if (count.containsKey(word))
{
count.put(word, count.get(word) + 1);
}
else
{
count.put(word, 1);
}
}
scanner.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Entry<String, Integer> entry : count.entrySet())
{
writer.write("#" + entry.getKey() + " " + entry.getValue()+"\r\n");
}
writer.close();
}
This also, it is a lot simpler if You can't use HashMap or BufferedReader:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;
public class WordCounter
{
public static void main(String[] args) throws Throwable
{
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
Scanner scanner = new Scanner(inputFile);
LinkedList<Word> words = new LinkedList<Word>();
while (scanner.hasNext())
{
String word = scanner.next();
addWord(words, word);
}
scanner.close();
WriteToFile(outputFile, words);
}
private static void WriteToFile(File outputFile, LinkedList<Word> words) throws IOException
{
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Word word : words)
{
writer.write("#" + word.getWord() + " " + word.getCount() + "\r\n");
}
writer.close();
}
private static void addWord(LinkedList<Word> words, String word)
{
for (Word aWord : words)
{
if (aWord.getWord().equals(word))
{
aWord.incrementCount();
return;
}
}
words.add(new Word(word, 1));
}
}
class Word
{
private String word;
private int count;
public Word(String word, int count)
{
this.word = word;
this.count = count;
}
public String getWord()
{
return word;
}
public void setWord(String word)
{
this.word = word;
}
public int getCount()
{
return count;
}
public void setCount(int count)
{
this.count = count;
}
public void incrementCount()
{
count++;
}
#Override
public String toString()
{
return "Word: " + word + " Count: " + count;
}
}