save data from servlet to recordstore in j2me - java-me

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);
}

Related

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

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

Nifi: how to remove session based on atribute value in nifi

I want to remove session in case i get certain data from file i have code like this,but i got errors "flowfile has already marked for removal", what should i change to get rid of extra errors?
In case of session rollback flowfile will dissapear in queues also?
2.should i use rollback instead of remove()?
NodeList childNodes = nodeGettingChanged.getChildNodes();
for (int i = 0; i != childNodes.getLength(); ++i) {
Node child = childNodes.item(i);
if (!(child instanceof Element))
continue;
if (child.getNodeName().equals("runAs")) {
if(child.getFirstChild().getTextContent()=="false"){
session.remove(flowFile1);
File deleteExtraFile =new File("C://Users//s.tkhilaishvili//Desktop//try2//nifi-1.3.0//1//conf.xml");
boolean delete=deleteExtraFile.delete();
}
else {
child.getFirstChild().setNodeValue("false");
}
}
}
Document finalXmlDocument = xmlDocument;
session.write(flowFile1, new StreamCallback() {
public void process(InputStream inputStream, OutputStream outputStream) throws IOException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
DOMSource source = new DOMSource(finalXmlDocument);
ffStream.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bos);
try {
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
byte[] array = bos.toByteArray();
outputStream.write(array);
}
});
session.remove(flowFile);
session.transfer(flowFile1, REL_SUCCESS);
}
If you are executing session.remove(flowFile1) then later trying to transfer it to REL_SUCCESS, you will get that error. It looks like you already have an if-clause checking the firstChild for "false", perhaps you could put the transfer in an else-clause, such that it will only be transferred if it wasn't removed.

Blackberry - How to consume wcf rest services

Recently i have started working on consuming wcf rest webservices in blackberry.
I have used the below two codes:
1.
URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
// passing q’s value and ie’s value
postData.append("UserName", "hsharma#seasiaconsulting.com");
postData.append("Password", "mind#123");
HttpPosst hh=new HttpPosst();
add(new LabelField("1"));
String res=hh.GetResponse("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration",postData);
add(new LabelField("2"));
add(new LabelField(res));
public String GetResponse(String url, URLEncodedPostData data)
{
this._postData = data;
this._url = url;
ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try
{
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// logMessage("Carrier coverage.");
// String carrierUid = getCarrierBIBSUid();
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
// logMessage("No Uid");
connectionString = ";deviceside=true";
}
// Check for an MDS connection instead (BlackBerry Enterprise
// Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// logMessage("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the
// user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
// logMessage("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else {
// logMessage("no other options found, assuming device.");
// connectionString = ";deviceside=true";
}
conDesc = conFactory.getConnection(url + connectionString);
}
catch (Exception e)
{
System.out.println(e.toString() + ":" + e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if (null != conDesc)
{
try
{
HttpConnection connection = (HttpConnection) conDesc.getConnection();
// set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length",Integer.toString(data.size()));
// body content of
// post data
connection.setRequestProperty("Connection", "close");
// close
// the
// connection
// after
// success
// sending
// request
// and
// receiving
// response
// from
// the
// server
connection.setRequestProperty("Content-Type","application/json");
// we set the
// content of
// this request
// as
// application/x-www-form-urlencoded,
// because the
// post data is
// encoded as
// form-urlencoded(if
// you print the
// post data
// string, it
// will be like
// this ->
// q=remoQte&ie=UTF-8).
// now it is time to write the post data into OutputStream
OutputStream out = connection.openOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
// when this
// code is
// called,
// the post
// data
// request
// will be
// send to
// server,
// and after
// that we
// can read
// the
// response
// from the
// server if
// the
// response
// code is
// 200 (HTTP
// OK).
if (responseCode == HttpConnection.HTTP_OK)
{
// read the response from the server, if the response is
// ascii character, you can use this following code,
// otherwise, you must use array of byte instead of String
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while ((read = in.read()) != -1)
buf.append((char) read);
response = buf.toString();
}
// don’t forget to close the connection
connection.close();
}
catch (Exception e)
{
System.out.println(e.toString() + ":" + e.getMessage());
}
}
return response;
}
public boolean checkResponse(String res)
{
if(!res.equals(""))
{
if(res.charAt(0)=='{')
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
but with this code i am unable to obtain response as what the above wcf web service return
which is({"UserRegistrationResult":[{"OutputCode":"2","OutputDescription":"UserName Already Exists."}]})
Can anybody help me regarding its parsing in blackberry client end.
2.And the another code which i used is:
public class KSoapDemo extends MainScreen
{
private EditField userNametxt;
private PasswordEditField passwordTxt;
private ButtonField loginBtn;
String Username;
String Password;
public KSoapDemo()
{
userNametxt = new EditField("User Name : ", "hsharma#seasiaconsulting.com");
passwordTxt = new PasswordEditField("Password : ", "mind#123");
loginBtn = new ButtonField("Login");
add(userNametxt);
add(passwordTxt);
add(loginBtn);
loginBtn.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert("Hi Satyaseshu..!");
login();
}
});
}
private void login()
{
if (userNametxt.getTextLength() == 0 || passwordTxt.getTextLength() == 0)
{
//Dialog.alert("You must enter a username and password", );
}
else
{
String username = userNametxt.getText();
String password = passwordTxt.getText();
System.out.println("UserName... " + username);
System.out.println("Password... " + password);
boolean value = loginPArse1(username, password);
add(new LabelField("value... " + value));
}
}
public boolean onClose()
{
Dialog.alert("ADIOOO!!");
System.exit(0);
return true;
}
public boolean loginPArse1(String username, String password)
{
username=this.Username;
password=this.Password;
boolean ans = false;
String result = null;
SoapObject request = new SoapObject("http://dotnetstg.seasiaconsulting.com/","UserRegistration");
//request.addProperty("PowerValue","1000");
//request.addProperty("fromPowerUnit","kilowatts");
//request.addProperty("toPowerUnit","megawatts");
request.addProperty("userName",Username);
request.addProperty("Password", Password);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = request;
envelope.dotNet = true;
add(new LabelField("value... " + "1"));
HttpTransport ht = new HttpTransport("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters());
ht.debug = true;
add(new LabelField("value... " + "2"));
//System.out.println("connectionType is: " + connectionType);
try {
ht.call("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration", envelope);
SoapObject body = (SoapObject) envelope.bodyIn;
add(new LabelField("soap....="+body.toString()));
add(new LabelField("property count....="+body.getPropertyCount()));
// add(new LabelField("Result....="+body.getProperty("HelloWorldResult")));
//result = body.getProperty("Params").toString();
// add(new LabelField("value... " + "4"));
ans=true;
}
catch (XmlPullParserException ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
} catch (IOException ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
} catch (Exception ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
}
return ans;
}
and in return i am obtain response as net.rim.device.cldc.io.dns.DNS Exception:DNS Error
Please help me in this regard
Thanks And Regards
Pinkesh Gupta
Please have the answer for my own question helps in parsing wcf rest services developed in .net and parsed at blackberry end.
This 2 classess definitely helps in achieving the above code parsing.
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class ConnectionThread extends Thread
{
private boolean start = false;
private boolean stop = false;
private String url;
private String data;
public boolean sendResult = false;
public boolean sending = false;
private String requestMode = HttpConnection.POST;
public String responseContent;
int ch;
public void run()
{
while (true)
{
if (start == false && stop == false)
{
try
{
sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
else if (stop)
{
return;
}
else if (start)
{
http();
}
}
}
private void getResponseContent( HttpConnection conn ) throws IOException
{
InputStream is = null;
is = conn.openInputStream();
// Get the length and process the data
int len = (int) conn.getLength();
if ( len > 0 )
{
int actual = 0;
int bytesread = 0;
byte[] data = new byte[len];
while ( ( bytesread != len ) && ( actual != -1 ) )
{
actual = is.read( data, bytesread, len - bytesread );
bytesread += actual;
}
responseContent = new String (data);
}
else
{
// int ch;
while ( ( ch = is.read() ) != -1 )
{
}
}
}
private void http()
{
System.out.println( url );
HttpConnection conn = null;
OutputStream out = null;
int responseCode;
try
{
conn = (HttpConnection) Connector.open(url);
conn.setRequestMethod(requestMode);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length",Integer.toString(data.length()));
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("SOAPAction","http://dotnetstg.seasiaconsulting.com/");
out = conn.openOutputStream();
out.write(data.getBytes());
out.flush();
responseCode = conn.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
sendResult = false;
responseContent = null;
}
else
{
sendResult = true;
getResponseContent( conn );
}
start = false;
sending = false;
}
catch (IOException e)
{
start = false;
sendResult = false;
sending = false;
}
}
public void get(String url)
{
this.url = url;
this.data = "";
requestMode = HttpConnection.GET;
sendResult = false;
sending = true;
start = true;
}
public void post(String url, String data)
{
this.url = url;
this.data = data;
requestMode = HttpConnection.POST;
sendResult = false;
sending = true;
start = true;
}
public void stop()
{
stop = true;
}
}
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.AutoTextEditField;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.DateField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.MainScreen;
import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.xml.sax.SAXException;
import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.jaxp.SAXParserImpl;
import org.xml.sax.helpers.DefaultHandler;
import java.io.ByteArrayInputStream;
import com.sts.example.ConnectionThread;
import com.sts.example.ResponseHandler;
public class DemoScreen extends MainScreen
{
private ConnectionThread connThread;
private BasicEditField response = new BasicEditField("Response: ", "");
private BasicEditField xmlResponse = new BasicEditField("xml: ", "");
private ButtonField sendButton = new ButtonField("Response");
public DemoScreen(ConnectionThread connThread)
{
this.connThread = connThread;
FieldListener sendListener = new FieldListener();
sendButton.setChangeListener(sendListener);
response.setEditable( false );
xmlResponse.setEditable( false );
add(sendButton);
add(response);
add(new SeparatorField());
add(xmlResponse);
}
public boolean onClose()
{
connThread.stop();
close();
return true;
}
private String getFieldData()
{
//{"UserName":"hsharma#seasiaconsulting.com","Password":"mind#123"}
StringBuffer sb = new StringBuffer();
sb.append("{\"UserNamepinkesh.g#cisinlabs.com\",\"Password\":\"pinkesh1985\"}");
return sb.toString();
}
class FieldListener implements FieldChangeListener
{
public void fieldChanged(Field field, int context)
{
StringBuffer sb = new StringBuffer("Sending...");
connThread.post("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters(), getFieldData());
while (connThread.sending)
{
try
{
Status.show( sb.append(".").toString() );
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (connThread.sendResult)
{
Status.show("Transmission Successfull");
xmlResponse.setText( connThread.responseContent );
try {
JSONObject jsonResponse = new JSONObject(connThread.responseContent);
JSONArray jsonArray = jsonResponse.getJSONArray("UserRegistrationResult");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject result = (JSONObject)jsonArray.get(i);
add(new LabelField("OutputCode"+result.getString("OutputCode")));
add(new LabelField("OutputDescription"+result.getString("OutputDescription")));
}
}
catch (JSONException e)
{
add(new LabelField(e.getMessage().toString()));
e.printStackTrace();
}
}
else
{
Status.show("Transmission Failed");
}
}
}
}

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;
}

rms queries, find a phrase inside a text

I want to do a midlet application for save product with its bar code, product's name, product's description and price. Then it is going to be saved as it:
123123123-coca cola-soda-6.50
124512341-crystal coca-soda-7.00
well for this I have built this code:
public boolean ProductoAgregar(String dato) // add product
{
byte bytes[] = dato.getBytes();
try {
rs.addRecord(bytes, 0, bytes.length);
return true;
} catch (RecordStoreException ex) {
ex.printStackTrace();
return false;
}
}
public boolean ProductoModificar(String dato, int id) // update product
{
try
{
byte bytes[] = dato.getBytes();
rs.setRecord(id, bytes, 0, dato.length());
return true;
}
catch(Exception ex)
{
return false;
}
}
public boolean ProductoEliminar(int id)// delete product
{
try
{
rs.deleteRecord(id);
return true;
}
catch(Exception ex)
{
return false;
}
}
I don't have an idea for how to create the method for find a product (with a part of its name, or with its bar code) and what is going to return? maybe an array?
For example all products has write coca in its name (or in description) or
find a unique product with bar code.
(This is a class with I'll instance for use its methods)
you can try following code, by editing as per your usage. I am using below code for searching an item from RMS Data.
public boolean SearchRecord(String Rec, int pos )
{
String [] data = getRecordData();
Rec = Rec.substring(0,pos);
for ( int i = 0 ; i < data.length ; i++ )
{
data[i] = data[i].substring(0, pos );
if ( Rec.toString().trim().equals(data[i].toString().trim()) )
{
data = null; // System.gc();
return true;
}
}
data = null; // System.gc();
return false;
}
By Changing the value of "pos" variable you can achieve your goal.

Resources