Jfree bar chart servlet code with oracle database - oracle

I am new to jfree chart I have the following code it runs without any error, however the browser shows me an empty page .. do not know where is the problem.
I am trying to create a bar chart using jfree chart in servlet and the data will be retrieved from oracle data base.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartUtilities;
public class BarChar extends HttpServlet {
#Override
public void init() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("JDBC driver loaded");
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
}
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
OutputStream out = response.getOutputStream();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","FATIMAH", "FATIMAH");
DefaultCategoryDataset bar = new DefaultCategoryDataset();
Statement stmt = conn.createStatement();
ResultSet r = stmt.executeQuery("select category,marks from chart_data");
while (r.next())
{
String category = r.getString("CATEGORY");
int marks = r.getInt("MARKS");
bar.addValue(marks,"Mark",category);
}
JFreeChart BarChartObject=ChartFactory.createBarChart("Subject Vs Marks Bar Chart","Subject","Marks",bar,PlotOrientation.VERTICAL,true,true,false);
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, BarChartObject, 400, 300);
}
catch (Exception e) {
System.err.println(e.toString());
}
finally {
out.close();
}
}
}

Related

How to convert CSV to Excel using Python with pandas in Apache NiFi?

How to convert CSV raw source from GenerateFlowFile processor to Excel file using processor ExecuteStreamCommand or ExecuteScript?
And how to run Python virtual env (env) to use dependencies in Python project?
Wrap your CSV to Excel logic inside a Python script and call it using ExecuteStreamCommand. Start something like below and make changes as per your requirement:
import pandas as pd
# Reading the csv file content from NiFi
csv_df = pd.read_csv(sys.stdin)
# send excel file back to NiFi
csv_df.to_excel(sys.stdout.buffer, index=False)
Configure your ExecuteStreamCommand processor as:
I run the script. Then the Error "import: not found" occours.
package com.anoop.converter;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import org.apache.nifi.annotation.behavior.*;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessorInitializationContext;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.io.StreamCallback;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
#Tags({"csvToExcel"})
#CapabilityDescription("This processor can convert CSV flow files into Excel flow file")
#SeeAlso({})
#ReadsAttributes({#ReadsAttribute(attribute="", description="")})
#WritesAttributes({#WritesAttribute(attribute="", description="")})
#InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
public class CsvToExcel extends AbstractProcessor {
public static final Relationship REL_SUCCESS = new Relationship.Builder()
.name("original")
.description("The original file")
.build();
private List<PropertyDescriptor> descriptors;
private Set<Relationship> relationships;
#Override
protected void init(final ProcessorInitializationContext context) {
descriptors = Collections.emptyList();
relationships = new HashSet<>();
relationships.add(REL_SUCCESS);
relationships = Collections.unmodifiableSet(relationships);
}
#Override
public Set<Relationship> getRelationships() {
return this.relationships;
}
#Override
public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
return descriptors;
}
#OnScheduled
public void onScheduled(final ProcessContext context) {}
#Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
FlowFile flowFile = session.get();
if ( flowFile == null ) {
return;
}
session.write(flowFile, new Converter());
session.putAttribute(flowFile,"convertedIntoExcel","true");
session.transfer(flowFile,REL_SUCCESS);
}
}
class Converter implements StreamCallback {
#Override
public void process(InputStream in, OutputStream out) throws IOException {
try {
streamConversion(in,out);
} catch (CsvValidationException e) {
throw new RuntimeException(e);
}
}
private void streamConversion(InputStream in, OutputStream out) throws IOException, CsvValidationException {
CSVReader csvReader = new CSVReader(new InputStreamReader(in));
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
String[] rowData = null;
int rowNum = 0;
while ((rowData = csvReader.readNext()) != null) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (String cellData : rowData) {
Cell cell = row.createCell(colNum++);
cell.setCellValue(cellData);
}
}
workbook.write(out);
workbook.close();
}
}

Spring Boot - readMessageInternal of AbstractHttpMessageConverter implementation not getting invoked

Trying to write very simple http message converter to add encryption around request & respose.
Implemented rest controller and messageConverter. writeInternal does get invoked during response. However readInternal does not get invoked when request is sent to the rest end point.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.techm.bm.util.EncryptDecryptUtil;
#Component
public class MessageEncryptionConverter extends AbstractHttpMessageConverter<Object> {
#Autowired
private ObjectMapper objectMapper;
public MessageEncryptionConverter() {
super(MediaType.ALL);
}
#Override
protected boolean supports(Class<?> clazz) {
return true;
}
#Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
return objectMapper.readValue(decrypt(inputMessage.getBody()), clazz);
}
#Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
outputMessage.getBody().write(encrypt(objectMapper.writeValueAsBytes(o)));
}
The below code is for encryption and decryption of request and response body For overall Project to modify response body and request parameters. Please check this code is works for me
For Request Encryption refer readInternal
below is the front-end or postman request sending, you have to add encrypted request in Json formate
Ex.{data : "+++++++++++++YOUR_ENCRYPTED_STRING++++++++++"}
For Response Descryption refer writeInternal
sending back to your front-end or postman request response with encrypted string
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.techm.bm.util.EncryptDecryptUtil;
#Component
public class MessageEncryptionConverter extends AbstractHttpMessageConverter<Object> {
#Autowired
private ObjectMapper objectMapper;
public MessageEncryptionConverter() {
super(MediaType.ALL);
}
#Override
protected boolean supports(Class<?> clazz) {
return true;
}
#Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
return objectMapper.readValue(decrypt(inputMessage.getBody()), clazz);
}
#Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
outputMessage.getBody().write(encrypt(objectMapper.writeValueAsBytes(o)));
}
// Convert request to input stream for sending to the controller
private InputStream decrypt(InputStream inputStream) throws IOException {
//this is API request params
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException" + e.getMessage());
} catch (IOException e) {
logger.error("IOException" + e.getMessage());
} finally {
inputStream.close();
}
try {
JSONObject requestJsonObject = new JSONObject(writer.toString().replace("\n", ""));
// Add your decryption method the object data will get your encrypted string data and return with string of your JSON object
String decryptRequestString = EncryptionUtils.decryptText(requestJsonObject.getString("data"));
if (decryptRequestString != null) {
return new ByteArrayInputStream(decryptRequestString.getBytes(StandardCharsets.UTF_8));
} else {
return inputStream;
}
} catch (JSONException err) {
logger.error("Error" + err.toString());
} catch (NoSuchAlgorithmException | BadPaddingException | DigestException | InvalidKeyException
| InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException e) {
logger.info("NoSuchAlgorithmException | BadPaddingException | DigestException | InvalidKeyException | " +
"InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException:: " + e.getMessage());
}
return inputStream;
}
private byte[] encrypt(Object obj) throws JsonProcessingException {
// do your encryption here
try {
String stringFromObject = objectMapper.writeValueAsString(obj);
// Add your encryption method
String encrypt = EncryptionUtils.encryptText(stringFromObject);
return objectMapper.writeValueAsBytes(encrypt);
} catch (Exception e) {
logger.info("Error While Encrypt data :: " + e.getMessage());
return objectMapper.writeValueAsBytes(obj);
}
}
}
Reference code Spring Boot - Encrypt JSON data
Hope this code is working for you
It is invoking if the request has body and "supports" method return ture

Fatal error:An error occured while executing doInBackground()

I am new to android and i am getting this error.Maths1 code:
package com.materialdesign.geniusmathsandphysics;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class Maths1 extends Activity{
MainActivity async;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maths1);
async=new MainActivity();
Button m15,d15;
m15 = (Button) findViewById(R.id.but_m1may15);
d15 = (Button) findViewById(R.id.but_m1dec15);
m15.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File pdf = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/" + "M1_May_15.pdf");
if (pdf.exists()) {
//file= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/pdf/Area.pdf");
Intent i=new Intent(Maths1.this,PdfViewer.class);
i.putExtra("FileName",pdf);
startActivity(i);
} else {
if (isNetworkConnected() == true) {
Toast.makeText(Maths1.this, "Starting Download....please wait.", Toast.LENGTH_LONG).show();
async.new Connect().execute("166.62.10.29", "M1_May_15.pdf");
} else {
Toast.makeText(Maths1.this, "No internet connection \n Please try again", Toast.LENGTH_SHORT).show();
}
}
}
});
d15.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File pdf = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/" + "M1_Dec_15.pdf");
if (pdf.exists()) {
ViewPDF();
} else {
if (isNetworkConnected() == true) {
async.new Connect().execute("166.62.10.29", "M1_Dec_15.pdf");
Toast.makeText(Maths1.this, "Starting Download....please wait.", Toast.LENGTH_LONG).show();
ViewPDF();
} else {
Toast.makeText(Maths1.this, "No internet connection \n Please try again", Toast.LENGTH_SHORT).show();
}
}
}
});
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
public void ViewPDF()
{
Intent i=new Intent(Maths1.this,PdfViewer.class);
SavePreferences("name", "M1_Dec_15.pdf");
startActivity(i);
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
}
pdf viewer code:
package com.materialdesign.geniusmathsandphysics;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
public class PdfViewer extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdfviewer);
com.joanzapata.pdfview.PDFView Pdf = (com.joanzapata.pdfview.PDFView) findViewById(R.id.pdfview1);
//String filepath=getIntent().getExtras().getString("name");
String file=showPreferences("name");
File fd = new File(file);
//Log.i("hhhhdsdada",filepath);
Pdf.fromFile(fd).defaultPage(1).swipeVertical(true).load();
}
private String showPreferences(String key){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String savedPref = sharedPreferences.getString(key, "");
File files= new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/"+savedPref);
String file=files.toString();
return file;
}
}
this is my logcat:
FATAL EXCEPTION: AsyncTask #3 Process: com.materialdesign.geniusmathsandphysics, PID: 18871
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: PDF file is corrupted
at org.vudroid.pdfdroid.codec.PdfDocument.open(Native Method)
at org.vudroid.pdfdroid.codec.PdfDocument.openDocument(PdfDocument.java:28)
at org.vudroid.pdfdroid.codec.PdfContext.openDocument(PdfContext.java:18)
at org.vudroid.core.DecodeServiceBase.open(DecodeServiceBase.java:59)
at com.joanzapata.pdfview.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:52)
at com.joanzapata.pdfview.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:818) 
i am using joanzapata library to view pdf files.for that i am trenter code hereying to pass that file name from maths 1 class on button click listner. The library takes file as input so i had to convert string to file previously using intent i was getting null pointer exception but now with shared preferences i am getting this error. Please help me to solve it. Thanks in advance.

Ajax loader is not getting called in a file upload custom component in JSF 2.0

In my current project I am trying to create a file upload custom component because we have a constraint that we can’t use any component library. Our requirement is to create single file upload, upon selecting and uploading a file it will get displayed in a data table below that component. User will be able to download the uploaded file and if required can delete the uploaded file also. There will be a ajax loader which needs to be fired upon uploading a file. Pictorially the UI looks like this.
________________________ __________ ____________
| | | Browse | | Upload |
|_______________________| |_________| |___________|
______________________________________________
| | |
| File1.pdf | * |
|_______________________________________|_____|
| | |
| File2.pdf | * |
|_______________________________________|_____|
To create this component I have taken help from Core JavaServer Pages(3e) to create custom component & BalusC’s blogs to trigger ajax call from a jsf page(jsf.ajax.addOnEvent). Here is the entire code of Renderer, xhtml, and managedbean. For the time being I have used a h:outputtext instead of h:datatable to update the page.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:corejsf="http://corejsf.com">
<h:head>
<title>A file upload test</title>
<h:outputScript name="jsf.js" library="javax.faces" target="head"/>
<script>
jsf.ajax.addOnEvent(function(data) {
var ajaxstatus = data.status;
var ajaxloader = document.getElementById("ajaxloader");
switch (ajaxstatus) {
case "begin": // This is called right before ajax request is been sent.
ajaxloader.style.display = 'block';
break;
case "complete":
ajaxloader.style.display = 'none';
break;
case "success": // NOOP.
break;
} });
</script>
</h:head>
<h:body>
<h:form>
<h:commandButton value="hello"></h:commandButton>
</h:form>
<h:form enctype="multipart/form-data">
Upload a photo of yourself:
<corejsf:upload uploadButton="upload"/>
<h:outputText id="updateText" value="#{user.value}"></h:outputText>
<h:commandButton action="#{user.submit}" value="Initiate"></h:commandButton>
</h:form>
<img id="ajaxloader" src="ajax-loader.gif" style="display: none;" />
</h:body>
</html>
The Renderer:
package com.corejsf;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import javax.el.ELContext;
import javax.el.ValueExpression;
import javax.faces.FacesException;
import javax.faces.application.ResourceDependencies;
import javax.faces.application.ResourceDependency;
import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;
import javax.faces.render.Renderer;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
#FacesRenderer(componentFamily="javax.faces.Input",
rendererType="com.corejsf.Upload")
public class UploadRenderer extends Renderer {
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
if (!component.isRendered()) return;
ResponseWriter writer = context.getResponseWriter();
String ajax = "jsf.ajax.request(this, event,{render:'j_idt11:updateText'}); return false";
String clientId = component.getClientId(context);
System.out.println("parentid>>>>>>"+component.getParent().getClientId(context));
System.out.println(clientId);
System.out.println("upload button >>>>>>"+(String)component.getAttributes().get("uploadButton"));
writer.startElement("input", component);
writer.writeAttribute("type", "file", "type");
writer.writeAttribute("name", clientId+":INPUT_FILE", "clientId");
writer.endElement("input");
writer.startElement("input", component);
writer.writeAttribute("type", "submit", null);
writer.writeAttribute("name", clientId + ":FILE_UPLOAD", null);
writer.writeAttribute("value", "Upload", "value");
writer.writeAttribute("onclick", ajax, null);
writer.endElement("input");
writer.flush();
}
public void decode(FacesContext context, UIComponent component) {
Map<String,String> requestMap = context.getExternalContext ().getRequestParameterMap();
String clientId = component.getClientId(context);
System.out.println("getId>>>>>>>"+component.getId());
if(requestMap.containsKey(clientId+":FILE_UPLOAD")){
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("true");
ExternalContext external = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) external.getRequest();
//String clientIdFile = component.getClientId(context);
FileItem item = (FileItem) request.getAttribute(clientId+":INPUT_FILE");
System.out.println("filename>>>>"+item.getName()+">>>");
System.out.println("file blank>>>>"+item.getName().equals(""));
ELContext elContext = FacesContext.getCurrentInstance().getELContext();
UserBean userBean = (UserBean) FacesContext.getCurrentInstance().getApplication()
.getELResolver().getValue(elContext, null, "user");
try {
userBean.setUploadedFile(item.getInputStream());
userBean.setValue(userBean.getUploadedFileList().size());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
System.out.println("false");
}
}
Managed bean:
package com.corejsf;
import java.io.Serializable;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
//import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import java.io.InputStream;
import java.util.ArrayList;
#ManagedBean(name="user")
#ViewScoped
public class UserBean implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private ArrayList<InputStream> uploadedFileList = new ArrayList<InputStream>();
public ArrayList<InputStream> getUploadedFileList() {
return uploadedFileList;
}
public void setUploadedFileList(ArrayList<InputStream> uploadedFileList) {
this.uploadedFileList = uploadedFileList;
}
private int value = 0;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getId() { return id; }
public void setId(String newValue) { id = newValue; }
public void setUploadedFile(InputStream inputStream){
uploadedFileList.add(inputStream);
}
}
UploadFilter:
package com.corejsf;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadFilter implements Filter {
private int sizeThreshold = -1;
private String repositoryPath;
public void init(FilterConfig config) throws ServletException {
repositoryPath = config.getInitParameter(
"com.corejsf.UploadFilter.repositoryPath");
try {
String paramValue = config.getInitParameter(
"com.corejsf.UploadFilter.sizeThreshold");
if (paramValue != null)
sizeThreshold = Integer.parseInt(paramValue);
}
catch (NumberFormatException ex) {
ServletException servletEx = new ServletException();
servletEx.initCause(ex);
throw servletEx;
}
}
public void destroy() {
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
chain.doFilter(request, response);
return;
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
boolean isMultipartContent
= ServletFileUpload.isMultipartContent(httpRequest);
if (!isMultipartContent) {
chain.doFilter(request, response);
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
if (sizeThreshold >= 0)
factory.setSizeThreshold(sizeThreshold);
if (repositoryPath != null)
factory.setRepository(new File(repositoryPath));
ServletFileUpload upload = new ServletFileUpload(factory);
try {
#SuppressWarnings("unchecked") List<FileItem> items
= (List<FileItem>) upload.parseRequest(httpRequest);
final Map<String, String[]> map = new HashMap<String, String[]>();
for (FileItem item : items) {
String str = item.getString();
if (item.isFormField())
map.put(item.getFieldName(), new String[] { str });
else
httpRequest.setAttribute(item.getFieldName(), item);
}
chain.doFilter(new
HttpServletRequestWrapper(httpRequest) {
public Map<String, String[]> getParameterMap() {
return map;
}
// busywork follows ... should have been part of the wrapper
public String[] getParameterValues(String name) {
Map<String, String[]> map = getParameterMap();
return (String[]) map.get(name);
}
public String getParameter(String name) {
String[] params = getParameterValues(name);
if (params == null) return null;
return params[0];
}
public Enumeration<String> getParameterNames() {
Map<String, String[]> map = getParameterMap();
return Collections.enumeration(map.keySet());
}
}, response);
} catch (FileUploadException ex) {
ServletException servletEx = new ServletException();
servletEx.initCause(ex);
throw servletEx;
}
}
}
taglib.xml:
<facelet-taglib version="2.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee">
<namespace>http://corejsf.com</namespace>
<tag>
<tag-name>upload</tag-name>
<component>
<component-type>javax.faces.Input</component-type>
<renderer-type>com.corejsf.Upload</renderer-type>
</component>
</tag>
</facelet-taglib>
The issue that I am facing with this code is that the ajax is updating the h:outputtext but the ajax loader is not working. It is not getting displayed upon uploading a file. It should get displayed on begin status and disappear on complete status. Besides, firefox error console shows a “Reference error: jsf is not defined” message.
I have put a :
<h:outputScript name="jsf.js" library="javax.faces" target="head"/>
inside h:head tag . But it did not help. The webpage is not responding after adding this line in firefox but it is working on IE, though ajax loader is not working in any case.
Please help.
Thanks in advance.

Android HttpClient problem

No errors in code according to Eclipse IDE. But when I'm trying to run this one in device it gives an error message.
package com.android.mypackage;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpEntity;
import android.widget.TextView;
public class MyActivity extends Activity
{
TextView textview;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.google.com");
HttpResponse httpresponse = httpclient.execute(httpget);
HttpEntity httpentity = httpresponse.getEntity();
if (httpentity != null)
{
httpentity = new BufferedHttpEntity(httpentity);
}
}
catch (Exception e)
{
System.out.println("Exception e");
textview.setText(e.getMessage());
}
};
});
}
}
Try this: add this line
httpget.addHeader("User-Agent", "Android");
Before you execute httpget.

Resources