CHTTPFile::SendRequest get feedback data from server - post

I used successfully to post a form to my webserver using MFC's function CHttpFile::SendRequest. The server respond success with return code 200.
The problem is that I want to get more data from the server like a custom process code or a custom string code. For example pFile->ReadString(str)
gives me the chance to read something but what ?
How to setup my server to send back to caller such informations ? My server runs apache.

The Read/ReadString below returns anything you want to return. Just decode each line you receive from the server.
pFile->ReadString(str)
CString MyClass::PostWebFormActivation() {
CString strHeaders;
CInternetSession session;
CString strFormData;
CHttpConnection *pConnection;
CHttpFile *pFile;
BOOL result;
DWORD dwRet;
CString strServerResponse;
CString strExceptionError;
INTERNET_PORT nPort(80);
CString strServer;
CString strObject;
CString strSubmitValue = _T("1");
CString strLine;
CString strTemp;
INT pos;
CUtils util;
// URL-encoded form variables -
// serial = "xxxxxxx", systemcode = "xxxxx", username = "xxxxxxx", restoreemail = "xxxxxxx". strCAPTCHA = "Xyz!"
strFormData = _T(SUBMIT_FORM) + _T(strSubmitValue)+ _T(SERIAL_FIELD) + _T(m_strSerial) + _T(SYSTEMCODE_FIELD) + _T(m_strSystemCode) + _T(USERNAME_FIELD) + _T(m_strUsername) + _T(RESTORE_EMAIL_FIELD) + _T(m_strRestoreEmail) + _T(CAPTCHA_FIELD);
pConnection = NULL;
pFile = NULL;
//I can use the AfxParseURL instead of the following code
strServer = ((CMainFrame *)AfxGetMainWnd())->m_strWebActivateProductURL;
strTemp = strServer;
strTemp.MakeUpper();
pos = strTemp.Find(_T("HTTP://"));
if (pos != -1) {
strServer = strServer.Mid(7); // remove http://
}
pos = strServer.Find('/',0);
strObject = strServer.Mid(pos); //the path after the domain ie /dir/index.php
strServer = strServer.Left(pos);//server is the actual domain ie www.mywebsite.gr
if (util.CheckURLFileExtension(strObject) == _T("") ) {
//folder
if (strObject.Find('/',strObject.GetLength()) == -1) {
strObject += _T("/?");
}
} else {
//file
strObject += _T("?");
}
try {
pConnection = session.GetHttpConnection( strServer , nPort);
pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST /*HTTP_VERB_GET*/,strObject /*_T("/paradox4a/activate/?") or _T("/paradox4a/activate/index.php?")*/);
//pFile->AddRequestHeaders(szHeaders); //not needed.
strHeaders = _T("Content-Type: application/x-www-form-urlencoded\r\n");
result = pFile->SendRequest(strHeaders, (LPVOID) (LPCTSTR) strFormData, strFormData.GetLength());
if (result > 0) {
pFile->QueryInfoStatusCode(dwRet);
strServerResponse.Empty();
if (dwRet == HTTP_STATUS_OK) {
while(pFile->ReadString(strLine)) {
strServerResponse += strLine + "\r\n";
}
} else {
strServerResponse = _T("ERROR");
AMLOGINFO(_T("Trying to post a form to server for activation procedure, got communication error [%d]" ), dwRet);
}
} else {
strServerResponse = _T("ERROR");
AMLOGINFO(_T("Trying to post a form to server for activation procedure, got communication error [%d]" ), result );
}
} catch (CInternetException* pEx) {
TCHAR sz[1024];
CString s = util.getInetError(pEx->m_dwError);
strServerResponse = _T("ERROR");
pEx->GetErrorMessage( sz,1024 );
pEx->Delete();
AMLOGINFO(_T("Trying to post a form to server for activation procedure, got network error [%s]" ), strExceptionError );
}
if (pFile) {
pFile->Close();
delete pFile;
}
if (pConnection) {
pConnection->Close();
delete pConnection;
}
return strServerResponse;
}

Related

Ads script: errors when create keywords CONCURRENT_MODIFICATION without any modification

I have a script which copy ads, keywords, negativeKeywords, sitelinks, callouts, shippets from master account to slave account
Everything works properly. But when I create keywords in slave account I receive errors
[CONCURRENT_MODIFICATION : DatabaseError.CONCURRENT_MODIFICATION : ]
Most weird that from 10 execution of script 5 can be executed without any error but 5 with error
function copyKeywords(slaveGroup, masterKeywordsData, replicationSettings) {
var count = Object.keys(masterKeywordsData).length;
l('Copying %s keywords...', count);
for (var i = 0; i < count; i++) {
var key = Object.keys(masterKeywordsData)[i];
var masterKeywordData = masterKeywordsData[key];
log('%s/%s - Replicating keyword %s...', (parseInt(i) + 1), count, masterKeywordData.id);
log('Keyword data: %s', JSON.stringify(masterKeywordData));
var slaveKeyword = null;
var finalUrl = null;
if(masterKeywordData.finalUrl) {
finalUrl = formateUrl(masterKeywordData.finalUrl, replicationSettings);
}
slaveKeyword = slaveGroup
.newKeywordBuilder()
.withText(masterKeywordData.text);
if(finalUrl) {
slaveKeyword = slaveKeyword
.withFinalUrl(finalUrl);
}
slaveKeyword = slaveKeyword
.build();
if (slaveKeyword == null) {
log('Nothing was replicated');
} else {
if (slaveKeyword.isSuccessful()) {
log('Keyword %s successfuly replicated', masterKeywordData.id);
} else {
log(slaveKeyword.getErrors());
error('Cannot replicate keyword %s ', masterKeywordData.id);
}
}
sleep(2000);
}
}
With 2000 milliseconds sleep I receive errors not so often. But sometimes it happens(
Does anybody know why I receive error about
[CONCURRENT_MODIFICATION : DatabaseError.CONCURRENT_MODIFICATION : ]
cause I do not make any modification

Mp4 cannot play on iOS by request spring mvc server resource, but working on Nginx access mp4 file directly

I have two scenario when play mp4 file on iOS devices.
MP4 access by Nginx is working:
Put mp4 file in /html and using following configure, then iOS devices and chrome browser can play mp4 files properly.
server {
listen 127.0.0.1:80 default_server;
location ~ ^/storage\/*.mp4 {
root html;
}
}
MP4 access by Tomcat Spring MVC is not working: When I request by Spring mvc restful API and return ResponseEntity contains Resource Object, in chrome browser will receive and play mp4 properly. But iOS devices not working
#GetMapping(value = "/storage/{filename:.+}")
#ResponseBody
public ResponseEntity<org.springframework.core.io.Resource> accessStorageFile(HttpServletResponse response, #PathVariable String filename) throws IOException {
org.springframework.core.io.Resource resource = storageUtil.loadAsResource(filename);
InputStream inputStream = resource.getInputStream();
InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
String contentType = FileTypeMap.getDefaultFileTypeMap().getContentType(resource.getFile());
contentType = resource.getFilename().contains(".mp4") ? "video/mp4" : contentType;
response.setContentType(contentType);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.valueOf(contentType));
responseHeaders.setContentLength(resource.getFile().length());
return new ResponseEntity<>(inputStreamResource, responseHeaders, HttpStatus.OK);
}
import java.io.BufferedInputStream; import java.io.File; import
java.io.IOException; import java.io.InputStream; import
java.io.OutputStream; import java.nio.file.Files; import
java.nio.file.Path; import java.nio.file.Paths; import
java.nio.file.attribute.FileTime; import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneOffset; import
java.util.ArrayList; import java.util.Arrays; import java.util.List;
import javax.servlet.ServletOutputStream; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse; import
org.springframework.util.StringUtils;
/** * * #author David 1 */ public class MultipartFileSender {
private static final int DEFAULT_BUFFER_SIZE = 20480; // ..bytes = 20KB.
private static final long DEFAULT_EXPIRE_TIME = 604800000L; // ..ms = 1 week.
private static final String MULTIPART_BOUNDARY = "MULTIPART_BYTERANGES";
Path filepath;
HttpServletRequest request;
HttpServletResponse response;
public MultipartFileSender() {
}
public static MultipartFileSender fromPath(Path path) {
return new MultipartFileSender().setFilepath(path);
}
public static MultipartFileSender fromFile(File file) {
return new MultipartFileSender().setFilepath(file.toPath());
}
public static MultipartFileSender fromURIString(String uri) {
return new MultipartFileSender().setFilepath(Paths.get(uri));
}
//** internal setter **//
private MultipartFileSender setFilepath(Path filepath) {
this.filepath = filepath;
return this;
}
public MultipartFileSender with(HttpServletRequest httpRequest) {
request = httpRequest;
return this;
}
public MultipartFileSender with(HttpServletResponse httpResponse) {
response = httpResponse;
return this;
}
public void serveResource() throws Exception {
if (response == null || request == null) {
return;
}
if (!Files.exists(filepath)) {
System.out.println("File doesn't exist at URI : {" + filepath.toAbsolutePath().toString() + "}");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
Long length = Files.size(filepath);
String fileName = filepath.getFileName().toString();
FileTime lastModifiedObj = Files.getLastModifiedTime(filepath);
if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
long lastModified = LocalDateTime.ofInstant(lastModifiedObj.toInstant(),
ZoneId.of(ZoneOffset.systemDefault().getId())).toEpochSecond(ZoneOffset.UTC);
String contentType = "video/mp4";
// Validate request headers for caching ---------------------------------------------------
// If-None-Match header should contain "*" or ETag. If so, then return 304.
String ifNoneMatch = request.getHeader("If-None-Match");
if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, fileName)) {
response.setHeader("ETag", fileName); // Required in 304.
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
// If-Modified-Since header should be greater than LastModified. If so, then return 304.
// This header is ignored if any If-None-Match header is specified.
long ifModifiedSince = request.getDateHeader("If-Modified-Since");
if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
response.setHeader("ETag", fileName); // Required in 304.
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
// Validate request headers for resume ----------------------------------------------------
// If-Match header should contain "*" or ETag. If not, then return 412.
String ifMatch = request.getHeader("If-Match");
if (ifMatch != null && !HttpUtils.matches(ifMatch, fileName)) {
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
// If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
// Validate and process range -------------------------------------------------------------
// Prepare some variables. The full Range represents the complete file.
Range full = new Range(0, length - 1, length);
List<Range> ranges = new ArrayList<>();
// Validate and process Range and If-Range headers.
String range = request.getHeader("Range");
if (range != null) {
// Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return;
}
String ifRange = request.getHeader("If-Range");
if (ifRange != null && !ifRange.equals(fileName)) {
try {
long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
if (ifRangeTime != -1) {
ranges.add(full);
}
} catch (IllegalArgumentException ignore) {
ranges.add(full);
}
}
// If any valid If-Range header, then process each part of byte range.
if (ranges.isEmpty()) {
for (String part : range.substring(6).split(",")) {
// Assuming a file with length of 100, the following examples returns bytes at:
// 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
long start = Range.sublong(part, 0, part.indexOf("-"));
long end = Range.sublong(part, part.indexOf("-") + 1, part.length());
if (start == -1) {
start = length - end;
end = length - 1;
} else if (end == -1 || end > length - 1) {
end = length - 1;
}
// Check if Range is syntactically valid. If not, then return 416.
if (start > end) {
response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return;
}
// Add range.
ranges.add(new Range(start, end, length));
}
}
}
// Prepare and initialize response --------------------------------------------------------
// Get content type by file name and set content disposition.
String disposition = "inline";
// If content type is unknown, then set the default value.
// For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
// To add new content types, add new mime-mapping entry in web.xml.
if (contentType == null) {
contentType = "application/octet-stream";
} else if (!contentType.startsWith("image")) {
// Else, expect for images, determine content disposition. If content type is supported by
// the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
String accept = request.getHeader("Accept");
disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
}
System.out.println("Content-Type : {" + contentType + "}");
// Initialize response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setHeader("Content-Type", contentType);
response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
System.out.println("Content-Disposition : {" + disposition + "}");
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("ETag", fileName);
response.setDateHeader("Last-Modified", lastModified);
response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);
// Send requested file (part(s)) to client ------------------------------------------------
// Prepare streams.
try (InputStream input = new BufferedInputStream(Files.newInputStream(filepath));
OutputStream output = response.getOutputStream()) {
if (ranges.isEmpty() || ranges.get(0) == full) {
// Return full file.
System.out.println("Return full file");
response.setContentType(contentType);
response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total);
response.setHeader("Content-Length", String.valueOf(full.length));
Range.copy(input, output, length, full.start, full.length);
} else if (ranges.size() == 1) {
// Return single part of file.
Range r = ranges.get(0);
System.out.println("Return 1 part of file : from ({" + r.start + "}) to ({" + r.end + "})");
response.setContentType(contentType);
response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
response.setHeader("Content-Length", String.valueOf(r.length));
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.
// Copy single part range.
Range.copy(input, output, length, r.start, r.length);
} else {
// Return multiple parts of file.
response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.
// Cast back to ServletOutputStream to get the easy println methods.
ServletOutputStream sos = (ServletOutputStream) output;
// Copy multi part range.
for (Range r : ranges) {
System.out.println("Return multi part of file : from ({" + r.start + "}) to ({" + r.end + "})");
// Add multipart boundary and header fields for every range.
sos.println();
sos.println("--" + MULTIPART_BOUNDARY);
sos.println("Content-Type: " + contentType);
sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);
// Copy single part range of multi part range.
Range.copy(input, output, length, r.start, r.length);
}
// End with multipart boundary.
sos.println();
sos.println("--" + MULTIPART_BOUNDARY + "--");
}
}
}
private static class Range {
long start;
long end;
long length;
long total;
/**
* Construct a byte range.
*
* #param start Start of the byte range.
* #param end End of the byte range.
* #param total Total length of the byte source.
*/
public Range(long start, long end, long total) {
this.start = start;
this.end = end;
this.length = end - start + 1;
this.total = total;
}
public static long sublong(String value, int beginIndex, int endIndex) {
String substring = value.substring(beginIndex, endIndex);
return (substring.length() > 0) ? Long.parseLong(substring) : -1;
}
private static void copy(InputStream input, OutputStream output, long inputSize, long start, long length) throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int read;
if (inputSize == length) {
// Write full range.
while ((read = input.read(buffer)) > 0) {
output.write(buffer, 0, read);
output.flush();
}
} else {
input.skip(start);
long toRead = length;
while ((read = input.read(buffer)) > 0) {
if ((toRead -= read) > 0) {
output.write(buffer, 0, read);
output.flush();
} else {
output.write(buffer, 0, (int) toRead + read);
output.flush();
break;
}
}
}
}
}
private static class HttpUtils {
/**
* Returns true if the given accept header accepts the given value.
*
* #param acceptHeader The accept header.
* #param toAccept The value to be accepted.
* #return True if the given accept header accepts the given value.
*/
public static boolean accepts(String acceptHeader, String toAccept) {
String[] acceptValues = acceptHeader.split("\\s*(,|;)\\s*");
Arrays.sort(acceptValues);
return Arrays.binarySearch(acceptValues, toAccept) > -1
|| Arrays.binarySearch(acceptValues, toAccept.replaceAll("/.*$", "/*")) > -1
|| Arrays.binarySearch(acceptValues, "*/*") > -1;
}
/**
* Returns true if the given match header matches the given value.
*
* #param matchHeader The match header.
* #param toMatch The value to be matched.
* #return True if the given match header matches the given value.
*/
public static boolean matches(String matchHeader, String toMatch) {
String[] matchValues = matchHeader.split("\\s*,\\s*");
Arrays.sort(matchValues);
return Arrays.binarySearch(matchValues, toMatch) > -1
|| Arrays.binarySearch(matchValues, "*") > -1;
}
} }
use is in your controller and make sure you are not use #RestController
you should use #Controller, and following class in void method
#RequestMapping(method = RequestMethod.GET, value = "/getFile")
public void getFile(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception {
MultipartFileSender.fromPath(Paths.get("D:\8561523973120206.mp4"))
.with(httpRequest)
.with(httpResponse)
.serveResource();
}

Error when attempting to save image data on Mac/iOS with Haxe

I'm creating a set of Haxe functions that saves text and images to a file. These functions work just fine on Windows and Android; however, a tester has informed me that attempting to save an image produces this error on iOS and Mac:
ERROR: Failure type not string # ./File.cpp:123
Here's the code for the two functions.
public static function savePNG(path:String, image:BitmapData, ?whenDone:Bool->Void):Void {
if (path.substr(path.length - 4).toLowerCase() != ".png") { path += ".png"; }
// Flash: Not possible to save; error out
#if flash
trace("ERROR: File IO cannot be accessed on Flash.");
if (whenDone != null)
whenDone(false);
#elseif js
trace("ERROR: File IO cannot be accessed on HTML5.");
if (whenDone != null)
whenDone(false);
// Windows, Mac, Linux, iOS, and Android: Use the "saveText" function with the converted file
#else
var b:ByteArray = image.encode("png", 1);
saveText(path, b.toString(), whenDone);
#end
}
public static function saveText(path:String, content:String, ?whenDone:Bool->Void):Void {
var success:Bool = true;
var path2:String = "";
path = "/assets/data/" + path;
var a:Array<String> = DataUtils.subfold(path);
// Flash or HTML5: Not possible to save; error out
#if (flash || js)
success = false;
#if flash
trace("ERROR: File IO cannot be accessed on Flash.");
#else
trace("ERROR: File IO cannot be accessed on HTML5.");
#end
// iOS and Android: Attempt to save to the storage directory
#elseif mobile
if (!FileSystem.exists(SystemPath.userDirectory + "/" + a[0])) {
FileSystem.createDirectory(SystemPath.userDirectory + "/" + a[0]);
}
path2 = SystemPath.userDirectory + "/" + a[0] + "/" + a[1];
try {
File.saveContent(path2, Std.string(content));
} catch (e:Dynamic) {
success = false;
trace("ERROR: " + e);
errorify(e);
}
// Windows, Mac, and Linux: Save straight to the "assets/data/" folder
#else
if (!FileSystem.exists(FileSystem.fullPath(a[0]))) {
FileSystem.createDirectory(FileSystem.fullPath(a[0]));
}
path2 = FileSystem.fullPath(a[0] + "/" + a[1]);
try {
File.saveContent(path2, Std.string(content));
} catch (e:Dynamic) {
success = false;
trace("ERROR: " + e);
errorify(e);
}
#end
if (whenDone != null)
whenDone(success);
}
The error is coming from the last trace("ERROR: " + e); line. I would troubleshoot myself, but I don't have a Mac or iOS device, and I'm not sure what information I need from the tester.
Bottom line: If there is an apparent error in this code, how can it be fixed? If not, for what troubleshooting information do I need to ask?
My guess is that something is messing up during Bytes->String conversion which is completely unnecessary here. I suggest you to remove it and use binary version of the FileOutput. If you are using the latest version of lime you can cast your ByteArray to Bytes (since ByteArray underlying type is Bytes) and write that to the FileOutput. Here is how the 'write' part should look like
/**
* Save bytes as a file
* #param path
* #param content
* #return true if succeed, false overwise
*/
static function saveBytes(path:String, content:Bytes):Bool
{
var success = false;
var fo:FileOutput = null;
try {
//open binary file and write bytes
fo = File.write(path, true);
fo.writeBytes(content, 0, content.length);
success = true;
} catch (e:Dynamic) {
trace("ERROR: " + e);
errorify(e);
}
//file output should be closed in any case
try {
if (fo != null)
fo.close();
} catch (e:Dynamic) {
trace("ERROR: " + e);
errorify(e);
}
return success;
}
Also, encoding part
/* insert your path construction here */
var b:ByteArray = image.encode("png", 1);
var success = saveBytes(path, (b:Bytes));
if (whenDone != null)
whenDone(success);

Reading Windows event log using JNA provides me only part of the description available in Event Veiwer

This is my code Provide me details where am going wrong so that am
getting only the part of the description available
========================================================================
http://code.dblock.org/jna-reading-windows-event-log-entries-in-java
#SuppressWarnings("unused")
public void testReadEventLogEntries() throws CharacterCodingException {
final Charset charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");
final CharsetEncoder encoder = charset.newEncoder();
final CharsetDecoder decoder = charset.newDecoder();
int i = 0;// loop contro variable
String type = null; // Type of the event
String user = null;
String str[] = { "System", "Application" };
while (i < 2) {
System.out.println("\n\n" + str[i]);
HANDLE h = Advapi32.INSTANCE.OpenEventLog(null, str[i]);
IntByReference pnBytesRead = new IntByReference();
IntByReference pnMinNumberOfBytesNeeded = new IntByReference();
Memory buffer = new Memory(1024 * 64);
IntByReference pOldestRecord = new IntByReference();
int dwRecord = pOldestRecord.getValue();
int rc = 0;
while (true) { // Travesing the read log records
if (!Advapi32.INSTANCE.ReadEventLog(h,
WinNT.EVENTLOG_SEQUENTIAL_READ
| WinNT.EVENTLOG_FORWARDS_READ, 0, buffer,
(int) buffer.size(), pnBytesRead,
pnMinNumberOfBytesNeeded)) {
rc = Kernel32.INSTANCE.GetLastError();
if (rc == W32Errors.ERROR_INSUFFICIENT_BUFFER) {
buffer = new Memory(pnMinNumberOfBytesNeeded.getValue());
continue;
}
break;
}
int dwRead = pnBytesRead.getValue();
Pointer pevlr = buffer;
while (dwRead > 0) {
EVENTLOGRECORD record = new EVENTLOGRECORD(pevlr);
EventLogRecord event = new EventLogRecord(pevlr);
org.hyperic.sigar.win32.EventLogRecord sigar;
EventLog log = new EventLog();
if (record.EventType.intValue() == 1)
type = "Error";
else if (record.EventType.intValue() == 10)
type = "Failure Audit";
else if (record.EventType.intValue() == 8)
type = "Sucess Audit";
else if (record.EventType.intValue() == 4)
type = "Information";
else
type = "Warning";
ByteBuffer names = pevlr
.getByteBuffer(
record.size(),
(record.UserSidLength.intValue() != 0 ? record.UserSidOffset
.intValue() : record.StringOffset
.intValue())
- record.size());
names.position(0);
CharBuffer namesBuf = names.asCharBuffer();
String[] splits = namesBuf.toString().split("\0");
if (record.UserSidLength.intValue() != 0) {
ByteBuffer usersid = pevlr.getByteBuffer(
record.UserSidOffset.intValue(),
record.UserSidLength.intValue());
usersid.position(0);
CharBuffer sidBuf = usersid.asCharBuffer();
String[] sp = sidBuf.toString().split("\0");
// System.out.println(sp[0] + sp[1] + sp[2]);
/*
* dst.get user= new String(dst);
*/
} else {
user = "N/A";
}
System.out.println(type + "\t" + toDate(record) + "\t"
+ event.getSource() + "\t" + record.EventCategory
+ "\t" + record.EventID.shortValue() + "\t" + user
+ "\t" + splits[1]);
ByteBuffer strings = pevlr.getByteBuffer(
record.StringOffset.longValue(),
record.DataOffset.intValue()
- record.StringOffset.intValue());
CharBuffer stringsBuf = strings.asCharBuffer();
System.out.println("Desc: " + stringsBuf.toString());
dwRecord++;
dwRead -= record.Length.intValue();
pevlr = pevlr.share(record.Length.intValue());
}
}
i++;
}
}
// Method to convert the timestamp to formated date
public Date toDate(EVENTLOGRECORD record) {
Timestamp stamp = new Timestamp(record.TimeWritten.longValue() * 1000);
Date date = new Date(stamp.getTime());
return date;
}
}
Finally I figured out the solution....The description returned by the
above code is just the insertion strings needed to build the message.
Instead of using jna I used WMI which is simple to use and more handy
/**
* #param args
*/
public static void main(String[] args) throws COMException {
String computerName = ".";
String userName = "";
String password = "";
String namespace = "root/cimv2";
String Message = "";
String queryProcessor = "Select * from Win32_NTLogEvent where Logfile='System'or Logfile='Application'";
DispatchPtr dispatcher = null;
try {
ISWbemLocator locator = new ISWbemLocator(
"WbemScripting.SWbemLocator");
ISWbemServices wbemServices = locator.ConnectServer(computerName,
namespace, userName, password, "", "", 0, dispatcher);
ISWbemObjectSet wbemObjectSet = wbemServices.ExecQuery(
queryProcessor, "WQL", 0, null);
DispatchPtr[] results = new DispatchPtr[wbemObjectSet.getCount()];
IUnknown unknown = wbemObjectSet.get_NewEnum();
IEnumVariant enumVariant = (IEnumVariant) unknown
.queryInterface(IEnumVariant.class);
enumVariant.Next(wbemObjectSet.getCount(), results);
for (int i = 0; i < results.length; i++) {
ISWbemObject wbemObject = (ISWbemObject) results[i]
.queryInterface(ISWbemObject.class);
if (wbemObject.get("Message") != null) {
Message = (String) wbemObject.get("Message");
} else {
Message = "The description for Event ID ("
+ wbemObject.get("EventCode")
+ " ) in Source ( "
+ wbemObject.get("SourceName")
+ ") cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details.";
}
System.out.println(wbemObject.get("Logfile") + "\t"
+ wbemObject.get("Type") + "\t"
+ toDate(wbemObject.get("TimeGenerated").toString())
+ "\t"
+ toTime(wbemObject.get("TimeGenerated").toString())
+ "\t" + wbemObject.get("EventCode") + "\t"
+ wbemObject.get("ComputerName") + "\t" + Message);
// System.out.println(wbemObject.GetObjectText_(0));
}
} catch (COMException e) {
e.printStackTrace();
}
}
public static String toDate(String time) throws COMException {
String date = time.substring(6, 8) + "-" + time.substring(4, 6) + "-"
+ time.substring(0, 4);
return date;
}
public static String toTime(String time) throws COMException {
String Generatedtime = time.substring(8, 10) + ":"
+ time.substring(10, 12) + ":" + time.substring(12, 14) + ":"
+ time.substring(16, 21) + "-" + "GMT" + time.substring(21, 25);
return Generatedtime;
}

Stream file from ftp in localhost working in azure no

Hi I using VisualStudio 2012 and I have created web site which reads info (from .csv) from external ftp site. When I running it on local host everything works fine, but then I deployed it to azure web sites it is not working, just show zeros everywhere were should be numbers. (Dont get info from ftp)
public static List<ApiClient.Models.StatsList> GetStatsData(string Ticket, DateTime start, DateTime end, int CampaignId, String CampaignName)
{
//--------------------------------------------------------------------------------------------------------
//Gets stats from GetAdsStats service (included: Banner id, impressions, and clicks)
//--------------------------------------------------------------------------------------------------------
List<ApiClient.Models.StatsList> FullList = GetAdStatsService.GetAdsStats(Ticket, start, end, CampaignId);
List<LikesDislikesList> LikeDislike = new List<LikesDislikesList>();
//--------------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------------
string day;
string month;
if (DateTime.Today.AddDays(-1).Day.ToString().Count() == 1)
{
day = "0" + DateTime.Today.AddDays(-1).Day;
}
else
{
day = DateTime.Today.AddDays(-1).Day.ToString();
}
if (DateTime.Today.Month.ToString().Count() == 1)
{
month = "0" + DateTime.Today.Month;
}
else
{
month = DateTime.Today.Month.ToString();
}
try
{
string uri = "ftp://siteAdres" + CampaignName.Replace(" ", "_") + "_Optimizing_events_" + day + "-" + month + "-" + DateTime.Today.Year + ".csv";
Uri serverUri = new Uri(uri);
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return FullList;
}
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential("username", "password");
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader csvStream = new StreamReader(response.GetResponseStream());
//--------------------------------------------------------------------------------------------------------
//Read Likes/Dislikes from csv file stream
//--------------------------------------------------------------------------------------------------------
using (var rd = csvStream)
{
int iname = -1;
int ilikes = -1;
int idislikes = -1;
while (!rd.EndOfStream)
{
var raw = rd.ReadLine().Split((char)9);
if (rd.Peek() == -1)
{
break;
}
if (ilikes == -1 || idislikes == -1)
{
for (int i = 0; i < raw.Length; i++)
{
if (raw[i] == "Event name")
iname = i;
if (raw[i] == "Custom Event 14")
ilikes = i;
if (raw[i] == "Custom Event 15")
{
idislikes = i;
raw = rd.ReadLine().Split((char)9);
}
}
}
else
{
LikeDislike.Add(new LikesDislikesList() { Likes = Convert.ToInt32(raw[ilikes]), Dislikes = Convert.ToInt32(raw[idislikes]), Name = raw[iname] });
}
}
}
response.Close();
}
catch(Exception ex)
{
log4net.Config.XmlConfigurator.Configure();
log.Warn("GetAdStatsService.cs " + ex);
}
//--------------------------------------------------------------------------------------------------------
//Add like/dislike values for certain banners
//--------------------------------------------------------------------------------------------------------
foreach (var element in FullList)
{
foreach (var el in LikeDislike)
{
if (element.name == el.Name)
{
element.Likes = el.Likes;
element.Dislikes = el.Dislikes;
}
}
}
return FullList;
}
}
}
Check FtpWebResponse.StatusCode before calling response.GetResponseStream(). You are probably having come kind of connection error. My guess would be firewall settings on your Azure VM.

Resources