I am getting a parse file back from parse.com which is a string message and displaying it in textView.
ParseFile file = message.getParseFile(ParseConstants.KEY_FILE);
String filePath = file.getDataInBackground().toString();
if (messageType.equals("string")){
Intent intent = new Intent(getActivity(), StringActivity.class);
intent.putExtra("file", filePath);
string activity class i try to display file in textView:
protected TextView mDisplay;
mDisplay = (TextView)findViewById(R.id.stringDisplay);
String mess = getIntent().getStringExtra("file");
byte[] by = mess.getBytes();
String filePath =new String(by);
mDisplay.setText(filePath);
whats displayed in the textView is this bolts.Task#12af9f90 random numbers.
how can i get the string to display?
This will get you the content of the file:
String fileContent = "";
try {
fileContent = new String(file.getData());
} catch (ParseException e) {
e.printStackTrace();
}
Related
I am capturing a live image using JavaScript and storing that image in the database in encrypted form. Below is the code for storing image in database.
Session["imageName"] = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
Session["imagePath"] = string.Format("{0}.png", Session["imageName"].ToString());
Session["CapturedImage"] = ResolveUrl(Session["imagePath"].ToString());
private static byte[] ConvertHexToBytes(string hex)
{
byte[] bytes = new byte[hex.Length * sizeof(char)];
System.Buffer.BlockCopy(hex.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static bool SaveCapturedImage(string data)
{
string url = HttpContext.Current.Session["CapturedImage"].ToString();
HttpContext.Current.Session["CapturedImage"] = null;
return true;
}
protected void btnUpload_Click1 (object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader(Request.InputStream))
{
Session["hexString"] = Server.UrlEncode(reader.ReadToEnd());
string filename = Session["imageName"].ToString();
string contentType = Session["imagePath"].ToString();
using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
{
byte[] bytes = ConvertHexToBytes(Session["hexString"].ToString());
string constr = ConfigurationManager.ConnectionStrings["Con2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles values (#UId,#Name, #RelativeName, #ImageName, #ContentType, #Data, #uname)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UId", txtId.Text);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#RelativeName", txtRName.Text);
cmd.Parameters.AddWithValue("#ImageName", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
cmd.Parameters.AddWithValue("#uname", Session["uname"].ToString());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.clear();
}
}
}
}
}
How can I decrypted the image on page load at next page. I have tried many things but am not able to do it.
Thanks.
I am trying to use httpurlconnection to post parameters to URL. The httpurlconnection seems to be posting fine when posting values without spaces however the issue appears when something like submit=Login Accountwhich contains a space. I have tried to use a plus symbol and %20 instead of the space however I have been unsuccessful submitting the form.
String requestParameters =“password=test123&confirm=test123&id=2869483&submit=Login Account”;
posting function
public static String postURL(String urlString, String parameters, int timeout, Proxy proxy, String accept, String acceptEncoding, String userAgent, String acceptLanguage) throws IOException {
URL address = new URL(urlString);
HttpURLConnection httpConnection = (HttpURLConnection) address.openConnection(proxy);
httpConnection.setRequestMethod("POST");
httpConnection.addRequestProperty("Accept", accept);
httpConnection.addRequestProperty("Accept-Encoding", acceptEncoding);
httpConnection.addRequestProperty("User-Agent", userAgent);
httpConnection.addRequestProperty("Accept-Language", acceptLanguage);
httpConnection.addRequestProperty("Connection", "keep-alive");
httpConnection.setDoOutput(true);
httpConnection.setConnectTimeout(timeout);
httpConnection.setReadTimeout(timeout);
DataOutputStream wr = new DataOutputStream(httpConnection.getOutputStream());
wr.writeBytes(parameters);
wr.flush();
wr.close();
httpConnection.disconnect();
BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
String result = response.toString();
in.close();
return result;
}
request to post using posting function
*
ArrayList<unlock> ns = new ArrayList<>();
try {
ns = methods.UnlockRequest("register#test.com");// gets urls from database.
} catch (IOException e) {
e.printStackTrace();
}
String s = ns.get(0).toString(); // gets first url in list
url=s; // sets url to s
String[] st= url.split("id="); // splits url to get id
System.out.println(url);
System.out.println(st[1]);
System.out.println("accounts class reached");
String requestParameters = null;
requestParameters = "password=test123&confirm=test123&id=2869483&submit=Login Account”;
System.out.println(requestParameters);
ConnectionSettings connectionSettings = Variables.get().getConnectionSettings();
String creation = "";
System.out.println(Variables.get().getCaptchaSolution());
try {
if (connectionSettings.isProxyCreation()) {
creation = HTTPRequests.postURL(url, requestParameters, 30000, connectionSettings.getProxy(), connectionSettings.getAcceptCriteria(), connectionSettings.getAcceptEncoding(),
connectionSettings.getUserAgent(), connectionSettings.getAcceptLanguage());
}
} catch (FileNotFoundException e) {
System.out.println(ColoredText.criticalMessage("Error: Your IP is banned from requesting. Ending script."));
Variables.get().setStopScript(true);
} catch (IOException e) {
e.printStackTrace();
Variables.get().setStopScript(true);
}
*
I wrote a Java program which generates HMAC SHA hash code, But due to some reason I have to write the same code in NodeJs/JavaScript. I tried googling around but did not get anything. In this Java code, I am passing URI and Key as arguments, to generate the hash code, where URI contains Timestamp.
The java code is as :
public static String calcMAC(String data, byte[] key) throws Exception {
String result=null;
SecretKeySpec signKey = new SecretKeySpec(key, SecurityConstants.HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(SecurityConstants.HMAC_SHA1_ALGORITHM);
mac.init(signKey);
byte[] rawHmac;
try {
rawHmac = mac.doFinal(data.getBytes("US-ASCII"));
result = Base64.encodeBase64String(rawHmac);
} catch (Exception e) {
e.printStackTrace();
}
return result.trim();
}
public static void main(String args[]) {
String timestamp = args[0];
String key = "d134hjeefcgkahvg32ajkdbaff84ff180";
String out = null;
try {
out = calcMAC("/req?app_id=47ca34" + timestamp + "=2018-05-22T12:02:15Z",
key.getBytes());
System.out.println(URLEncoder.encode(out, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
Is it possible to achieve the same goal in NodeJs/JavaScript?
Note:: I have to call this script from Postman pre-request script.
The crypto module should do this for you, you can substitute the 'data' variable with whatever you want to hash:
const crypto = require('crypto');
const data = 'The fault dear Brutus lies not in our stars';
const key = Buffer.from('d134hjeefcgkahvg32ajkdbaff84ff180', 'utf8');
const hash = crypto.createHmac('sha1', key).update(data).digest('base64');
const uriEncodedHash = encodeURIComponent(hash);
console.log('Hash: ' + uriEncodedHash);
Hashing the data in both Java and Node.js gives me the result (URI Encoded) of:
TJJ3xj93m8bfVpGoucluMQqkB0o%3D
The same Java code would be:
public static void main(String args[]) {
String data = "The fault dear Brutus lies not in our stars";
String key = "d134hjeefcgkahvg32ajkdbaff84ff180";
String out = null;
try {
out = calcMAC(data, key.getBytes());
System.out.println(URLEncoder.encode(out, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
Again, we can put anything into 'data' we want.
I have links that call a javascript function "GetDocument" which passes the ID of the link that the user wants to retrieve to an ashx page which than retrieves the document from a database and writes it back to the users browser if it's a PDF or opens the appropriate program if it's something else. These could be PDF's, XLS, DOCX.... etc.. When the user clicks a link that is a PDF everything work just fine and the PDF is opened within the browser. When the user opens anything else though, lets say for example an xlsx excel opens a garbage file with the name of the .ashx page. No errors occur and everything works with PDF. I'm kind of at a loss.
Here is the javascript
function GetDocument(id) {
spl1.loadPage('RightContent', 'FrmDocHandler.ashx?ID=' + id);
}
Here is the .ashx page
Public Class FrmDocHandler
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim sID As String = context.Request.QueryString("id")
Dim fileName As String = String.Empty
Dim fileType As String = String.Empty
Dim bytes() As Byte
bytes = Get_Blob(fileName, fileType, sSql_GetDocument(sID))
context.Response.Clear()
'clear the content of the browser
context.Response.ClearContent()
context.Response.ClearHeaders()
context.Response.Buffer = True
'I tried both of these add header and the same result
'context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)
context.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName)
context.Response.ContentType = GetMIMEType(fileType)
context.Response.BinaryWrite(bytes)
End Sub
MIME Types returned by GetMIMEType
Public Const g_MIME_DOC As String = "application/msword"
Public Const g_MIME_DOCX As String = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Public Const g_MIME_DOT As String = "application/msword"
Public Const g_MIME_DOTX As String = "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
Public Const g_MIME_HTM As String = "text/html"
Public Const g_MIME_HTML As String = "text/html"
Public Const g_MIME_JPEG As String = "image/jpeg"
Public Const g_MIME_PDF As String = "application/pdf"
Public Const g_MIME_PPSX As String = "application/vnd.openxmlformats-officedocument.presentationml.slideshow"
Public Const g_MIME_PPT As String = "application/vnd.ms-powerpoint"
Public Const g_MIME_PPTX As String = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
Public Const g_MIME_XLS As String = "application/vnd.ms-excel"
Public Const g_MIME_XLSX As String = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Public Const g_MIME_XLTX As String = "application/vnd.openxmlformats-officedocument.spreadsheetml.template"
Public Const g_MIME_XML As String = "application/rss+xml"
The line which is probably causing the file to be opened in Excel is the following:
context.Response.ContentType = GetMIMEType(fileType)
A couple of things you can do:
Check to see what MIME type is being returned by GetMIMEType, and ensure its a PDF related one (application/pdf) rather than an Excel related one (application/vnd.ms-excel)
Check on the browser end to see what application is set to handle the mime type and/or file extension that you are sending from the server
I made a Javascript page to generate a JSON object for read it then from Android device.
I read it with the following code
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null){
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to donwload file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The problem is that this code returns the source code of the webpage, and the source code is the script in Javascript, not the JSON string generated after execute it.
I need the JSON string and I need use Javascript to generate the JSON string because I access to an external service.
I haven't find any solution for this. I don't care if the possible solution involves the server or the Android terminal.
Thanks.
String myresponse=Html.escapeHtml(YourStringHere);
Try this.
private class MyJavaScriptInterface {
private MyJavaScriptInterface () {
}
public void setHtml(String contentHtml) {
//here you get the content html
}
}
private WebViewClient webViewClient = new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:window.ResponseChecker.setHtml"
+ "(document.body.innerHTML);");
}
}