The following code fails to compile with message: cannot instantiate type SymmetricKey SymmetricKey is
an interface. How do I fix this?
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InitializationVector iv = new InitializationVector("helo".getBytes());
SymmetricKey key = new SymmetricKey("AES_256","key", 0, "key".length());
OutputStream os = EncryptorFactory.getEncryptorOutputStream(key, baos, "AES/CBC/PKCS5",);
os.write("somedata".getBytes());
byte[] encryptedData = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(encryptedData);
InputStream is = DecryptorFactory.getDecryptorInputStream(key, bais, "AES/CBC/PKCS5", iv);
I solved my problem by using SymmetricKeyFactory
SymmetricKey key=
SymmetricKeyFactory.getInstance("AES_256","key".getBytes(), 0, "abc123".length());
Related
I am trying to use avro serialization but when I have multiple records to serialize, the application hangs on DataFileWriter close method, however it works with a small amount of records.
final PipedOutputStream pipedOutputStream = new PipedOutputStream();
PipedInputStream pipedInputStream = new PipedInputStream(
pipedOutputStream);
DatumWriter<DW> userDatumWriter = new SpecificDatumWriter<DW>(DW.class);
DataFileWriter<DW> dataFileWriter = new DataFileWriter<DW>(
userDatumWriter);
dataFileWriter.create(payload.get(0).getSchema(), pipedOutputStream);
for (DW currentRecord : payload) {
dataFileWriter.append(currentRecord);
}
dataFileWriter.close();
return pipedInputStream;
I tried to flush after adding 10 records at a time, but then it hangs on the flush method.
Can anyone help me with this?
Solved by returning a ByteArrayOutputStream as follows:
Schema schema = ReflectData.get().getSchema(DW.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ReflectDatumWriter<Object> reflectDatumWriter = new ReflectDatumWriter<Object>(
schema);
DataFileWriter<Object> writer = new DataFileWriter<Object>(
reflectDatumWriter).create(schema, outputStream);
for (DW currentRecord : payload) {
writer.append(currentRecord);
}
writer.close();
return outputStream.toByteArray();
I am developing an app for iOS using Xamarin iOS & MonoGame. I want to use Parse's push notifications through their REST API, so first I must create an installation object:
var bundle = new Dictionary<string, object>();
bundle.Add("channels", "");
bundle.Add("deviceType", "ios");
bundle.Add("deviceToken", _deviceToken);
string urlpath = "https://api.parse.com/1/installations";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlpath);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("X-Parse-Application-Id", _parseAppID);
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", _parseRestAPIKey);
httpWebRequest.Method = "POST";
string bundleString = bundle.ToJson();
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(bundleString);
string result = Convert.ToBase64String(buffer);
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(result, 0, result.Length);
requestWriter.Close();
WebResponse httpResponse = await httpWebRequest.GetResponseAsync();
Stream stream = httpResponse.GetResponseStream();
string json = string.Empty;
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
json += reader.ReadLine();
}
}
JsonObject jsonObject = JsonObject.Parse(json);
_varStorage.Save("ObjectId", jsonObject.Get<string>("objectId"));
The bundleString value is:
"{\"channels\":\"\",\"deviceType\":\"ios\",\"deviceToken\":\"46becd0a165be042eeab5a1ec96b8858065cbea7311479da16c0fd1c9428e2eb\"}"
This code raises a System.Net.WebExceptionStatus.ProtocolError error 400 "Bad Request", and I can't see why.
Channels is supposed to be an array of strings according to the documentation, https://www.parse.com/docs/rest#installations
bundle.Add("channels", new [] { "" });
After more trail and error, I found that replacing this
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(bundleString);
string result = Convert.ToBase64String(buffer);
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(result, 0, result.Length);
requestWriter.Flush();
requestWriter.Close();
with this
httpWebRequest.ContentLength = bundleString.Length;
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(bundleString);
requestWriter.Flush();
requestWriter.Close();
fixed the problem, I don't know exactly why though.
should you not be calling flush before closing your stream ?
requestWriter.Write(result, 0, result.Length);
requestWriter.Close();
I am trying to upload file to server and for that I try so many different codes but I can't get success.
In this code connection is created successfully, but at the time of reading file and posting data to server by creating header...
class ConnectionThread extends Thread
{
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String boundary = "*****";
String lineEnd = "\r\n";
String twoHyphens = "--";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 2*1024*1024;
DataInputStream fileInputStream = null;
public void run()
{
try {
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://www.myserver/upload.php");
if (connDesc != null)
{
HttpConnection conn;
conn = (HttpConnection)connDesc.getConnection();
conn.setRequestMethod(conn.POST);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( conn.openDataOutputStream() );
outputStream.writeChars(twoHyphens + boundary + lineEnd);
outputStream.writeChars("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + "files:///SDCard/bb.txt" +"\"" + lineEnd);
outputStream.writeChars(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
FileConnection fis=(FileConnection)Connector.open("file:///SDCard/bb.txt");
InputStream inputStream = fis.openInputStream();
ByteArrayOutputStream bos=new ByteArrayOutputStream();
int buffersize=1024*1024;
byte[] buffer=new byte[buffersize];
int length=0;
while((length=inputStream.read(buffer))!=-1)
{
bos.write(buffer,0,length);
}
byte[] imagedata=bos.toByteArray();
outputStream.write(imagedata);
outputStream.writeChars(lineEnd);
outputStream.writeChars(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = conn.getResponseCode();
final String serverResponseMessage = conn.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
}
catch (Exception e) {
}
}
plz somebody help... thanks in advance..
Try This link,
This code is support to upload file on Server using multi part .
it can also work on blackberry , With some modifications needed.
http://www.developer.nokia.com/Community/Wiki/HTTP_Post_multipart_file_upload_in_Java_ME
I am needing to upload a posted file to an FTP file location in my controller.
Here is what I have now.
public ActionResult Upload(HttpPostedFileBase file)
{
string fileName = System.IO.Path.GetFileName(file.FileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://10.10.0.3"+"/"+fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
StreamReader streamReader = new StreamReader(file.InputStream);
byte[] fileContents = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());
streamReader.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
.....
}
The file is being uploaded, it has the correct number of pages, however there is no text in the new file. (these are pdfs, I will do validation on the type later, just trying to get it to work now).
Thanks!
You are reading PDF file as if they were text files. Instead try this.
var sourceStream = file.InputStream;
requestStream = request.GetRequestStream();
request.ContentLength = sourceStream.Length;
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = sourceStream.Read(buffer, 0, BUFFER_SIZE);
do
{
requestStream.Write(buffer, 0, bytesRead);
bytesRead = sourceStream.Read(buffer, 0, BUFFER_SIZE);
} while (bytesRead > 0);
sourceStream.Close();
requestStream.Close();
response = (FtpWebResponse)request.GetResponse();
I want to send data to the server by using URLEncodedPost Class.
I am getting error while i am trying to call the POST method. so if anybody have any idea about this method then give me some hint about it.
enter code here
You are not posted any code to know which error you are getting any way, the following code is an example of Http Post method
HttpConnection connection = (HttpConnection) Connector.open("url", Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
encPostData.append("username","your username");
encPostData.append("password","ur password");
byte[] postData = encPostData.toString().getBytes("UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(postData.length));
OutputStream os = connection.openOutputStream();
os.write(postData);
os.flush();
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
System.out.println("Unexpected response code: "+ responseCode);
connection.close();
return;
}
String contentType = connection.getHeaderField("Content-type");
baos = new ByteArrayOutputStream();
InputStream responseData = connection.openInputStream();
byte[] buffer = new byte[10000];
int bytesRead = responseData.read(buffer);
while (bytesRead > 0)
{
baos.write(buffer, 0, bytesRead);
bytesRead = responseData.read(buffer);
}
baos.close();
connection.close();
System.out.println("Server response"+new String(baos.toByteArray()));