I have HttpServletRequest req and HttpServletResponse res wont to use req and res variables in another place in code.
and I have another problem in if statement when I was pass function in compression
here my code
#WebServlet(name = "NaiveBayesExample", urlPatterns = {"/NaiveBayesExample"})
public class NaiveBayesExample extends HttpServlet {
String param="";
public static String[] readLines(URL url) throws IOException {
Reader fileReader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8"));
List<String> lines;
try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
lines = new ArrayList<>();
String line;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
}
return lines.toArray(new String[lines.size()]);
}
public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
param =req.getParameter("a");
pw.print("<br> <font color=blue size=5>POST METHOD</font>");
pw.print("Param is "+ param);
}
protected void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
param =req.getParameter("a");
pw.print("Param is "+ param);
}
public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws IOException {
PrintWriter out = res.getWriter();
res.setContentType("text/plain");
String paramName = "param name";
String paramValue = req.getParameter(paramName);
out.write(paramName + " = ");
out.write(paramValue);
paramName = "UNKNOWN";
paramValue = req.getParameter(paramName);
if (paramValue==null) {
out.write("Parameter " + paramName + " not found");
}
out.close();
}
public static void main(String[] args) throws IOException {
//map of dataset files
Map<String, URL> trainingFiles = new HashMap<>();
trainingFiles.put("Paaass Request", NaiveBayesExample.class.getResource("/datasets/training.normaltraffic.nt.txt"));
trainingFiles.put("Sql Injectionnn Request", NaiveBayesExample.class.getResource("/datasets/training.sqlinjection.si.txt"));
//loading examples in memory
Map<String, String[]> trainingExamples = new HashMap<>();
for(Map.Entry<String, URL> entry : trainingFiles.entrySet()) {
trainingExamples.put(entry.getKey(), readLines(entry.getValue()));
}
//train classifier
NaiveBayes nb = new NaiveBayes();
nb.setChisquareCriticalValue(6.63); //0.01 pvalue
nb.train(trainingExamples);
//get trained classifier knowledgeBase
NaiveBayesKnowledgeBase knowledgeBase = nb.getKnowledgeBase();
nb = null;
trainingExamples = null;
//Use classifier
nb = new NaiveBayes(knowledgeBase);
// String PassTraffic = "http://www.testsite.com/catigories/index.php=1";
String output = nb.predict(req.getParameter("a"));
if (output!=trainingFiles.put("Pass", NaiveBayesExample.class.getResource("/datasets/training.normaltraffic.nt.txt")))
{
res.sendRedirect("SecondServlet");
}
else
{
}
// System.out.format("The Traffic \"%s\" was classified as \"%s\".%n", PassTraffic, outputpass);
//
String output2 = nb.predict(req.getParameter("a"));
if (output2!=trainingFiles.put("stop", NaiveBayesExample.class.getResource("/datasets/training.sqlinjection.si.txt")))
{
res.sendRedirect("SecondServlet");
}
else
{
} }
}
in if statement compiler said incomparable type: String and URL and res and req not accessible to get parameters
DonĀ“t compare strings with == or != only with the equals function.
And you must caste the URL to a string, after that you can only compare this two.
For example
if (output.equals(trainingFiles.put("Pass", NaiveBayesExample.class.getResource("/datasets/training.normaltraffic.nt.txt")).toString())) {
res.sendRedirect("SecondServlet");
}
Related
This question already has answers here:
How to use java.net.URLConnection to fire and handle HTTP requests
(12 answers)
Making http calls from swing application to a servlet, session not saved
(1 answer)
Closed 1 year ago.
Server-side I have an HttpSession object. Each time the client starts the connection to the Servlet, the session changes.
Here I have a simplified version of my Servlet code:
//import ...
#WebServlet(name = "ServletController", urlPatterns = {"/ServletController"})
public class ServletController extends HttpServlet {
public void init(ServletConfig conf) {
//...
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//...
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
HttpSession s = request.getSession();
PrintWriter out = response.getWriter();
try {
String action = request.getParameter("action");
switch (action) {
case "login":
s.setAttribute("account", "John");
out.println("Logged in successfully. Session: " + s);
out.flush();
break;
case "account":
String account = (String) s.getAttribute("account");
out.println(account + ". Session: " + s);
out.flush();
break;
default:
break;
}
} catch (Exception x) {
System.out.println(x);
}
}
}
And here the simplified Android one:
//import ...
public class Operation {
public static Executor e = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
Button login_btn = findViewById(R.id.login);
Button account_btn = findViewById(R.id.account);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
e.execute(() -> {
String login = Operation.operation("?action=login");
});
}
});
account_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
e.execute(() -> {
String account = Operation.operation("?action=account");
});
}
});
System.out.println(login);
System.out.println(account);
}
public static String operation(String urlParameters) {
HttpURLConnection conn = null;
try {
System.out.println(urlParameters);
URL url = new URL("http://10.0.2.2:8080/progettoTweb/ServletController" + urlParameters);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(1000);
conn.setConnectTimeout(1500);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
return readIt(conn.getInputStream());
} catch (Exception ex) {
System.out.println(ex);
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
//building the output as a String
private static String readIt(InputStream stream) throws IOException, UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line).append("\n");
}
return result.toString();
}
}
As the System.out.println in the Android app show, I obtain a different session for each Operation.operation call I make.
In the original code I use SharedPreferences in order to save my data, but it does not solve the problem since I do not know how to use the session, gained from the interaction with the server-side, to obtain the required values.
Indeed, in the Servlet code I use s.getAttribute() but, since it creates a new HttpSession object each time, It cannot give back the requested values.
I am wrting a code to send email from mulitple sender to one recepient in a continuous loop. I have to read senders emailID from csv file for that I have written a code for raeding as follows:
public class ReadFile {
CsvReader senders;
public CsvReader read(){
try {
senders = new CsvReader("C:/Users/D/Documents/Senderlist.csv");
senders.readHeaders();
while (senders.readRecord())
{
String SenderID = senders.get("SenderID");
String ReceiverID = senders.get("ReceiverID");
// perform program logic here
System.out.println(SenderID + " : " + ReceiverID);
}
senders.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> al=new ArrayList<String>();
al.add("senders");
//traversing list through iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
return senders;
}
}
Now how do I call this method in my servlet to read and send emails in continuous loop, servlet is as follows:
public class MailController extends HttpServlet {
private static final long serialVersionUID = 1L;
private String ExchangeIP;
private String port;
public MailController() {
super();
// TODO Auto-generated constructor stub
}
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
ExchangeIP = context.getInitParameter("ExchangeIP");
port = context.getInitParameter("port");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// read from field
List<File> uploadedFiles= saveUploadedFiles(request);
String sender=request.getParameter("sender");// reading from the form page
String recipient=request.getParameter("recipient");
String subject=request.getParameter("subject");
String content=request.getParameter("content");
String resultMessage = "";
try {
EmailUtility.sendEmail(ExchangeIP, port,user, recipient, subject, content, uploadedFiles);
resultMessage = "The e-mail has been sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
//deleteUploadFiles(uploadedFiles);
request.setAttribute("Message", resultMessage);
getServletContext().getRequestDispatcher("/Result.jsp").forward(request, response);
}
}
If you have class name, ReadFile
public class ReadFile {
public static ReadFile thisCls;
private String filename = "C:/Users/D/Documents/Senderlist.csv";
public static ReadFile getSenderClass()
{
if(thisCls == null) thisCls = new ReadFile();
return thisCls;
}
private CSVRead() {}
public List<String []> readCsv() {
try {
CSVReader reader = new CSVReader(new FileReader(filename));
// UTF-8
// CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"), ",", '"', 1);
String[] s;
while ((s = reader.readNext()) != null)
{
data.add(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
Then, Your servlet class might be
public class MailController extends HttpServlet {
.....skip code....
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// read from field
List<File> uploadedFiles= saveUploadedFiles(request);
String sender=request.getParameter("sender");// reading from the form page
String recipient=request.getParameter("recipient");
String subject=request.getParameter("subject");
String content=request.getParameter("content");
//String resultMessage = "";
List<String> resultMessage = new ArrayList<String>();
//<==============================
CSVRead read = new CSVRead();
List<String[]> data = CSVRead.readCsv();
//assuming you have a sender in a second column value
Iterator<String[]> it = data.iterator();
String targetSender = null;
try {
String[] array = (String[]) it.next();
targetSender = array[1];
EmailUtility.sendEmail(ExchangeIP, port,sender, recipient, subject, content, uploadedFiles);
resultMessage.add("The e-mail has been sent successfully to " + targetSender);
} catch (Exception ex) {
ex.printStackTrace();
resultMessage.add("There were an error: " + ex.getMessage() + " while sending user " + targetSender);
}
try{
while (it.hasNext()) {
try {
String[] array = (String[]) it.next();
targetSender = array[1];
EmailUtility.sendEmail(ExchangeIP, port,targetSender, recipient, subject, content, uploadedFiles);
resultMessage.add("The e-mail has been sent successfully to " + targetSender);
} catch (Exception ex) {
ex.printStackTrace();
resultMessage.add("There were an error: " + ex.getMessage() + " while sending user " + targetSender);
}
}
} finally {
//deleteUploadFiles(uploadedFiles);
request.setAttribute("Message", resultMessage);
getServletContext().getRequestDispatcher("/Result.jsp").forward(request, response);
}
}
}
I don't know about the sendEmail method of EmailUtility class.
I assume that the 3rd parameter must be a sender.
If your only concern is to read the CSV file and iterate the items you read from that file in Servlet then why dont you simply call the read() method in the servlet ? And change the read() method like this
public List<String> getSenderEmails() {
CsvReader senders = new CsvReader("C:/Users/D/Documents/Senderlist.csv");
senders.readHeaders();
List<String> senderEmails = new ArrayList<>();
while (senders.readRecord()) {
String senderID = senders.get("SenderID");
String receiverID = senders.get("ReceiverID");
// perform program logic here
System.out.println(senderID + " : " + receiverID);
senderEmails.add(senderID);
}
return senderEmails;
}
NB:
I dont know whats your CsvReader is doing. But assuming here it is kind of a library or Util calss. So necessary Exception handeling is required.
But the main idea I am suggesting is instead of returning CsvReader or something like that just return the list of email address you are just concern about.
Next thing is you can call the getSenderEmails() from servlet and iterate over it to send emails
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// read from field
List<File> uploadedFiles = saveUploadedFiles(request);
String sender = request.getParameter("sender");// reading from the form page
String recipient = request.getParameter("recipient");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
String resultMessage = "";
try {
List<String> senderEmails = ReadFile.getSenderEmails();
for (String user : senderEmails) {
EmailUtility.sendEmail(ExchangeIP, port, user, recipient, subject, content, uploadedFiles);
}
resultMessage = "The e-mail has been sent successfully";
} catch (Exception ex) {
} finally {
}
}
I had just changed My IDE from Eclipse To Idea 14 ,and find a log loop problem.
I can't post image,here is the link:
http://img.rehulu.com/idea.png
Just like the picture,keep looping about half a second and there is no income request.
The same code in Eclipse is OK.
web.xml
<filter>
<filter-name>loggingFilter</filter-name>
<filter-class>com.rehulu.coreapi.service.impl.LoggingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loggingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
LoggingFilter.class
public class LoggingFilter extends OncePerRequestFilter {
protected static final Logger logger = Logger.getLogger(LoggingFilter.class);
private AtomicLong id = new AtomicLong(1);
private static final String REQUEST_PREFIX = "Req:%s sId:%s Ip:%s Method:%s Uri:%s Parameter:%s";
private static final String RESPONSE_PREFIX = "Resp:";
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
long requestId = id.incrementAndGet();
request = new RequestWrapper(requestId, request);
response = new ResponseWrapper(requestId, response);
try {
filterChain.doFilter(request, response);
} finally {
logRequest(request);
logResponse((ResponseWrapper) response);
}
}
private void logRequest(final HttpServletRequest request) {
StringBuilder msg = new StringBuilder();
msg.append(REQUEST_PREFIX);
HttpSession session = request.getSession(false);
String id = "";
if (session != null) {
id = session.getId();
}
String uri = request.getRequestURI();
String method = request.getMethod();
String parameter = "";
if (request instanceof HttpServletRequest && !isMultipart(request)) {
HttpServletRequest requestWrapper = (HttpServletRequest) request;
Map<String, String[]> parameters = requestWrapper.getParameterMap();
for (Entry<String, String[]> entry : parameters.entrySet()) {
String[] value = entry.getValue();
String keyV = "";
if (value == null || value.length == 0) {
continue;
} else {
if (value.length == 1) {
keyV = value[0];
} else {
keyV = Arrays.toString(value);
}
}
parameter += "{" + entry.getKey() + ":" + keyV + "}";
}
}
logger.info(String.format(REQUEST_PREFIX, String.valueOf(((RequestWrapper) request).getId()), id,
IPUtil.getClientIP(request), method, uri, parameter));
}
private boolean isMultipart(final HttpServletRequest request) {
return request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
}
private void logResponse(final ResponseWrapper response) {
StringBuilder msg = new StringBuilder();
msg.append(RESPONSE_PREFIX).append((response.getId()));
try {
String contentType = response.getContentType();
if (contentType != null && contentType.contains("json")) {
msg.append(" Payload:").append(new String(response.toByteArray(), response.getCharacterEncoding()));
} else {
msg.append(" Content-Type:").append(contentType);
}
} catch (UnsupportedEncodingException e) {
logger.warn("Failed to parse response payload", e);
}
logger.info(msg.toString());
}
}
Thanks very much !!!
I have this servlet to handle uploaded file and to store them on server.
public class ImageService extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final long MAX_FILE_SIZE = 1024 * 1024 * 1024; // 1GB
#Override
protected void doPost(final HttpServletRequest request,
final HttpServletResponse response) {
slog("SERVLET STARTED");
List<String> files = new ArrayList<String>();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
slog("REQUEST IS MULTIPART");
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
slog("TROVATO FILE " + item.getName());
String root = getServletContext().getRealPath("/");
File path = new File(root + "/fileuploads");
slog("SALVO FILE IN " + path.getAbsolutePath());
if (!path.exists()) {
path.mkdirs();
}
File uploadedFile = creaFileNonAmbiguo(path, fileName);
slog("NOME ASSEGNATO AL FILE " + uploadedFile.getName());
item.write(uploadedFile);
response.getWriter()
.write(uploadedFile.getName() + ";");
files.add(uploadedFile.getName());
}
}
response.getWriter().flush();
slog("RISPOSTA INVIATA");
} catch (Exception e) {
e.printStackTrace();
}
} else {
slog("LA RICHIESTA NON E' MULTIPART");
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
slog("SERVLET TERMINATA");
}
#Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) {
response.setContentType("image/jpeg");
String root = getServletContext().getRealPath("/").concat(
"fileuploads/");
String path = root.concat(request.getParameter("src"));
File file = new File(path);
response.setContentLength((int) file.length());
FileInputStream in;
try {
in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) >= 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private File creaFileNonAmbiguo(File path, String fileName) {
File res = new File(path + "/" + fileName);
if (!res.exists())
return res;
else {
return creaFileNonAmbiguo(path, "c".concat(fileName));
}
}
private void slog(String s) {
System.out.println("UPLOAD SERVLET: " + s);
}
}
As you can see the servlet has doPost and doGet. doGet() is correctly called in this part of my code:
[...]
String path = GWT.getModuleBaseURL() + "imageUpload?src=";
for (String foto : result) {
String url = path.concat(foto);
[...]
But the doPost method is never called, as I can see from the Chrome debugger and from the fact that SERVLET STARTED is never logged.
This is the way I call the doPost() method from client:
inserisciSegnalazioneBtn.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
if (!catLst.isEnabled()
|| catLst.getItemText(catLst.getSelectedIndex())
.equals("")
|| catLst.getItemText(catLst.getSelectedIndex())
.equals("")
|| descrizioneBox.getText().equals("")
|| gsb.getText().equals("")) {
Window.alert("ATTENZIONE: devi riempire tutti i campi");
return;
}
segnalazione.setCategoria(new Categoria(catLst.getItemText(catLst
.getSelectedIndex())));
segnalazione.setDescrizione(descrizioneBox.getText());
segnalazione.setIndirizzo(gsb.getText());
segnalazione.setUtente(LoginPanel.username);
Segnalazioni_Degrado.dataLayerService.inserisciSegnalazione(
segnalazione, new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
#Override
public void onSuccess(Boolean result) {
if (result) {
geocode(segnalazione);
uploadFrm.submit();
Window.alert("Inserimento avvenuto con successo");
MenuPanel.refreshBtn.click();
} else
Window.alert("L'inserimento ha avuto esito negativo");
thisPnl.hide();
}
});
}
});
uploadFrm.setAction(GWT.getModuleBaseURL() + "imageUpload");
uploadFrm.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadFrm.setMethod(FormPanel.METHOD_POST);
uploadFrm
.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
Window.alert("SUBMIT COMPLETATO");
String res = event.getResults();
if (res != null && !res.equals("")) {
Window.alert("IL SERVER RISPONDE " + res.toString());
String[] uploadedFiles = res.split(";");
aggiornaFotoDB(uploadedFiles, segnalazione);
}
}
});
The weird thing is that it works properly on DevMode, but it doesn't work when I deploy my webapp to Tomcat.
What's wrong with my code?
It turned out that the problem was
thisPnl.hide();
The solution was to hide the panel INSIDE the SubmitCompleteHandler
I want to upload a file, store it in the Blobstore and then later access it (via the BlobKey) but this won't work.
Here is my Code:
public class CsvToBlobstoreUploadServlet extends HttpServlet {
private final BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
#Override
public void doPost(final HttpServletRequest request, final HttpServletResponse res) throws ServletException, IOException {
final Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);
final BlobKey blobKey = blobs.get("upload");
final BlobInfo info = new BlobInfoFactory().loadBlobInfo(blobstoreService.getUploadedBlobs(request).get("upload"));
if (blobKey == null) {
res.sendRedirect("/");
} else {
res.sendRedirect("/csvupload?blob-key=" + blobKey.getKeyString());
}
}
#Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(new BlobKey(req.getParameter("blob-key")));
resp.setContentType("text/html");
resp.setHeader("Content-Language", "en");
resp.getWriter().println("<blob-key>" + blobInfo.getBlobKey().getKeyString() + "</blob-key>"); // Here I get no NullPointerException, blobInfo is NOT null, everything es as expected....
}
This works! Means the File ist stored in the Blobstore, and I get something like <blob-key>jA_W_jiKoTpXAe9QjeFlrg</blob-key> back from Post request.
Now I want to access this Blob with this key, but following Code results in NullPointerException, because blobInfo is null.... but why???
// A method from another Servlet....
private String getData(final String blobKey) {
//at this point blobKey is exactly that one returned previously for example jA_W_jiKoTpXAe9QjeFlrg
try {
final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(new BlobKey(blobKey));
final BlobstoreInputStream bis = new BlobstoreInputStream(blobInfo.getBlobKey()); // Here I got NullPointerException, because BlobInfo is null
final InputStreamReader isr = new InputStreamReader(bis);
final BufferedReader br = new BufferedReader(isr);
final StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (final IOException e) {
e.printStackTrace();
}
return "";
}
I would be very very glad if someone could figure out what the problem is....
The following works for me it need only one helper class, called FileObject, which is a named dynamic byte buffer to append byte arrays:
public class FileObject {
private String name;
byte [] bufferArray = null;
public FileObject(String name, byte[] data) {
this.name = name;
this.bufferArray = data;
}
public FileObject(String name) {
this.name = name;
}
public void appendData(byte[] data, int numberOfBytes) {
if (bufferArray == null)
{
this.bufferArray = new byte [numberOfBytes];
System.arraycopy(data, 0, bufferArray, 0, numberOfBytes);
}
else
{
byte[] tempArray = new byte[bufferArray.length + numberOfBytes];
System.arraycopy(bufferArray, 0, tempArray, 0, bufferArray.length);
System.arraycopy(data, 0, tempArray, bufferArray.length, numb erOfBytes);
bufferArray = tempArray;
}
}
public byte[] getData() {
return bufferArray;
}
public void setData(byte[] data) {
this.bufferArray = data;
}
public String getName() {
return name;
}
}
This is the core method to write into the file object:
public synchronized static byte[] readBlob(BlobKey blobKey) throws BlobServiceException{
int bufferSize = MAX_READ_BUFFER_SIZE;
FileObject fileObject = new FileObject("");
try{
AppEngineFile file = fileService.getBlobFile(blobKey);
FileReadChannel readChannel = fileService.openReadChannel(file, false);
// write the files to the disk
ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
int numberOfBytes;
while ((numberOfBytes = readChannel.read(byteBuffer)) != -1) {
fileObject.appendData(byteBuffer.array(), numberOfBytes);
byteBuffer = ByteBuffer.allocate(bufferSize);
}
readChannel.close();
}catch(Exception e){
BlobServiceException blobIoException = new BlobServiceException("Failure while reading blob.\n" + e.getMessage());
blobIoException.setStackTrace(e.getStackTrace());
throw blobIoException;
}
return fileObject.getData();
}