Convert ZipOutputStream to ByteArrayInputStream - compression

I want to compress an InputStream using ZipOutputStream and then get the InputStream from compressed ZipOutputStream without saving file on disc. Is that possible?

I figured it out:
public InputStream getCompressed(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
zos.putNextEntry(new ZipEntry(""));
int count;
byte data[] = new byte[2048];
BufferedInputStream entryStream = new BufferedInputStream(is, 2048);
while ((count = entryStream.read(data, 0, 2048)) != -1) {
zos.write( data, 0, count );
}
entryStream.close();
zos.closeEntry();
zos.close();
return new ByteArrayInputStream(bos.toByteArray());
}

Related

Issues reimplementing some C# encryption stuff in C++ using cryptopp

So I have this piece of C# code:
void Decrypt(Stream input, Stream output, string password, int bufferSize) {
using (var algorithm = Aes.Create()) {
var IV = new byte[16];
input.Read(IV, 0, 16);
algorithm.IV = IV;
var key = new Rfc2898DeriveBytes(password, algorithm.IV, 100);
algorithm.Key = key.GetBytes(16);
using(var decryptor = algorithm.CreateDecryptor())
using(var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read)) {
CopyStream(cryptoStream, output, bufferSize);
}
}
}
and I am trying to translate this into C++ with CryptoPP.
So this is what I have written:
void decrypt(std::ifstream& in_file, std::ofstream& out_file, std::string_view password, size_t bufSize) {
using namespace CryptoPP;
// Get IV
byte iv[16];
in_file.read(reinterpret_cast<char*>(iv), sizeof(iv));
// Read cypher
std::string cypher;
while (in_file && cypher.size() != bufSize) {
char c;
in_file.read(&c, 1);
cypher.push_back(c);
}
// Get key
byte key[16];
PKCS5_PBKDF2_HMAC<SHA1> pbkdf2;
pbkdf2.DeriveKey(key, sizeof(key), 0, reinterpret_cast<const byte*>(password.data()), password.size(), iv, sizeof(iv), 100);
// Decrypt
CTR_Mode<AES>::Decryption decrypt(key, sizeof(key), iv);
std::string output;
StringSource(cypher, true, new StreamTransformationFilter(decrypt, new StringSink(output)));
// Write output to file
out_file.write(output.data(), output.size());
}
However, from this function, I am only getting back trash data. What could I be doing wrong?
Thanks
Tuxifan!
So I found the solution! First of all, as #mbd mentioned, C# uses CBC by default. Additionally, I need to cut away the rest of the data like this:
while ((cipher.size() % 16) != 0) {
cipher.pop_back();
}

how to save pdf with PDFIUM c++

Is there any example that shows how to use FPDF_SaveAsCopy() function for saving PDF document ?
I can't find any examples anywhere !
I'm not familiarized with c++. But I can give you a C# example. So you can get an idea and convert it to c++.
string test_doc = "myTest.pdf";
FPDF_DOCUMENT doc = FPDF_LoadDocument(test_doc, NULL);
var stream = new FileStream(filename, FileMode.Create);
FPDF_SaveAsCopy(doc, stream, 0, 0);
public static bool FPDF_SaveAsCopy(FPDF_DOCUMENT document, Stream stream, SaveFlags flags, int version = 0)
{
byte[] buffer = null;
FPDF_FILEWRITE fileWrite = new FPDF_FILEWRITE((ignore, data, size) =>
{
if (buffer == null || buffer.Length < size)
buffer = new byte[size];
Marshal.Copy(data, buffer, 0, size);
stream.Write(buffer, 0, size);
return true;
});
if (version >= 10)
return FPDF_SaveWithVersion(document, fileWrite, flags, version);
else
return FPDF_SaveAsCopy(document, fileWrite, flags);
}
I hope this will help you any way.

Give a file as input to Pocketsphinx on Android

I am using the latest pocketsphinx android demo (mighty computer),which takes input from microphone. I want to give a wav file as input to the same. I tried using decoder.processrow() function. But I don't know how to configure the decoder using hmm, lm etc.
Code to process files in pocketsphinx-java
Config c = Decoder.defaultConfig();
c.setString("-hmm", "../../model/en-us/en-us");
c.setString("-lm", "../../model/en-us/en-us.lm.dmp");
c.setString("-dict", "../../model/en-us/cmudict-en-us.dict");
Decoder d = new Decoder(c);
URL testwav = new URL("file:../../test/data/goforward.wav");
FileInputStream stream = new FileInputStream(new File(testwav)));
d.startUtt();
byte[] b = new byte[4096];
try {
int nbytes;
while ((nbytes = stream.read(b)) >= 0) {
ByteBuffer bb = ByteBuffer.wrap(b, 0, nbytes);
// Not needed on desktop but required on android
bb.order(ByteOrder.LITTLE_ENDIAN);
short[] s = new short[nbytes/2];
bb.asShortBuffer().get(s);
d.processRaw(s, nbytes/2, false, false);
}
} catch (IOException e) {
fail("Error when reading goforward.wav" + e.getMessage());
}
d.endUtt();
System.out.println(d.hyp().getHypstr());
for (Segment seg : d.seg()) {
System.out.println(seg.getWord());
}
}
Adding to the answer from Nikolay, this is how it can be done on Android, adapting the SpeechRecognizer Android implementation example found here: http://cmusphinx.sourceforge.net/wiki/tutorialandroid
//statically load our library
static {
System.loadLibrary("pocketsphinx_jni");
}
//convert an inputstream to text
private void convertToSpeech(final InputStream stream){
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(WearService.this);
File assetsDir = assets.syncAssets();
Config c = Decoder.defaultConfig();
c.setString("-hmm", new File(assetsDir, "en-us-ptm").getPath());
c.setString("-dict", new File(assetsDir, "cmudict-en-us.dict").getPath());
c.setBoolean("-allphone_ci", true);
c.setString("-lm", new File(assetsDir, "en-phone.dmp").getPath());
Decoder d = new Decoder(c);
d.startUtt();
byte[] b = new byte[4096];
try {
int nbytes;
while ((nbytes = stream.read(b)) >= 0) {
ByteBuffer bb = ByteBuffer.wrap(b, 0, nbytes);
// Not needed on desktop but required on android
bb.order(ByteOrder.LITTLE_ENDIAN);
short[] s = new short[nbytes/2];
bb.asShortBuffer().get(s);
d.processRaw(s, nbytes/2, false, false);
}
} catch (IOException e) {
fail("Error when reading inputstream" + e.getMessage());
}
d.endUtt();
System.out.println(d.hyp().getHypstr());
for (Segment seg : d.seg()) {
//do something with the result here
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

How to convert zip file containing xml into byte array without not using zipfile entries in java

I have a zip file containing xml file generated in Java.And I will send the zip file to Web Service in byte array format.The code snippet to convert zip file into byte array is
public static byte[] FileToArrayOfBytes(ZipFile file) throws IOException {
final Enumeration<? extends ZipEntry> entries = file.entries();
final ZipEntry entry = entries.nextElement();
BufferedInputStream istream = new BufferedInputStream(
file.getInputStream(entry));
int file_size = (int) entry.getCompressedSize();
byte[] blob = new byte[file_size];
int bytes_read = 0;
int offset = 0;
while ((bytes_read = istream.read(blob, 0, file_size)) != -1) {
offset += bytes_read;
}
file.close();
istream.close();
return blob;
}
When I send the byte array returned from above method,web service is returning an error message as 'invalid file extensions'.Normally we know web service accepts zip file.
Can you help me how can I handle the problem ?
I handled the my problem as following
public static byte[] convertFileIntoArrayOfBytes(String zipFilePath) {
FileInputStream fileInputStream = null;
File file = new File(zipFilePath);
byte[] bFile = new byte[(int) file.length()];
try {
// convert file into array of bytes
fileInputStream = new FileInputStream(zipFilePath);
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return bFile;
}

Silverlight 4 image upload problem

I am using Silverlight4 with java webervices in jsp page. I want to save an image to the server so trying to do this with java webservice. I am using below lines of code but output is damaged. I dont understand why. Please help me. This is really important for me. When i try to open 3mb jpeg file contains "Windows Photo Viewer cant open this picture because file appears to be damaged, corrupted or is too large."
Client Side COde
WriteableBitmap wb = new WriteableBitmap(bitmapImage);
byte[] bb = ToByteArray(wb);
public byte[] ToByteArray(WriteableBitmap bmp)
{
int[] p = bmp.Pixels;
int len = p.Length * 4;
byte[] result = new byte[len]; // ARGB
Buffer.BlockCopy(p, 0, result, 0, len);
return result;
}
WebService Code
#WebMethod(operationName = "saveImage")
public Boolean saveImage(#WebParam(name = "img")
byte[] img, #WebParam(name = "path")
String path) {
try{
FileOutputStream fos = new FileOutputStream("C:\\Users\\TheIntersect\\Desktop\\sharp_serializer_dll\\saved.jpg");
fos.write(img);
fos.close();
return true;
}
catch(Exception e){
return false;
}
}
I found my answer on forums.silverlight.net
It is very interesting when i try to call ReadFully(Stream) just after the Stream definition it works but when i call 10 lines of code later it returns all 0.
FUnction
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[input.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Fail Code
using (Stream str = opd.File.OpenRead())
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(str);
image.Tag = bitmapImage.UriSource.ToString();
image.Source = bitmapImage;
image.Width = width;
image.Height = height;
image.Stretch = Stretch.Uniform;
container.Child = image;
rtb.Selection.Insert(container);
ServiceReference1.webWordWebServiceClient s = new ServiceReference1.webWordWebServiceClient();
byte[] bb = ReadFully(str);
s.saveImageCompleted += new EventHandler<ServiceReference1.saveImageCompletedEventArgs>(s_saveImageCompleted);
s.saveImageAsync(bb, "gungorrrr");
}
Successfull Code
using (Stream str = opd.File.OpenRead())
{
byte[] bb = ReadFully(str);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(str);
image.Tag = bitmapImage.UriSource.ToString();
image.Source = bitmapImage;
image.Width = width;
image.Height = height;
image.Stretch = Stretch.Uniform;
container.Child = image;
rtb.Selection.Insert(container);
ServiceReference1.webWordWebServiceClient s = new ServiceReference1.webWordWebServiceClient();
(bitmapImage);
s.saveImageCompleted += new EventHandler<ServiceReference1.saveImageCompletedEventArgs>(s_saveImageCompleted);
s.saveImageAsync(bb, "gungorrrr");
}
Link: http://forums.silverlight.net/forums/p/234126/576070.aspx#576070