Hi I am developing an application to download an attachment from server and read those files using Blackberry 10 Cascades(QNX Momentics IDE) . I have downloaded the attachment but the attachment is a .Zip file. How can I unzip the folder? Does anyone have samples please share?
you can use quazip library for unzipping the archive, here quazip porting for Blackberry 10 cascades
https://github.com/hakimrie/quazip
here sample function to unzip a file using quazip to extract a file into /data/ folder
bool ZipUtils::extractArchive(QString m_filename) {
// check if file exists
QFile file(m_filename);
if (!file.exists()){
qDebug() << "file is not exists gan";
return false;
}
bool result = true;
QuaZip *m_zip = new QuaZip(m_filename);
QString dataFolder = QDir::homePath();
QString bookname = m_filename.split("/").last().split(".").first();
QString dest = dataFolder + "/" + bookname;
QDir dir(dest);
if (!dir.exists()) {
// create destination folder
dir.mkpath(".");
}
qDebug() << "destination folder: " + dest;
m_zip->open(QuaZip::mdUnzip);
if (!m_zip) {
return false;
}
QuaZipFile *currentFile = new QuaZipFile(m_zip);
int entries = m_zip->getEntriesCount();
int current = 0;
for (bool more = m_zip->goToFirstFile(); more; more =
m_zip->goToNextFile()) {
++current;
// if the entry is a path ignore it. Path existence is ensured separately.
if (m_zip->getCurrentFileName().split("/").last() == "")
continue;
QString outfilename = dest + "/" + m_zip->getCurrentFileName();
QFile outputFile(outfilename);
// make sure the output path exists
if (!QDir().mkpath(QFileInfo(outfilename).absolutePath())) {
result = false;
//emit logItem(tr("Creating output path failed"), LOGERROR);
qDebug() << "[ZipUtil] creating output path failed for:"
<< outfilename;
break;
}
if (!outputFile.open(QFile::WriteOnly)) {
result = false;
//emit logItem(tr("Creating output file failed"), LOGERROR);
qDebug() << "[ZipUtil] creating output file failed:" << outfilename;
break;
}
currentFile->open(QIODevice::ReadOnly);
outputFile.write(currentFile->readAll());
if (currentFile->getZipError() != UNZ_OK) {
result = false;
//emit logItem(tr("Error during Zip operation"), LOGERROR);
qDebug() << "[ZipUtil] QuaZip error:" << currentFile->getZipError()
<< "on file" << currentFile->getFileName();
break;
}
currentFile->close();
outputFile.close();
//emit logProgress(current, entries);
}
return result;
}
please make sure to update your pro file to include quazip library (assume your project & quazip project in the same workspace/folder):
INCLUDEPATH += ../src ../../quazip/src/
SOURCES += ../src/*.cpp
HEADERS += ../src/*.hpp ../src/*.h
LIBS += -lbbsystem
LIBS += -lbbdata
LIBS += -lz
lupdate_inclusion {
SOURCES += ../assets/*.qml
}
device {
CONFIG(release, debug|release) {
DESTDIR = o.le-v7
LIBS += -Bstatic -L../../quazip/arm/o.le-v7 -lquazip -Bdynamic
}
CONFIG(debug, debug|release) {
DESTDIR = o.le-v7-g
LIBS += -Bstatic -L../../quazip/arm/o.le-v7-g -lquazip -Bdynamic
}
}
simulator {
CONFIG(release, debug|release) {
DESTDIR = o
LIBS += -Bstatic -L../../quazip/x86/o-g/ -lquazip -Bdynamic
}
CONFIG(debug, debug|release) {
DESTDIR = o-g
LIBS += -Bstatic -L../../quazip/x86/o-g/ -lquazip -Bdynamic
}
}
I used the PKZIP 2.0 compatible archive handler from the OSDaB Project, it does the job quite nicely. They provide Zip and UnZip classes. You also need to include linkage to the installed compression library by adding -lz to the LIBS variable in your .pro file:
LIBS += -lz
Sample code:
UnZip unzip;
UnZip::ErrorCode ec = unzip.openArchive(fileName);
if (ec != UnZip::Ok) {
emit errorString(fileName + " could not open archive.");
} else {
QList<UnZip::ZipEntry> fileNames = unzip.entryList();
ec = unzip.extractAll(dirName);
if (ec != UnZip::Ok) {
emit errorString(
newFileName + " could not extract data to "
+ dirName);
} else {
UnZip::ZipEntry file;
foreach(file, fileNames) {
// do something with file if needed.
}
}
}
Related
I'm running a .NET Core Console Application on CentOS box. The below code is executing for normal command like uptime, but not executing for lz4 -dc --no-sparse vnp.tar.lz4 | tar xf - Logs.pdf:
try
{
var connectionInfo = new ConnectionInfo("server", "username", new PasswordAuthenticationMethod("username", "pwd"));
using (var client = new SshClient(connectionInfo))
{
client.Connect();
Console.WriteLine("Hello World!");
var command = client.CreateCommand("lz4 -dc --no-sparse vnp.tar | tar xf - Logs.pdf");
var result = command.Execute();
Console.WriteLine("yup ! UNIX Commands Executed from C#.net Application");
Console.WriteLine("Response came form UNIX Shell" + result);
client.Disconnect();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Expected output is Logs.pdf file needs to be extracted and saved in the current location. Can someone correct me where im
If application is running on Linux machine then you can try this also:
string command = "write your command here";
string result = "";
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
result += proc.StandardOutput.ReadToEnd();
result += proc.StandardError.ReadToEnd();
proc.WaitForExit();
}
return result;
I want to create a nuget package that contains only what is specified in my nuspec file, but still get the version from my csproj. In order to use the token I have to pack like:
nuget pack MyProj.csproj
But when I do it like this it adds some dependencies and creates an unwanted folder in my nuget package. My nuspec file is:
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata>
<id>Test</id>
<version>$version$</version>
<title>Test</title>
<authors>Test</authors>
<owners>Test</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Test</description>
<summary>Test</summary>
<releaseNotes>Test</releaseNotes>
<copyright>Test</copyright>
</metadata>
<files>
<file src="bin\Debug\*.dll" target="lib\net45" />
<file src="bin\Debug\MyProj.Wpf.exe" target="lib\net45" />
<file src="bin\Debug\MyProj.Wpf.exe.config" target="lib\net45" />
</files>
</package>
When I run the pack command the file it adds extra is the MyProj.Wpf.exe in the target="lib\net452"
Can I force it not to add the dependencies and this extra file? Or to do only what is specified in nuspec?
It's been a while since I posted this question. Since then I used a solution that worked for me, so I'm going to post it here for anyone that needs it.
I created a .csproj that modifies the .nuspec file and sets it's version according to the assembly file of the .csproj. To reduce the manual work I created a .bat file that called this .exe with arguments and finished creating the installer. I used Squirrel.Windows for the installer creation.
I created a NuspectVersionSetter.csproj to set the nuspec version. There are many ways to implement this, here goes a simple one:
static void Main(string[] args)
{
try
{
if (args.Length < 2)
{
throw new Exception("Args are not correct");
}
var assemblyFilePath = args[0];
var nuspecFilePath = args[1];
IsFileValid(assemblyFilePath, ".cs");
IsFileValid(nuspecFilePath, ".nuspec");
var version = GetAssemblyVersion(assemblyFilePath);
if (string.IsNullOrEmpty(version))
{
throw new Exception("Unable to get version");
}
WriteNuspec(nuspecFilePath, version);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
static void WriteNuspec(string path, string version)
{
var lines = File.ReadAllLines(path);
string versionLine = null;
for(var i = 0; i < lines.Length; ++i)
{
var line = lines[i];
if (line.Contains("<version>") && line.Contains("</version>"))
{
var init = line.IndexOf("<version>") + "<version>".Length;
var end = line.IndexOf("</version>");
line = line.Remove(init, end - init);
lines[i] = line.Insert(init, version);
break;
}
}
File.WriteAllLines(path, lines);
}
static void IsFileValid(string file, string extension)
{
if (!File.Exists(file))
{
throw new Exception("Invalid file path: " + file);
}
if (!file.EndsWith(extension))
{
throw new Exception("Invalid file extension: " + file);
}
}
static string GetAssemblyVersion(string path)
{
var lines = File.ReadAllLines(path);
foreach(var line in lines)
{
if(line.Contains("AssemblyVersion") && !line.Contains(".*"))
{
var parts = line.Split('\"');
if (parts.Length != 3)
{
break;
}
return parts[1];
}
}
foreach (var line in lines)
{
if (line.Contains("AssemblyFileVersion") && !line.Contains(".*"))
{
var parts = line.Split('\"');
if (parts.Length != 3)
{
break;
}
return parts[1];
}
}
foreach (var line in lines)
{
if (line.Contains("AssemblyInformationalVersion") && !line.Contains(".*"))
{
var parts = line.Split('\"');
if (parts.Length != 3)
{
break;
}
return parts[1];
}
}
throw new Exception("Unable to get version");
}
As explained before the .bat file also wrapped the Squirrel.Windows installer creation.
Small observations about the .bat:
NuspecVersionSetter was the .exe created from the .csproj above
This example assumes your NuspecVersionSetter.exe is inside a folder in your .csproj, therefore some paths may need to be adjusted
The Squirrel.Windows version is old in this example, you many need to change it
The .bat file I used was the following:
NuspecVersionSetter ../Properties/AssemblyInfo.cs mynuspec.nuspec
nuget pack
#echo off
setlocal EnableDelayedExpansion
for /f "tokens=*" %%G in ('dir *.nupkg /b /a-d /od') do (
SET newest=%%G
)
"../../packages/squirrel.windows.1.2.1/tools/Squirrel" --releasify !newest! -g installing.gif
If there are any questions about this answer, ask them in the comments.
void main( )
{
char filename[] = "dns.pcap";
nids_params.filename = filename ;
nids_params.device = NULL;
if (!nids_init())
{
printf("%s\n", nids_errbuf);
exit(1);
}
nids_register_udp(udp_callback);
nids_run();
}
My application need to read local pcap file for debuging more easily. My code is wrong , it still read data from eth0.How to read pcapfile using libnids?
I am trying to download a pdf file on my mobile (using Java ME) using SocketConnection Api. The idea is to send the server a HTTP GET request, and it replies back with the data for pdf file. However, the problem I am facing is that the server initially replies back with string data (the HTTP Headers), and then the binary data. I just want to store the binary data (the pdf file).
I have written this code so far, and it works perfectly fine as far as the server replies back with string data. However, when it replies back with binary data, this code still tries to store everything as string, correctly storing the initially returned HTTP Headers (not required) and then garbled bits corresponding to the binary data of my PDF file.
public void FileDownload() {
try {
sc = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
OutputStream os = sc.openOutputStream();
os.write(("GET " + link_to_file_to_be_downloaded + " HTTP/1.0\r\n").getBytes("UTF-8"));
os.write(("HOST: " + hostname + "\r\n").getBytes("UTF-8"));
os.write(("\r\n").getBytes("UTF-8"));
os.flush();
os.close();
String url = "file:///E:/Data/" + "binary_data.pdf";
FileConnection fconn = (FileConnection) Connector.open(url, Connector.READ_WRITE);
if (!fconn.exists()) {
fconn.create();
}
OutputStream ops = fconn.openOutputStream();
byte data = 0;
in = sc.openInputStream();
data = (byte) in.read();
while (data != -1) {
ops.write(data);
data = (byte) in.read();
}
ops.flush();
ops.close();
fconn.close();
} catch (IOException ex) {
parent_class.main_form.append("Exception occured while "
+ "downloading file: " + ex.toString() + "\n");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
parent_class.main_form.append("Exception occured while "
+ "downloading file: " + ex.toString() + "\n");
}
}
}
}
This is what gets stored in the file "binary_data.pdf" using this code -
HTTP/1.1 200 OK
Date: Sun, 25 Mar 2012 07:03:10 GMT
Server: Apache/2.2.14 (Ubuntu)
Last-Modified: Tue, 20 Mar 2012 22:00:45 GMT
ETag: "420050-12bad-4bbb3ce85fd21"
Accept-Ranges: bytes
Content-Length: 76717
Content-Type: application/pdf
Via: 1.0 www.XXX.XXX.org
Connection: close
%PDF-1.4
%????
3 0 obj <<
/Length 4077
/Filter /FlateDecode
>>
stream
x??ZYs?6~????9U.?#??Udg?M*qYJ???T-4?fq? #Z????<FT?}
lt7??n???_???4?s???????"
3????<???^?V?z??M?z??m?^????V???o??S'm6?????.??/Sx??Y?av?MB?*b^?f??/?IO??B??q??/?(??aT?a?##??,?%???Z8? ?]??-?\?]??????nw?2?;?????Z?;?[}??????&J=ml??-??V?|??:??"?(?Gf??D??~?QW?U?Z???cP?b???QX
(This operation might be simpler using the high level HttpConnection api, but I wish to understand how everything works at the most basic level, and hence I am using the SocketConnection api instead.)
In short, what I wish my app to do is simply interpret the data replied by the server correctly, either as string or binary, and then accordingly store the binary file (possibly discarding the string HTTP headers).
I found the solution. Below is the working code.
I am first storing the header response as a string. Headers are terminated by \r\n\r\n, (so, read in bytes upto these characters). Later am storing the (possibly) binary data in a file separately.
public String FileDownloadNonPersistently() {
String server_reply = new String();
try {
sc = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
os = sc.openOutputStream();
os.write(("GET " + link_to_file_to_be_downloaded +
" HTTP/1.0\r\n").getBytes("UTF-8"));
os.write(("HOST: " + hostname + "\r\n").getBytes("UTF-8"));
os.write(("\r\n").getBytes("UTF-8"));
os.flush();
os.close();
in = sc.openInputStream();
// 1. Read the response header from server separately beforehand.
byte data;
String temp_char = "";
while (!"\r\n\r\n".equals(temp_char)) {
data = (byte) in.read();
server_reply += String.valueOf((char) data);
if (((char) data) == '\r' || ((char) data) == '\n') {
temp_char += String.valueOf((char) data);
} else {
temp_char = "";
}
}
// 2. Recieving the actual data, be it text or binary
current = 0;
mybytearray = new byte[filesize];
bytesRead = in.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead = in.read(mybytearray, current,
(mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
// Store recieved data to file, if set true from options
if (tcp_save_downloaded_file == true) {
// decide an appropriate file name acc. to download link
String url = "file:///E:/Data/" + "tcp_downloaded_file.pdf";
FileConnection fconn = (FileConnection)
Connector.open(url, Connector.READ_WRITE);
if (!fconn.exists()) { // XXX. what if file already present? overwrite or append mode?
fconn.create();
}
OutputStream ops = fconn.openOutputStream();
ops.write(mybytearray, 0 , current);
ops.flush();
ops.close();
}
} catch (Exception ex) {
parent_class.main_form.append("Exception occured while "
+ "downloading file: " + ex.toString() + "\n\n");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
parent_class.main_form.append("Exception occured while "
+ "closing inputstream "
+ "after downloading file: " + ex.toString() + "\n\n");
}
}
// XXX. see if you need to close the OutputStreams and
// SocketConnection as well.
return server_reply;
}
}
The first 10 lines are the HTTP message headers. For more information on them please go to https://www.rfc-editor.org/rfc/rfc2616#page-31.
The blank line identifies where the body starts.
You can start saving the pdf content from line 12 onwards, but you should do it using a different read method.
Instead of
data = (byte) in.read();
while (data != -1) {
ops.write(data);
data = (byte) in.read();
}
please try
byte buff[] = new byte[1024];
int len = in.read(buff);
while (len > 0) {
ops.write(buff, 0, len);
len = in.read(buff);
}
I'm creating my first gradle plugin. I'm trying to copy a file from the distribution jar into a directory I've created at the project. Although the file exists inside the jar, I can't copy it to the directory.
This is my task code:
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
class InitTask extends DefaultTask {
File baseDir;
private void copyEnvironment(File environments) {
String resource = getClass().getResource("/environments/development.properties").getFile();
File input = new File(resource);
File output = new File(environments, "development.properties");
try {
copyFile(input, output);
}
catch (IOException e) {
e.printStackTrace();
}
}
void copyFile(File sourceFile, File destFile) {
destFile << sourceFile.text
}
#TaskAction
void createDirectories() {
logger.info "Creating directory."
File environments = new File(baseDir, "environments");
File scripts = new File(baseDir, "scripts");
File drivers = new File(baseDir, "drivers");
[environments, scripts, drivers].each {
it.mkdirs();
}
copyEnvironment(environments);
logger.info "Directory created at '${baseDir.absolutePath}'."
}
}
And this is the error I'm getting:
:init
java.io.FileNotFoundException: file:/path-to-jar/MyJar.jar!/environments/development.properties (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at groovy.util.CharsetToolkit.<init>(CharsetToolkit.java:69)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.newReader(DefaultGroovyMethods.java:15706)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.getText(DefaultGroovyMethods.java:14754)
at org.codehaus.groovy.runtime.dgm$352.doMethodInvoke(Unknown Source)
at org.codehaus.groovy.reflection.GeneratedMetaMethod$Proxy.doMethodInvoke(GeneratedMetaMethod.java:70)
at groovy.lang.MetaClassImpl$GetBeanMethodMetaProperty.getProperty(MetaClassImpl.java:3465)
at org.codehaus.groovy.runtime.callsite.GetEffectivePojoPropertySite.getProperty(GetEffectivePojoPropertySite.java:61)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
at br.com.smartcoders.migration.tasks.InitTask.copyFile(InitTask.groovy:29)
Just to emphasize, the development.properties is inside the environments directory inside the MyJar.jar
getClass().getResource() returns a URL. To access that URL, you'll have to read it directly (e.g. with url.text) rather than first converting it to a String/File. Or you can use getClass().getResourceAsStream().text, which is probably more accurate. In both cases you can optionally specify the file encoding.
Kotlin DSL answer!
For cases like this it is good to have extensions:
fun Any.getResource(filename: String): File? {
val input = this::class.java.classLoader.getResourceAsStream(filename) ?: return null
val tempFile = File.createTempFile(
filename.substringBeforeLast('.'),
"." + filename.substringAfterLast('.')
)
tempFile.deleteOnExit()
tempFile.writer().use { output ->
input.bufferedReader().use { input ->
output.write(input.readText())
}
}
return tempFile
}