We currently have a project in android and company wants to do some parts on server. Server side code in with Node JS. The thing I want to do looks very simple but I am stuck on that.
We have a long byte array which is compressed, in the android project I have his code that works fine and decompress the byte array. I want to do same in Node JS but I got the error incorrect data check.
public byte[] decompressBytes(byte[] compressedBytes) {
try {
Inflater decompresser = new Inflater();
decompresser.setInput(compressedBytes);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[2048];
while(!decompresser.finished()) {
int cnt = decompresser.inflate(buf);
if(cnt <= 0) {
break;
}
bos.write(buf, 0, cnt);
}
bos.close();
return bos.toByteArray();
} catch (Exception var6) {
return new byte[0];
}
}
Here is the code I wrote form the documents of Pako but as I told it returns error.
function decompress(data, callback) {
var response = '';
var pako = require('pako');
try {
response = pako.inflate(actData);
console.log("response : " + response);
callback('', response);
} catch (err) {
console.log(err);
callback(err, '');
}
}
The inputs are exactly same byte array.
Any help would be appreciated.
Related
I want to download a file when clicking on a button in my AngularJS app which runs on Tomcat with a Java Spring backend but nothing is happening. The method in the backend is called and everything seems to have worked....but my browser doesn't download anything.
What am I missing?
Here's the AngularJS code, which logs Export-Response:[object Object]:
exportProjects() {
let filteredProjectIds = [];
for (let i in this.filteredProjects) {
for (let x = 0, l = this.filteredProjects[i].length; x < l; x++) {
if (!this.isOldProjectsBundle(this.filteredProjects[i][x])) {
filteredProjectIds.push(this.filteredProjects[i][x].id);
}
}
}
this.$http.get('/profiles/projectWordExport?filteredProjects=' + filteredProjectIds.join(",")).then(response => {
console.log("Export-Response:" + response);
return response;
});
}
This is the Java code being called (it's really being called, already debugged it, no errors occuring):
#RequestMapping(value = "/projectWordExport", method = RequestMethod.GET)
public void getProjectsWord(HttpServletRequest request, HttpServletResponse response, #RequestParam String filteredProjects) throws Exception {
//Load project objects from input string or load all projects if input empty
List<Project> projects = new java.util.ArrayList<>();
if (filteredProjects.isEmpty()) {
projects = projectRepository.findAll();
} else {
String[] pIds = filteredProjects.split(",");
for (String pId : pIds) {
projects.add(projectRepository.findById(Long.parseLong(pId)));
}
}
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader("Content-disposition", "attachment;filename=Projektexport.docx");
try {
SaveToZipFile saver = new SaveToZipFile(printer.printProjects(this.prepareProjectExport(projects)));
saver.save(response.getOutputStream());
response.flushBuffer();
} catch (NullPointerException e) {
response.setStatus(500);
response.sendError(500, "Fehler beim exportieren des Tests aufgetreten");
}
}
Put this in #RequestMapping annotation
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.
Controller code of Angular Js...
FactoryPBD.showPbdCostCompareData(data).success(
function(result) {
if(result != ""){
//doing my processing and working fine
}).error(function(result,status,message){
console.log("result" , result);
//getting undefined in all the above variable
});
Service code:
showPbdCostCompareData : function(filter) {
promise = $http({
url : 'pbd/showPbdCostCompareData?serachFilterJson='+JSON.stringify(filter),
method : "POST"
});
return promise;
}
Java Controller:-
#RequestMapping(value = "/showPbdCostCompareData", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<String> showPbdCostCompareData(HttpServletRequest request,
#RequestParam String serachFilterJson) {
try {
if (null != serachFilterJson && !"".equalsIgnoreCase(serachFilterJson)) {
Gson gson = new Gson();
SearchCriteriaBean searchCriteriaObj = gson.fromJson(serachFilterJson, SearchCriteriaBean.class);
CnHeaderBean cnHeaderBean = pbdServiceImpl.getPbdCostCompareCnHeaderData(searchCriteriaObj); //getting the value from sevice
List<PbdCostCompareBean> pbdCostCompareList = null;
if (null != cnHeaderBean) {
if("F".equalsIgnoreCase(cnHeaderBean.getPbdType())){
searchCriteriaObj.setFromPartIscb(cnHeaderBean.getFromPartIscb());
searchCriteriaObj.setToPartIscb(cnHeaderBean.getToPartIscb());
pbdCostCompareList = pbdServiceImpl.getPbdCostComparisonData(searchCriteriaObj); //getting the value from sevice
}else{
return new ResponseEntity<String>("Incorrect PBD Type",HttpStatus.SERVICE_UNAVAILABLE);
}
} else {
return new ResponseEntity<String>(HttpStatus.SERVICE_UNAVAILABLE);
}
HashMap<Integer, Object> costCompareMap = new HashMap<Integer, Object>();
costCompareMap.put(1, cnHeaderBean);
costCompareMap.put(2, pbdCostCompareList);
costCompareMap.put(3, pbdServiceImpl.validateUserAccess(searchCriteriaObj, serviceUtility.getUserFromSession(request)));
String pbdDataJsonResponse = gson.toJson(costCompareMap);
return new ResponseEntity<String>(pbdDataJsonResponse, HttpStatus.OK);
} else {
return new ResponseEntity<String>(HttpStatus.SERVICE_UNAVAILABLE);
}
} catch (C2PCException e) {
return new ResponseEntity<String>(e.getMessage(),HttpStatus.SERVICE_UNAVAILABLE);
}
}
I am using Spring Rest controller with Angular js for my project. Things are working fine and data is properly sent to client side when there is no error at Java side. But in case there is an exception at java side then depending upon the exception i want to return my message to the user.My response text is not getting transmitted to the client side. Any help will be appreciated. Code is provided above
Here in above e.getMessage, i get my custom message which i have set in mu service layer and throws the exception from there. But in the client side in error message i get all the values as undefined.
I assume that in angular js when an error occurs, a JSON is expected and not html/text
So, convert the exception to json.
You can create a class
ie
class ClassErrorMessage {
private String errorCode;
private String errorMessage;
ClassErrorMessage() {
}
//getters and setters
}
and then
catch (C2PCException e) {
ClassErrorMessage classErrorMessage= new ClassErrorMessage();
classErrorMessage.setErrorCode("some code that you may want");
classErrorMessage.setErrorMessage(e.getMessage());
String error = gson.toJson(classErrorMessage);
return new ResponseEntity<String>(error,HttpStatus.SERVICE_UNAVAILABLE);
}
and let me know if this worked for you
is it possible to render a specific page in a razor function. I tried #RenderPage but i cant figure out the path. Are there any built in functions to accomplish this?
Thanks Johan
Not really a C1 specific approach, but personally my best approach has been to just make a separate web-request for the page in question, parse out the html and render it.
This code can serve as an example, its a 1:1 of what i'm using. As you can see the trick is to find the element that wraps your content, in my example its the element inside that has an id equals to ContentColumnInner
public static string GetContentFromPage(Guid pageId)
{
var DomainName = HttpContext.Current.Request.Url.Authority;
var Uri = String.Format("http://{0}/page({1})", DomainName, pageId);
var request = WebRequest.Create(Uri);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
using (var response = (HttpWebResponse)request.GetResponseWithoutException())
{
if (response.StatusCode != HttpStatusCode.OK)
{
LogError("StatusCode: " + response.StatusCode);
return null;
}
// Get the stream containing content returned by the server.
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null)
{
LogError("ResponseStream is null");
return null;
}
// Open the stream using a StreamReader for easy access.
using (var stream = new StreamReader(responseStream))
{
// Read the content.
var responseFromServer = stream.ReadToEnd();
var beforeBodyStartIndex = responseFromServer.IndexOf("<body", StringComparison.Ordinal);
var afterBodyEndIndex = responseFromServer.LastIndexOf("</body>", StringComparison.Ordinal) + 7;
var body = responseFromServer.Substring(beforeBodyStartIndex, afterBodyEndIndex - beforeBodyStartIndex);
try
{
var xmlDocument = XElement.Parse(body);
var content = xmlDocument.Descendants().FirstOrDefault(o => o.Attribute("id") != null && o.Attribute("id").Value.EndsWith("ContentColumnInner"));
if (content == null || !content.HasElements)
{
return null;
}
var reader = content.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
catch (XmlException ex)
{
LogError("Error parsing xml: " + ex.Message);
return null;
}
}
}
}
}
I want to get value of an array from JSON code in internet. from this URL : http://olympics.clearlytech.com/api/v1/medals/
after that, I want to display that array of my script without rewrite that JSON code on this URL http://olympics.clearlytech.com/api/v1/medals/
so, what code (script) that I can use?
for example, I want to display value from this array
var JSONs = {
example:['one','two','three']
};
the code is
document.write(JSONs.example[0]);
but if I want get the array value from the internet, what code/script that I can use?
Using jQuery, here is an example. In the success event, turn the resulting json text into a json object. You could also set the content type as json so you wouldn't have to call the JSON.parse().
$.ajax({
url: "http://olympics.clearlytech.com/api/v1/medals/",
success: function(data) {
var json = JSON.parse(data);
}
});
This is another way of doing the same i hope you asked how to parse through each value just try this in jsfiddle
$(document).ready(function(){
alert("here");
$.getJSON("http://olympics.clearlytech.com/api/v1/medals/",function(data){
$.each(data,function(key,value){
alert(data[key].country_name);
alert(data[key].rank);
console.log(data[key].rank));
});
});
});
public void handleResponse(String response)
{
// display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
jso = new JSONObject(response);
String status = jso.getString("status");
int valid=jso.getInt("valid");
// display("Welcome : "+UName);
if(valid>0)
{
if( status.equalsIgnoreCase("") || status==null || status.equalsIgnoreCase("Failed"))
{
invalid.setText("Invalid password");
//reset();
pwd.setText("");
}
else
{
//display(status);
intObj=new Intent(MainActivity.this,Design_Activity.class);
intObj.putExtra("Username", mUname);
startActivity(intObj);
MainActivity.this.finish();
}
}
else
{
invalid.setText("Invalid userid");
uname.setText("");
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Althought you want us to do everything, thats why your question went negative. Anyhow this is how you can do it in plain ajax
function getData(){
// Initialize the Ajax request
var xhr=new XMLHttpRequest();
xhr.open('get', 'http://olympics.clearlytech.com/api/v1/medals/');
// Track the state changes of the request
xhr.onreadystatechange=function(){
// Ready state 4 means the request is done
if(xhr.readyState === 4){
// 200 is a successful return
if(xhr.status === 200){
alert(xhr.responseText); // 'This is the returned text.'
}else{
alert('Error: '+xhr.status); // An error occurred during the request
}
}
}
// Send the request to send-ajax-data.php
xhr.send(null);
}