Java Apache HttpClient error uploading files with InputStream - http

Am having the same issue with inputstream. Can you please share more details about your fix please.
Thanks,
Harsha
link to your question
Java Apache HttpClient error uploading files

There is another simple way we can override InputStreamBody.getContentLength without a need to create our own ContentBody implementation if you know your contentLength-
InputStreamBody inputStreamBody = new InputStreamBody(inputStream, ContentType.APPLICATION_OCTET_STREAM, fileName){
#Override
public long getContentLength(){return contentLength;}
};
MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("dataAsStream", inputStreamBody)
.build();

The code of the extended org.apache.http.entity.mime.content.InputStreamBody will be something like this. You will need to somehow calculate the correct content length before creating the InputStreamBodyExtended
public class InputStreamBodyExtended extends InputStreamBody {
private long contentLength = -1;
public InputStreamBodyExtended(InputStream in, String filename, long contentLength) {
super(in, filename);
this.contentLength = contentLength;
}
public InputStreamBodyExtended(InputStream in, ContentType contentType, long contentLength) {
super(in, contentType);
this.contentLength = contentLength;
}
public InputStreamBodyExtended(InputStream in, ContentType contentType,
String filename, long contentLength) {
super(in, contentType, filename);
this.contentLength = contentLength;
}
#Override
public long getContentLength() {
return contentLength;
}
}

An other option is org.apache.http.entity.mime.content.ByteArrayBody, if don't know what is the size beforehand (!!! You have to be sure that the content of the inputStream will fit into the memory of JVM):
InputStream inputStream = // get your input stream somehow
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
byte buff[] = new byte[4096];
while( -1 != (i = inputStream.read(buff))){
baos.write(buff, 0, i);
}
ByteArrayBody bab = new ByteArrayBody(baos.toByteArray(), "fileName1");

Here is how I solved it.
public class CustomInputStreamBody extends InputStreamBody {
private InputStream inputStream;
private BufferedReader bufferedReader = null;
StringBuilder stringBuilder = null;
public CustomInputStreamBody(InputStream in,ContentType contentType){
super(in,contentType);
this.inputStream=in;
}
#Override
public long getContentLength() {
int length=0;
byte[] bytes=null;
try {
bytes = IOUtils.readBytesFromStream(inputStream);
// iterate to get the data and append in StringBuilder
System.out.println("___________"+bytes.length);
}catch (IOException ioe){
ioe.printStackTrace();
}
return bytes.length;
}

Related

How to save objects in a proper way with the stream writer?

In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}

Javafx TextArea setText method using text files

Hi I am trying to create a method to be used in the TextArea setText method for javafx.
I am trying to get a method that does this:
public static void setTextArea(String fileName) {
String line;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(fileReader);
while ((line = buffer.readLine()) != null) {
out.println(line);
}
buffer.close();
} catch //etc etc
but I can't use it in the setText method because it is a void method.
Can anyone help translate this method so it could work in the TextArea setText method?
-Thanks!
You just pring out the lines to System.out I guess. You have to add up the content of the text file by doing something like this
public static void setTextArea(String fileName) {
String line;
String content;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(fileReader);
while ((line = buffer.readLine()) != null) {
out.println(line);
content += line;
}
buffer.close();
} catch //etc etc
Then you can either return content or call setText(content) from the TextArea class. If it's a big file, then using StringBuilder would probably be a better idea instead of concatenating each line.
You will have to get the data from the file and and set the data to textArea..
TextArea txtArea = new TextArea();
String data = getDataForTextArea(String fileLocation);
txtArea.setText(data);
public String getDataForTextArea(String fileLocation) {
InputStream inputStream = new FileInputStream(fileLocation);
if (inputStream != null) {
int b;
String txtData = "";
try {
while ((b = inputStream.read()) != -1) {
txtData += (char) b;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
inputStream.close();
}
return txtData;
}
Make sure to check for nullpointerException.

Using my own key in an AES encryption algorithm implementation

I have the following code:
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESHelper {
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
and the main class:
public class MainActivity extends Activity {
String seedValue = "This Is MySecure";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String normalText = "VIJAY";
String normalTextEnc;
try{
normalTextEnc = AESHelper.encrypt(seedValue, normalText);
String normalTextDec = AESHelper.decrypt(seedValue, normalTextEnc);
TextView txe = new TextView(this);
txe.setTextSize(14);
txe.setText("Normal Text ::" + normalText + " \n Encrypted Value :: " + normalTextEnc + " \n Decrypted value :: " + normalTextDec);
setContentView(txe);
}catch(Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
How can I use my own key?
What is the use of a rawKey?
That's the getRawKey function I've been fighting against for as long as I'm on StackOverflow. To use a password, use PBKDF2, it's build into Java. To create a random key, use a random number generator new SecureRandom() and SecretKeySpec.
If your random number generator ever does anything unexpected, e.g. generating a random number instead of acting as a deterministic PRNG your key will not be the same and you may never decrypt your ciphertext again. This actually happened after an update on Android where the default provider was replaced and the RNG differed from the one before.
package com.example.encryption;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESOwnKey {
private Cipher ecipher;
private Cipher dcipher;
AESOwnKey(SecretKey key) {
try {
ecipher = Cipher.getInstance("AES");
dcipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (Exception e) {
System.out.println("Failed in initialization");
}
}
public byte[] encrypt(String str) {
try {
byte[] utf8 = str.getBytes("UTF-8");
byte[] enc = ecipher.doFinal(utf8);
return Base64.getEncoder().encode(enc);
} catch (Exception e) {
System.out.println("Failed in Encryption");
}
return null;
}
public String decrypt(byte[] bytes) {
try {
byte[] dec = Base64.getDecoder().decode(bytes);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF-8");
} catch (Exception e) {
System.out.println("Failed in Decryption");
}
return null;
}
public static void main(String[] args) {
try {
String mykey = "1234567891234567";
SecretKey key = new SecretKeySpec(mykey.getBytes(), "AES");
AESOwnKey encrypter = new AESOwnKey(key);
String original = "Testing encryption";
System.out.println("Before Encryption : " + original);
byte[] encrypted = encrypter.encrypt(original);
System.out.println("After Encryption : " + encrypted);
String decrypted = encrypter.decrypt(encrypted);
System.out.println("After Decryption : " + decrypted);
} catch (Exception e) {
}
}
}

Can't download file. Browser opens it instead.

I have tried a lot of contentTypes and headers I have seen here but still can't figure out what I am doing wrong. I have the following Spring Controller:
#RequestMapping(value = "/anexo/{id}", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<String> getAnexoById(#PathVariable int id, HttpServletResponse response) {
Anexo a = anexoDAO.getAnexo(id);
if (a == null)
return new ResponseEntity<String>(HttpStatusMessage.NOT_FOUND, HttpStatus.NOT_FOUND);
else {
try {
File dir = new File("temp");
if (!dir.exists())
dir.mkdirs();
String filePath = dir.getAbsolutePath() + File.separator + a.getName();
File serverFile = new File(filePath);
FileInputStream fistream = new FileInputStream(serverFile);
org.apache.commons.io.IOUtils.copy(fistream, response.getOutputStream());
response.setHeader("Content-Disposition", "attachment; filename=" + a.getName());
response.setContentType("application/octet-stream");
response.setHeader("Content-Length", String.valueOf(serverFile.length()));
response.setHeader("Content-Transfer-Encoding", "binary");
response.flushBuffer();
System.out.println(response.toString());
return new ResponseEntity<String>(HttpStatus.OK);
} catch (IOException ex) {
return new ResponseEntity<String>("Exception on getting file", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
I also have tried with and without #ResponseBody.
The user will be able to upload any type of file to the server and then he will be able to download through this controller. The problem is that instead of the download window, the browser open the file in the page. How can I make it download?
Thanks in advance
This work for me:
#ResponseBody
void getOne(#PathVariable("id") long id, HttpServletResponse response) throws IOException {
MyFile file = fileRepository.findOne(id);
if(file == null) throw new ResourceNotFoundException();
response.setContentType(file.getContentType());
response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() +"\"");
response.setContentLength(file.getData().length);
FileCopyUtils.copy(file.getData(), response.getOutputStream());
}
Where MyFile is a class like this:
class MyFile {
private Long id;
private String contentType;
private String name;
private bit[] data;
...
}

Write Glassfish output into servlet html page

How to redirect Glassfish server output into HttpServletResponse.out? I am making servlet in NetBeans.
here is a working example, just expose this as a servlet
public class ReadLogs extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.append("<html>\n<head>\n\n");
out.append("<script>function toBottom()" + "{"
+ "window.scrollTo(0, document.body.scrollHeight);" + "}");
out.append("\n</script>");
out.append("\n</head>\n<body onload=\"toBottom();\">\n<pre>\n");
try {
File file = new File("C:\\pathToServerLogFile");
BufferedReader in = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
while (in.ready()) {
String x = in.readLine();
sb.append(x).append("<br/>");
}
in.close();
out.append("\n</pre>\n</body>\n</html>");
out.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
UPDATE
If you need to print only the last portion of the file use this after line "in.close();"
//print only 1MB Oof data
if(sb.length()>1000000){
out.append(sb.substring(sb.length()-1000000, sb.length()));
}else{
out.append(sb.toString());
}
So.. to print only lines which appeared after invoking script I've made such code:
BufferedReader reader = new BufferedReader(new FileReader("/path/to/server/log/server.log"));
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
reader.close();
BufferedReader reader2 = new BufferedReader(new FileReader("/path/to/server/log/server.log"));
String strLine;
int i = 0;
while (i != lines) {
reader2.readLine();
i++;
}
while ((strLine = reader2.readLine()) != null) {
out.println(stringToHTMLString(strLine));
out.println("<br>");
}
reader2.close();
When servlet starts it counts lines in server log (saves it in variable i), then after clicking on action form it read lines which indexes are higher than i and displays it on html page. I've used function stringToHTMLString which I found somewhere on stackoverflow.
Greets.

Resources