Primefaces dataExporter - inline PDF in new window without footer - jsf-2

I'm trying to use Primefaces's dataExporter component. I have two problems with it (for now):
In column footers of datatable I have a p:commandButton. What happens to me is that when I export datatable with dataExporter to PDF I can see that it added column footers to PDF and wrote something like this: javax.faces.component.UIPanel#9e08b9 (it just called toString of UIComponent I suppose). Is there any way to instruct dataExporter to ignore column footers?
I want to try to somehow open new window with generated PDF and show that PDF inline on a new page. I don't wont to see Download file prompt. Is this possible?

After some time, and coding I finally succeeded to make this work. Primefaces doesn't have this functions included so I have to override default behavior little bit.
First I created custom PDFExporter to skip footer printing:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.component.export.PDFExporter;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfPTable;
public class CustomPDFExporter extends PDFExporter {
#Override
protected void addColumnFacets(DataTable table, PdfPTable pdfTable,
ColumnType columnType) {
if (columnType == ColumnType.HEADER) {
super.addColumnFacets(table, pdfTable, columnType);
}
}
#Override
protected void writePDFToResponse(ExternalContext externalContext,
ByteArrayOutputStream baos, String fileName) throws IOException,
DocumentException {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.put("reportBytes", baos.toByteArray());
FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.put("reportName", fileName);
}
}
As you can see, report data is added in session.
Now DataExporter of Primefaces should be rewriten:
import java.io.IOException;
import javax.el.ELContext;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.faces.FacesException;
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.component.export.CSVExporter;
import org.primefaces.component.export.Exporter;
import org.primefaces.component.export.ExporterType;
import org.primefaces.component.export.XMLExporter;
import org.primefaces.context.RequestContext;
import asw.iis.common.ui.beans.DatatableBackingBean;
public class CustomDataExporter implements ActionListener, StateHolder {
private ValueExpression target;
private ValueExpression type;
private ValueExpression fileName;
private ValueExpression encoding;
private MethodExpression preProcessor;
private MethodExpression postProcessor;
private DatatableBackingBean<?> datatableBB;
public CustomDataExporter() {}
public CustomDataExporter(ValueExpression target, ValueExpression type, ValueExpression fileName, ValueExpression encoding,
MethodExpression preProcessor, MethodExpression postProcessor, DatatableBackingBean<?> datatableBB) {
this.target = target;
this.type = type;
this.fileName = fileName;
this.encoding = encoding;
this.preProcessor = preProcessor;
this.postProcessor = postProcessor;
this.datatableBB = datatableBB;
}
public void processAction(ActionEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
try {
datatableBB.stampaPreProcess();
ELContext elContext = context.getELContext();
String tableId = (String) target.getValue(elContext);
String exportAs = (String) type.getValue(elContext);
String outputFileName = (String) fileName.getValue(elContext);
String encodingType = "UTF-8";
if(encoding != null) {
encodingType = (String) encoding.getValue(elContext);
}
try {
Exporter exporter;
ExporterType exporterType = ExporterType.valueOf(exportAs.toUpperCase());
switch(exporterType) {
case XLS:
exporter = new ExcelExporter();
break;
case PDF:
exporter = new CustomPDFExporter();
break;
case CSV:
exporter = new CSVExporter();
break;
case XML:
exporter = new XMLExporter();
break;
default:
exporter = new CustomPDFExporter();
break;
}
UIComponent component = event.getComponent().findComponent(tableId);
if(component == null) {
throw new FacesException("Cannot find component \"" + tableId + "\" in view.");
}
if(!(component instanceof DataTable)) {
throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName() + "\", exporter must target a PrimeFaces DataTable.");
}
DataTable table = (DataTable) component;
exporter.export(context, table, outputFileName, false, false, encodingType, preProcessor, postProcessor);
if ("pdf".equals(exportAs)) {
String path = ((ServletContext)(FacesContext.getCurrentInstance().getExternalContext().getContext())).getContextPath();
RequestContext.getCurrentInstance().execute("window.open('" + path + "/report.pdf', '_blank', 'dependent=yes, menubar=no, toolbar=no')");
} else {
context.responseComplete();
}
}
catch (IOException e) {
throw new FacesException(e);
}
}
finally {
((HttpServletRequest) context.getExternalContext().getRequest()).removeAttribute("vrstaStampe");
datatableBB.stampaPostProcess();
}
}
public boolean isTransient() {
return false;
}
public void setTransient(boolean value) {
}
public void restoreState(FacesContext context, Object state) {
Object values[] = (Object[]) state;
target = (ValueExpression) values[0];
type = (ValueExpression) values[1];
fileName = (ValueExpression) values[2];
preProcessor = (MethodExpression) values[3];
postProcessor = (MethodExpression) values[4];
encoding = (ValueExpression) values[5];
datatableBB = (DatatableBackingBean<?>) values[6];
}
public Object saveState(FacesContext context) {
Object values[] = new Object[7];
values[0] = target;
values[1] = type;
values[2] = fileName;
values[3] = preProcessor;
values[4] = postProcessor;
values[5] = encoding;
values[6] = datatableBB;
return ((Object[]) values);
}
}
Main job here is to instantiate CustomPDFExporter, and open new window in case when report type is PDF.
Now I wrote simple Servlet to handle this request and print report data:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/report.pdf")
public class PdfReportServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
byte[] b = (byte[]) req.getSession().getAttribute("reportBytes");
if (b == null) {
b = new byte[0];
}
resp.setContentType("application/pdf");
resp.setContentLength(b.length);
resp.getOutputStream().write(b);
req.getSession().removeAttribute("reportBytes");
}
}
This will configure HTTP header, and print bytes of report to output stream. Also it removes report bytes from session.
Finally, as I handle this printing from dynamically created menu button I add this action listener in code:
MenuItem item = ...;
ELContext el = FacesContext.getCurrentInstance().getELContext();
ExpressionFactory ef = FacesContext.getCurrentInstance().getApplication().getExpressionFactory();
ValueExpression typeEL = ef.createValueExpression(el, "#{startBean.reportType}", String.class);
ValueExpression fileEL = ef.createValueExpression(el, datasource, String.class);
ValueExpression targetEL = ef.createValueExpression(el, ":" + datatableId + ":datatableForm:datatable", String.class);
ValueExpression encodingEL = ef.createValueExpression(el, "ISO-8859-2", String.class);
CustomDataExporter de = new CustomDataExporter(targetEL, typeEL, fileEL, encodingEL, null, null, this);
item.setAjax(true);
item.addActionListener(de);

Related

Java How to format URL as a String to connect with JSoup Malformed URL error

I have a program that connects to a user defined URL from a TextField and scrapes the images on that web page. The user defined URL is gotten from the textfield via .getText() and assigned to a String. The String is then used to connect to the Web page with JSoup and puts the webpage into a document.
String address = labelforAddress.getText();
try {
document = Jsoup.connect(address).get();
}catch(IOException ex){
ex.printStackTrace();
}
I've tried differently formatted URLS: "https://www.", "www.", "https://" but everything I use throws the malformed URL error.
Someone please show me how to get the text from the TextField the correct way.
Below is the entire code.
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main extends Application {
Document document;
LinkedList<String> imageURLList = new LinkedList<String>();
ArrayList<File> fileList = new ArrayList<File>();
int fileCount = 1;
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Webpage Photo Scraper");
GridPane gp = new GridPane();
Label labelforAddress = new Label("URL");
GridPane.setConstraints(labelforAddress, 0,0);
TextField URLAddress = new TextField();
GridPane.setConstraints(URLAddress, 1,0);
Button scrape = new Button("Scrape for Photos");
GridPane.setConstraints(scrape, 0,1);
scrape.setOnAction(event->{
String address = labelforAddress.getText();
try {
document = Jsoup.connect(address).get();
}catch(IOException ex){
ex.printStackTrace();
}
Elements imgTags = document.getElementsByAttributeValueContaining("src", "/CharacterImages");
for(Element imgTag: imgTags){
imageURLList.add(imgTag.absUrl("src"));
}
for(String url: imageURLList){
File file = new File("C:\\Users\\Andrei\\Documents\\file" + fileCount + ".txt");
downloadFromURL(url, file);
fileList.add(file);
fileCount++;
}
});
Button exportToZipFile = new Button("Export to Zip File");
GridPane.setConstraints(exportToZipFile, 0,2);
exportToZipFile.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter exfilt = new FileChooser.ExtensionFilter("Zip Files", ".zip");
fileChooser.getExtensionFilters().add(exfilt);
try{
FileOutputStream fos = new FileOutputStream(fileChooser.showSaveDialog(primaryStage));
ZipOutputStream zipOut = new ZipOutputStream(fos);
for(int count = 0; count<=fileList.size()-1; count++){
File fileToZip = new File(String.valueOf(fileList.get(count)));
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
}catch(IOException e1){
e1.printStackTrace();
}
});
primaryStage.setScene(new Scene(gp, 300, 275));
primaryStage.show();
gp.getChildren().addAll(exportToZipFile, labelforAddress, scrape, URLAddress);
}
public static void downloadFromURL(String url, File file){
try {
URL Url = new URL(url);
BufferedInputStream bis = new BufferedInputStream(Url.openStream());
FileOutputStream fis = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int count = 0;
while((count = bis.read(buffer, 0,1024)) !=-1){
fis.write(buffer, 0, count);
}
fis.close();
bis.close();
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Your text field containing the value entered by user is stored in URLAddress object but you always try to get the url from labelforAddress object which is a label always containing "URL" text.
So the solution is to use:
String address = URLAddress.getText();
If you read carefully error message it would help you to find the cause, because it always displays the value it considers wrong. In this case I see:
Caused by: java.net.MalformedURLException: no protocol: URL
and it shows the unrecognized address is: URL.
If you encounter this kind of error next time try:
debugging the aplication in runtime to see values of each variable
logging variable values in the console to see if variables contain values you expect

Snowflake SDKTest: Error:(137, 49) java: cannot find symbol variable PublicKeyReader location: class net.snowflake.ingest.example.SDKTest

I am not able to run the SDKTest class following this documentation:
https://docs.snowflake.net/manuals/user-guide/data-load-snowpipe-rest-load.html
I am using IntelliJ and Java SDK 12.0.
Error:(137, 49) java: cannot find symbol
symbol: variable PublicKeyReader
location: class net.snowflake.ingest.example.SDKTest
Can anybody help me with this?
BR,
Here is the running copy of SDK Test code :
package com.snowflake.SalesforceTestCases;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Instant;
import java.util.Base64;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import net.snowflake.ingest.SimpleIngestManager;
import net.snowflake.ingest.connection.HistoryRangeResponse;
import net.snowflake.ingest.connection.HistoryResponse;
public class SDKTest {
private static final String PRIVATE_KEY_FILE = "<Path to your p8 file>/rsa_key.p8";
public static class PrivateKeyReader {
public static PrivateKey get(String filename) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
String encrypted = new String(keyBytes);
String passphrase = "Snowflake";
encrypted = encrypted.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "");
encrypted = encrypted.replace("-----END ENCRYPTED PRIVATE KEY-----", "");
EncryptedPrivateKeyInfo pkInfo = new EncryptedPrivateKeyInfo(Base64.getMimeDecoder().decode(encrypted));
PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray());
SecretKeyFactory pbeKeyFactory = SecretKeyFactory.getInstance(pkInfo.getAlgName());
PKCS8EncodedKeySpec encodedKeySpec = pkInfo.getKeySpec(pbeKeyFactory.generateSecret(keySpec));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey encryptedPrivateKey = keyFactory.generatePrivate(encodedKeySpec);
return encryptedPrivateKey;
}
}
private static HistoryResponse waitForFilesHistory(final SimpleIngestManager manager, Set<String> files)
throws Exception {
ExecutorService service = Executors.newSingleThreadExecutor();
class GetHistory implements Callable<HistoryResponse> {
private Set<String> filesWatchList;
GetHistory(Set<String> files) {
this.filesWatchList = files;
}
String beginMark = null;
public HistoryResponse call() throws Exception {
HistoryResponse filesHistory = null;
while (true) {
Thread.sleep(5000);
HistoryResponse response = manager.getHistory(null, null, beginMark);
if (response.getNextBeginMark() != null) {
beginMark = response.getNextBeginMark();
}
if (response != null && response.files != null) {
for (HistoryResponse.FileEntry entry : response.files) {
// if we have a complete file that we've
// loaded with the same name..
String filename = entry.getPath();
if (entry.getPath() != null && entry.isComplete() && filesWatchList.contains(filename)) {
if (filesHistory == null) {
filesHistory = new HistoryResponse();
filesHistory.setPipe(response.getPipe());
}
filesHistory.files.add(entry);
filesWatchList.remove(filename);
// we can return true!
if (filesWatchList.isEmpty()) {
return filesHistory;
}
}
}
}
}
}
}
GetHistory historyCaller = new GetHistory(files);
// fork off waiting for a load to the service
Future<HistoryResponse> result = service.submit(historyCaller);
HistoryResponse response = result.get(2, TimeUnit.MINUTES);
return response;
}
public static void main(String[] args) {
final String account = "<Snowflake Account Name >";
final String hostName = "<Snowflake Account URL>";
final String user = "<Snowflake Account Username>";
final String pipe = "<Snowflake Pipe Path>";
try {
final long oneHourMillis = 1000 * 3600L;
String startTime = Instant.ofEpochMilli(System.currentTimeMillis() - 4 * oneHourMillis).toString();
PrivateKey privateKey = PrivateKeyReader.get(PRIVATE_KEY_FILE);
//PublicKey publicKey = PublicKeyReader.get(PUBLIC_KEY_FILE);
#SuppressWarnings("deprecation")
SimpleIngestManager manager = new SimpleIngestManager(account, user, pipe, privateKey, "https", hostName, 443);
Set<String> files = new TreeSet<>();
files.add("<filename>");
manager.ingestFiles(manager.wrapFilepaths(files), null);
HistoryResponse history = waitForFilesHistory(manager, files);
System.out.println("Received history response: " + history.toString());
String endTime = Instant.ofEpochMilli(System.currentTimeMillis()).toString();
HistoryRangeResponse historyRangeResponse = manager.getHistoryRange(null, startTime, endTime);
System.out.println("Received history range response: " + historyRangeResponse.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
My understanding of the error is that the compiler does not know what the variable PublicKeyReader references. Perhaps the variable was declared incorrectly in the code or there was a misspelling? There is a sample Java program in the documentation you mentioned, but there is also a sample program here if it helps:
https://github.com/snowflakedb/snowflake-ingest-java
References for Error:
What does a "Cannot find symbol" compilation error mean?
https://www.thoughtco.com/error-message-cannot-find-symbol-2034060

InputStream exceptions while processing xml-code

hi am trying tp parse the xml in blackberry that stores in server. But it comes out in inputstream line with different exceptions.mostly with Datagram Protocol and TcpInput exceptions.i have attached my code here kindly guide me.
try {
Document doc;
StreamConnection conn = null;
InputStream is = null;
conn = (StreamConnection) Connector.open("http://xyz.com/GetImageDetails.xml;deviceside=true;");
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setIgnoringElementContentWhitespace(true);
docBuilderFactory.setCoalescing(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.isValidating();
is = conn.openInputStream();
doc = docBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("IMG_URL");
for (int i = 0; i < list.getLength(); i++) {
Node textNode = list.item(i).getFirstChild();
System.out.println(textNode);
}
} catch (Exception e) {
System.out.println(e.toString());
}
The XML parsing class is
/***/
package com.application.xmlParser;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Vector;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import com.application.log.Log;
public class CopyOfXMLParser extends DefaultHandler {
private String RecordElement;
private String xmlURL;
private Hashtable newObj = new Hashtable();
private Vector Records = new Vector();
private CallBack callBack ;
private String _localEndTag = "";
public void ParseInputStream(String stream,String rootElement, String recordElement , CallBack callBack)
{
RecordElement = recordElement;
this.callBack = callBack;
InputStream in = new ByteArrayInputStream(stream.getBytes());
try
{
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(this);
reader.parse(new InputSource(in));
}
catch ( Exception e )
{
System.out.println("#### ##### Parse Exception : " + e + "#### #####" + xmlURL);
/* callbackAdapter.callback(Records);*/
}
}
public void startElement(String Uri, String localName, String qName, Attributes attributes) throws SAXException
{
}
public void characters(char [ ] ch, int start, int length) throws SAXException
{
String elementValue = new String(ch, start, length).trim();
Log.d("End Tag", _localEndTag);
Log.d("Tag Value ", elementValue);
if(_localEndTag == null || _localEndTag.equalsIgnoreCase(""))
{
}
else
{
newObj.put((String)_localEndTag, (String)elementValue);
}
}
public void endElement(String Uri, String localName, String qName) throws SAXException
{
_localEndTag = localName;
if ( localName.equalsIgnoreCase(RecordElement) )
{
Records.addElement(newObj);
callBack.callBack(Records);
System.out.println("###### ###### FINISH ###### ######" +RecordElement);
}
}
}
/***/
/***/
How to Implement
take the (Http)InputStream response into String and call the below method ..your problem is solved
new CopyOfXMLParser().ParseInputStream(new String(baos.toByteArray()) ,"SOAP:Envelope", "SOAP:Envelope");
I am getting all the elements value , with this code
/*/
USe Sax parsing For XML Parsing.
Refer this link: http://stackoverflow.com/questions/11901822/xml-parsing-using-sax-for-blackberry/11914662#11914662

smart gwt required xml file structure

code is working properly.but i am not able to display the final data which is from "setDataURL("ds/test_data/employees.data.xml".so tel me where shud i create dis file and how to create.
package com.smartgwt.sample.showcase.client;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.fields.DataSourceFloatField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.google.gwt.i18n.client.NumberFormat;
import com.smartgwt.sample.showcase.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Showcase implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Greeting service.
*/
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
RootPanel.get().add(getViewPanel());
}
public Canvas getViewPanel() {
EmployeeXmlDS employeesDS = EmployeeXmlDS.getInstance();
TreeGrid treeGrid = new TreeGrid();
treeGrid.setCanEdit(true);
treeGrid.setLoadDataOnDemand(false);
treeGrid.setWidth(500);
treeGrid.setHeight(400);
treeGrid.setDataSource(employeesDS);
treeGrid.setNodeIcon("icons/16/person.png");
treeGrid.setFolderIcon("icons/16/person.png");
treeGrid.setShowOpenIcons(false);
treeGrid.setShowDropIcons(false);
treeGrid.setClosedIconSuffix("");
treeGrid.setAutoFetchData(true);
TreeGridField nameField = new TreeGridField("Name");
TreeGridField jobField = new TreeGridField("Job");
TreeGridField salaryField = new TreeGridField("Salary");
salaryField.setCellFormatter(new CellFormatter() {
public String format(Object value, ListGridRecord record, int rowNum, int colNum) {
if (value != null) {
NumberFormat nf = NumberFormat.getFormat("#,##0");
try {
return "$" + nf.format(((Number) value).longValue());
} catch (Exception e) {
return value.toString();
}
} else {
return null;
}
}
});
treeGrid.setFields(nameField, jobField, salaryField);
return treeGrid;
}
}
class EmployeeXmlDS extends DataSource {
private static EmployeeXmlDS instance = null;
public static EmployeeXmlDS getInstance() {
if (instance == null) {
instance = new EmployeeXmlDS("employeesDS");
}
return instance;
}
public EmployeeXmlDS(String id) {
setID(id);
setTitleField("Name");
setRecordXPath("/List/employee");
DataSourceTextField nameField = new DataSourceTextField("Name", "Name", 128);
DataSourceIntegerField employeeIdField = new DataSourceIntegerField("EmployeeId", "Employee ID");
employeeIdField.setPrimaryKey(true);
employeeIdField.setRequired(true);
DataSourceIntegerField reportsToField = new DataSourceIntegerField("ReportsTo", "Manager");
reportsToField.setRequired(true);
reportsToField.setForeignKey(id + ".EmployeeId");
reportsToField.setRootValue("1");
DataSourceTextField jobField = new DataSourceTextField("Job", "Title", 128);
DataSourceTextField emailField = new DataSourceTextField("Email", "Email", 128);
DataSourceTextField statusField = new DataSourceTextField("EmployeeStatus", "Status", 40);
DataSourceFloatField salaryField = new DataSourceFloatField("Salary", "Salary");
DataSourceTextField orgField = new DataSourceTextField("OrgUnit", "Org Unit", 128);
DataSourceTextField genderField = new DataSourceTextField("Gender", "Gender", 7);
genderField.setValueMap("male", "female");
DataSourceTextField maritalStatusField = new DataSourceTextField("MaritalStatus",
"Marital Status", 10);
setFields(nameField, employeeIdField, reportsToField, jobField, emailField, statusField,
salaryField, orgField, genderField, maritalStatusField);
setDataURL("ds/test_data/employees.data.xml");
setClientOnly(true);
}
}

How to send audio data from Java Applet to Rails controller

I have to send the audio data in byte array obtain by recording from java applet at the client side to rails server at the controller in order to save.
So, what encoding parameters at the applet side be used and in what form the audio data be converted like String or byte array so that rails correctly recieve data and then I can save that data at the rails in the file. As currently the audio file made by rails controller is not playing. It is the following ERROR :
LAVF_header: av_open_input_stream() failed
while playing with the mplayer.
Here is the sample Java Code i m using in which i m reading audio data from the audio file:
package networksocket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JApplet;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.util.Properties;
import javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager;
import sun.awt.HorizBagLayout;
import sun.awt.VerticalBagLayout;
import sun.misc.BASE64Encoder;
/**
*
* #author mukand
*/
public class Urlconnection extends JApplet implements ActionListener
{
/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
public BufferedInputStream in;
public BufferedOutputStream out;
public String line;
public FileOutputStream file;
public int bytesread;
public int toread=1024;
byte b[]= new byte[toread];
public String f="FINISH";
public String match;
public File fileopen;
public JTextArea jTextArea;
public Button refreshButton;
public HttpURLConnection urlConn;
public URL url;
OutputStreamWriter wr;
BufferedReader rd;
#Override
public void init() {
// TODO start asynchronous download of heavy resources
//textField= new TextField("START");
//getContentPane().add(textField);
JPanel p = new JPanel();
jTextArea= new JTextArea(1500,1500);
p.setLayout(new GridLayout(1,1, 1,1));
p.add(new JLabel("Server Details"));
p.add(jTextArea);
Container content = getContentPane();
content.setLayout(new GridBagLayout()); // Used to center the panel
content.add(p);
jTextArea.setLineWrap(true);
refreshButton = new java.awt.Button("Refresh");
refreshButton.reshape(287,49,71,23);
refreshButton.setFont(new Font("Dialog", Font.PLAIN, 12));
refreshButton.addActionListener(this);
add(refreshButton);
Properties properties = System.getProperties();
properties.put("http.proxyHost", "netmon.iitb.ac.in");
properties.put("http.proxyPort", "80");
}
#Override
public void actionPerformed(ActionEvent e)
{
try
{
url = new URL("http://localhost:3000/audio/audiorecieve");
urlConn = (HttpURLConnection)url.openConnection();
//String login = "mukandagarwal:rammstein$";
//String encodedLogin = new BASE64Encoder().encodeBuffer(login.getBytes());
//urlConn.setRequestProperty("Proxy-Authorization",login);
urlConn.setRequestMethod("POST");
// urlConn.setRequestProperty("Content-Type",
//"application/octet-stream");
//urlConn.setRequestProperty("Content-Type","audio/mpeg");//"application/x-www- form-urlencoded");
//urlConn.setRequestProperty("Content-Type","application/x-www- form-urlencoded");
//urlConn.setRequestProperty("Content-Length", "" +
// Integer.toString(urlParameters.getBytes().length));
urlConn.setRequestProperty("Content-Language", "UTF-8");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
byte bread[]=new byte[2048];
int iread;
char c;
String data=URLEncoder.encode("key1", "UTF-8")+ "=";
//String data="key1=";
FileInputStream fileread= new FileInputStream("//home//mukand//Hellion.ogg");//Dogs.mp3");//Desktop//mausam1.mp3");
while((iread=fileread.read(bread))!=-1)
{
//data+=(new String());
/*for(int i=0;i<iread;i++)
{
//c=(char)bread[i];
System.out.println(bread[i]);
}*/
data+= URLEncoder.encode(new String(bread,iread), "UTF-8");//new String(new String(bread));//
// data+=new String(bread,iread);
}
//urlConn.setRequestProperty("Content-Length",Integer.toString(data.getBytes().length));
System.out.println(data);
//data+=URLEncoder.encode("mukand", "UTF-8");
//data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
//data="key1=";
wr = new OutputStreamWriter(urlConn.getOutputStream());//urlConn.getOutputStream();
//if((iread=fileread.read(bread))!=-1)
// wr.write(bread,0,iread);
wr.write(data);
wr.flush();
fileread.close();
jTextArea.append("Send");
// Get the response
rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = rd.readLine()) != null) {
jTextArea.append(line);
}
wr.close();
rd.close();
//jTextArea.append("click");
}
catch (MalformedURLException ex) {
Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void start()
{
}
#Override
public void stop()
{
}
#Override
public void destroy()
{
}
// TODO overwrite start(), stop() and destroy() methods
}
Here is the Rails controller function for recieving:
def audiorecieve
puts "///////////////////////////////////////******RECIEVED*******////"
puts params[:key1]#+" "+params[:key2]
data=params[:key1]
#request.env('RAW_POST_DATA')
file=File.new("audiodata.ogg", 'w')
file.write(data)
file.flush
file.close
puts "////**************DONE***********//////////////////////"
end
Please reply quickly
Base64 encode the data. Send it as a string, receive it on the Rails side and decode it back to the original format.

Resources