Error java.lang.IllegalStateException: Unable to obtain OutputStream because Writer is already in use - liferay

I'm trying to download an Excel in a liferay portlet but when I'm going to get the outPutPortletStream I obtain the next exception:
java.lang.IllegalStateException: Unable to obtain OutputStream because Writer is already in use
This is the method I'm using to download the Excel:
public static void descargaFichero(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws Exception {
HttpServletRequest request = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(resourceRequest));
OutputStreamWriter osWriter = null;
BufferedWriter bWriter = null;
OutputStream outputStream = null;
InputStream is = null;
InputStreamReader isr = null;
File tempFile = null;
try {
String idDescarga = request.getParameter("id-descarga");
String rutaFicheroDescarga = Encriptador.decrypt(ConstantesFlujos.CLAVE_ENCRIPTADO_JSON, idDescarga);
String extension = FileUtil.getExtension(rutaFicheroDescarga);
String nombreArchivo = String.format("%s%s.%s",
ConstantesFlujos.PREFIJO_NOMBRE_FICHERO_RENOVACION,
fechaDesglosada(),
extension);
if(GestorLog.isInfoEnabled(clase)){
GestorLog.info(clase, String.format("Descargando fichero temporal: '%s' a '%s'", rutaFicheroDescarga, nombreArchivo));
}
if (extension.equalsIgnoreCase("xls")) {
resourceResponse.setContentType("application/vnd.ms-excel");
} else {
resourceResponse.setContentType("application/octet-stream");
}
((PortletResponse) resourceResponse).addProperty("Content-disposition", String.format("atachment; filename=%s", nombreArchivo));
tempFile = new File(rutaFicheroDescarga);
outputStream = resourceResponse.getPortletOutputStream();
osWriter = new OutputStreamWriter(outputStream, "ISO-8859-1");
char[] buf = new char[8192];
is = new FileInputStream(tempFile);
isr = new InputStreamReader(is, "ISO-8859-1");
int c = 0;
while ((c = isr.read(buf, 0, buf.length)) > 0) {
osWriter.write(buf, 0, c);
osWriter.flush();
}
} catch(Exception e){
GestorLog.error(clase, "Error en el metodo descargaFichero: " + e.getMessage());
throw e;
} finally {
if (isr != null) {
isr.close();
}
if (is != null) {
is.close();
}
if (bWriter != null) {
bWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (tempFile != null) {
tempFile.delete();
}
}
}
And I get the error in the line:
outputStream = resourceResponse.getPortletOutputStream();

This might be due to resourceResponse.addProperty being called before accessing the stream. Those operations can be nasty, as two parties will now try to write data to the output.
An easy way to omit all problems is to just delegate it all to the portal: PortletResponseUtil.sendFile exists in a couple of different variations, e.g.
PortletResponseUtil.sendFile(
resourceRequest,
resourceResponse,
fileName,
inputStream,
contentLength,
contentType,
contentDispositionType); // e.g. HttpHeaders.CONTENT_DISPOSITION_ATTACHMENT

Related

Shoutcast radio with J2ME

I have my application playing the radio stream which is shoutcast streaming. I have searched on the internet for 2 days but my application stills can't play this url. I don't know how to solve this.
This is my sample source code.
String url1 = "http://203.150.224.142:8003/;
HttpConnection con= (HttpConnection)Connector.open(url1);
InputStream is = con.openInputStream();
player = Manager.createPlayer(is, "audio/mpeg");
player.realize();
player.prefetch();
player.start();
I have used this code in production, it should work for you also.
HttpConnection conn = (HttpConnection) Connector.open(music.getTrack_url() + "?streamable=true", Connector.READ_WRITE);
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
is = conn.openInputStream();
player = Manager.createPlayer(is, "audio/mp3");
player.addPlayerListener(thisObj);
player.realize();
player.prefetch();
player.start();
}
Try This.
public void loadShoutcast(String url)
{
StreamConnection connection = null;
int BUFFER_SIZE = 1024;
DataOutputStream dos_ = null;
OutputStream os_ = null;
try
{
System.out.println("opening connection " + url);
//Shoutcast URL
connection = (StreamConnection) Connector.open(url);
os_ = connection.openOutputStream();
dos_ = new DataOutputStream(os_);
// send the HTTP request
String req = "GET / HTTP/1.1\r\nUser-Agent: Profile/MIDP-1.0 Configuration/CLDC-1.0\r\n\r\n";
dos_.write(req.getBytes());
is = null;
is = connection.openInputStream();
long byteDone = 0;
int byteCount;
byte[] buffer = new byte[BUFFER_SIZE];
//Connection to file where you want to save the content of shoutcast radio
//It can be skipped in case you dont want to save the contents
out = tempFilecon.openDataOutputStream();
System.out.println("starting download");
while (byteCount = is.read(buffer)) >= 0)
{
out.write(buffer, 0, byteCount);
byteDone += byteCount;
done += byteCount;
}
return;
}
catch (InterruptedIOException e)
{
System.out.println("InterruptedIOException 1" + e.getMessage());
return;
}
catch (Exception e)
{
System.out.println("ERROR - 51 " + e.getMessage());
return;
}
finally
{
if (dos_ != null)
{
dos_.close();
dos_ = null;
}
if (os_ != null)
{
os_.close();
os_ = null;
}
if (is != null)
{
is.close();
is = null;
}
if (out != null)
{
out.close();
out = null;
}
System.out.println("closing connection");
if (connection != null)
{
connection.close();
connection = null;
}
}
// return false;
}

how to upload audio to server: Blackberry

I'm trying to upload an .amr file to the server. My Code as follows:
private static void uploadRecording(byte[] data) {
byte[] response=null;
String currentFile = getFileName(); //the .amr file to upload
StringBuffer connectionStr=new StringBuffer("http://www.myserver/bb/upload.php");
connectionStr.append(getString());
PostFile req;
try {
req = new PostFile(connectionStr.toString(),
"uploadedfile", currentFile, "audio/AMR", data );
response = req.send(data);
} catch (Exception e) {
System.out.println("====Exception: "+e.getMessage());
}
System.out.println("Server Response : "+new String(response));
}
public class PostFile
{
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
byte[] postBytes = null;
String url = null;
public PostFile(String url, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
{
this.url = url;
String boundary = getBoundaryString();
String boundaryMessage = getBoundaryMessage(boundary, fileField, fileName, fileType);
String endBoundary = "\r\n--" + boundary + "--\r\n";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(boundaryMessage.getBytes());
bos.write(fileBytes);
bos.write(endBoundary.getBytes());
this.postBytes = bos.toByteArray();
bos.close();
}
String getBoundaryString()
{
return BOUNDARY;
}
String getBoundaryMessage(String boundary, String fileField, String fileName, String fileType)
{
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
return res.toString();
}
public byte[] send(byte[] fileBytes) throws Exception
{
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH ,Integer.toString(fileBytes.length));
OutputStream dout = hc.openOutputStream();
dout.write(postBytes);
dout.close();
int ch;
is = hc.openInputStream(); // <<< EXCEPTION HERE!!!
if(hc.getResponseCode()== HttpConnection.HTTP_OK)
{
while ((ch = is.read()) != -1)
{
bos.write(ch);
}
res = bos.toByteArray();
System.out.println("res loaded..");
}
else {
System.out.println("Unexpected response code: " + hc.getResponseCode());
hc.close();
return null;
}
}
catch(IOException e)
{
System.out.println("====IOException : "+e.getMessage());
}
catch(Exception e1)
{
e1.printStackTrace();
System.out.println("====Exception : "+e1.getMessage());
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
System.out.println("====Exception : "+e2.getMessage());
}
}
return res;
}
}
Highlighted above is the code line which throws the exception: Not Connected.
Can somebody tell me what can be done to correct this? Thanks a lot.
Updated:
public static String getString()
{
String connectionString = null;
String uid = null;
// Wifi
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
else
{
ServiceBook sb = ServiceBook.getSB();
net.rim.device.api.servicebook.ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++) {
if (records[i].isValid() && !records[i].isDisabled()) {
if (records[i].getUid() != null &&
records[i].getUid().length() != 0) {
if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) &&
(records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
(records[i].getUid().toLowerCase().indexOf("mms") == -1) ) {
uid = records[i].getUid();
break;
}
}
}
}
if (uid != null)
{
connectionString = ";deviceside=true;ConnectionUID="+uid;
}
else
{
// the carrier network
if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the
// carrier's
// TCP network
System.out.println("No Uid");
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier
// BIBS
// request
System.out.println("uid is: " + carrierUid);
connectionString = ";deviceside=false;connectionUID="
+ carrierUid + ";ConnectionType=mds-public";
}
}
//(BlackBerry Enterprise Server)
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging
// the user unnecessarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
System.out.println("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be
// reachable.
else {
System.out.println("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
}
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid() {
try {
net.rim.device.api.servicebook.ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals(
"ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
} catch (Exception e) {
System.out.println("====Exception : "+e.toString());
}
return null;
}

using post throws IOExceptions on some phones

i have created an application in J2ME that uses the following method to connect to a server. php is used on the Server side to process the requests. the application works fine on some phones like NOkia asha 303 but throws IOException on other phones what could be the problem with this code. this method is called on a different thread. i also want to ask if you use post in j2me and set the
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
do you have to urlencode the data before sending or that is handled automatically by j2me
public String sendData(String serverUrl, String dataToSend) {
String strResponse = "0"; //string to hold serverResponse
StringBuffer sb = new StringBuffer("");
HttpConnection httpConn = null;
InputStream inputStream = null;
OutputStream outStream = null;
try {
//convert the dataToSend to bytes
String strData = dataToSend; // get the data to Send and store it in a variable.
byte[] dataToSendBytes = strData.getBytes();
//open the Connection to the server.
httpConn = (HttpConnection) Connector.open(serverUrl, Connector.READ_WRITE, true);
if (httpConn != null) {
httpConn.setRequestMethod(HttpConnection.POST); // method used to send the data.
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
//httpConn.setRequestProperty("Content-Language", "en-US"); //language to use.
//setRequestProperty("Connection", "close") ===> could generate or Solve IOExceptions on different mobile Phones.
//httpConn.setRequestProperty("Connection", "close");
//setting the Content-length could have issues with some Servers===>
//if the dataToSend is Empty String => contentLen = 0 , else get length of the dataBytes.
String contentLen = ((dataToSend.length() > 0) ? Integer.toString(dataToSendBytes.length) : Integer.toString(0));
//httpConn.setRequestProperty("Content-length", contentLen); //not working on Emulator ....enable on shipping application.
//open the output Stream to send data to the Server.
outStream = httpConn.openOutputStream();
// send the bytes of data to the Server.===>
//outStream.write(dataToSendBytes);
//send the data bytes to the Server.
int byteLen = dataToSendBytes.length; //length of byteToSend.
for (int k = 0; k < byteLen; k++) {
//send all the databytes to the Server.
outStream.write(dataToSendBytes[k]);
}
//close the outputStream ===immediately after sending the data bytes to the Server===>eliminates the IOExceptions.
closeOutStream(outStream);
//get response code on Sending Data===> getting response code automatically flushes the output data.
ntworkResponseCode = httpConn.getResponseCode();
if (ntworkResponseCode == HttpConnection.HTTP_OK) {
//connection to the Server was okay.
if (httpConn != null) {
//read the Response From the Server-----------
inputStream = httpConn.openInputStream(); // open the inputStream.
//get server Response Content length.
int contLen = (int) httpConn.getLength();
byte[] serverResponseBytes; //byte array to store the serverResponse.
if (contLen != -1) {
//store the serverResponse to a byte array.===> using a byte buffer could be faster.
serverResponseBytes = new byte[contLen];
inputStream.read(serverResponseBytes);
//convert the bytes to String and store them to the StringBuffer.
sb.append(new String(serverResponseBytes));
} else {
//serverResponse Length not available===> read character by character could be slower.
int read;
while ((read = inputStream.read()) != -1) {
sb.append((char) read);
}
}
//store the server response in a String.
strResponse = sb.toString();
}
} else {
//connection problem occured.
//throw new IOException("Http Response Code [" + ntworkResponseCode + "]");
}
}// the httpConnection Not null.--end.
} catch (IllegalArgumentException arge) {
strResponse = CONNECTION_EXCEPTION;
} catch (ConnectionNotFoundException cone) {
//a string to show we got an exception
strResponse = CONNECTION_EXCEPTION;
} catch (IOException ioe) {
//a string to show we got an exception
strResponse = CONNECTION_EXCEPTION;
} catch (SecurityException se) {
//user cancelled the Connection Request.
strResponse = CONNECTION_EXCEPTION;
} finally {
//close all the connection streams
try {
if (inputStream != null) {
//close the inputStream
inputStream.close();
inputStream = null;
}
if (outStream != null) {
//close the outStream.
outStream.close();
outStream = null;
}
if (httpConn != null) {
//close the connection object.
httpConn.close();
httpConn = null;
}
} catch (IOException ie) {
//show exception occured.
}
}
//return server Response to the Client.
return strResponse;
}

save data from servlet to recordstore in j2me

I am developing an j2me application which is communicating with the database using servlet.
I want to store the data received from servlet into record store and display it.how this can be achieved?Please provide code examples.
Thank you in advance
public void viewcon()
{
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty("User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStream os = (DataOutputStream)c.openDataOutputStream();
os.flush();
os.close();
// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
// return sb;
showAlert(sb.toString());//display data received from servlet
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
}
}
Put this function call where you show the response data alert
writeToRecordStore(sb.toString().getBytes());
The function definition is as below:
private static String RMS_NAME = "NETWORK-DATA-STORAGE";
private boolean writeToRecordStore(byte[] inStream) {
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore(RMS_NAME, true);
if (null != rs) {
//Based on your logic either ADD or SET the record
rs.addRecord(inStream, 0, inStream.length);
return true;
} else {
return false;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
return false;
} finally {
try {
if (null != rs) {
rs.closeRecordStore();
}
} catch (RecordStoreException recordStoreException) {
} finally {
rs = null;
}
}
}
After you have saved the data, read the records store RMS-NAME and check the added index to get the response data.
.
NOTE: The assumption is the network response data is to be appended to the record store. If you want to set it to a particular record modify the method writeToRecordStore(...) accordingly.
//this code throws exception in display class.
try
{
byte[] byteInputData = new byte[5];
int length = 0;
// access all records present in record store
for (int x = 1; x <= rs.getNumRecords(); x++)
{
if (rs.getRecordSize(x) > byteInputData.length)
{
byteInputData = new byte[rs.getRecordSize(x)];
}
length = rs.getRecord(x, byteInputData, 0);
}
alert =new Alert("reading",new String(byteInputData,0,length),null,AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}

Reading a file in Blackberry

I am trying to read content from file in blackberry and i read the file content to result object and when i am trying to print the result object it gives error and the file is in res folder,and this is code that i got problem
private String readTextFile(String fName) {
String result = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
is = fconn.openDataInputStream();
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
System.out.println("result data is ...... "+result);
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != is)
is.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return result;
}
what is fName here ?
The file name or the path could cause similar problem.

Resources