How to make simple dicitonary J2ME - dictionary

I am beginner in JavaME. I'd like to make simple dicitionary. The source data is placed on "data.txt" file in "res" directory. The structure is like this:
#apple=kind of fruit;
#spinach=kind of vegetable;
The flow is so simple. User enters word that he want to search in a text field, e.g "apple", system take the user input, read the "data.txt", search the matched word in it, take corresponding word, and display it to another textfield/textbox.
I've managed to read whole "data.txt" using this code..
private String readDataText() {
InputStream is = getClass().getResourceAsStream("data.txt");
try {
StringBuffer sb = new StringBuffer();
int chr, i=0;
while ((chr = is.read()) != -1)
sb.append((char) chr);
return sb.toString();
}
catch (Exception e) {
}
return null;
}
but I still dont know how to split it, find the matched word with the user input and take corresponding word. Hope somebody willing to share his/her knowledge to help me..

Basically you want something like this:
private String readDataText() {
InputStream is = getClass().getResourceAsStream("data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
try {
while ((line = br.readLine()) != null)
{
String[] split = line.split("=");
if (split[0].equals("#someFruit"))
return split[1];
}
}
catch (Exception e) {}
return null;
}
Read the line using a BufferedReader, no need to handle single chars.
Split the line by the = token
Check if the key in the dictionary is the wanted key, if so, return the value.

Related

How to logically iterate through records using DataReader and then do something at each iteration

Please bear with me as I'm rather new to this.
I'm trying to iterate through a recordset using DataReader object, and do something at each iteration, but it doesn't seem to be getting passed the first record. I essentially want to look at each record and then assign a specific image to a specified location based on the data in a column in the recordset.
I'm using Visual Studio 2019 and using OleDataReader to read Access table. I've got the command object working properly, just can't seem to get passed the first record.
this is the method definition in my class
//Giving string variable names to the virtual paths of the images
private string whitePallet = "~/images/White.jpg";
private string redPallet = "~/images/Red.jpg";
private string bluePallet = "~/images/Blue.jpg";
private string blackPallet = "~/images/Black.jpg";
private string greenPallet = "~/images/Green.jpg";
private string racetrack = "~/images/Racetrack.jpeg";
public string Racetrack { get => racetrack; set => racetrack = value; }
public string OpenConnection(string connectString, String selectString)
{
using (OleDbConnection cn = new OleDbConnection(connectString))
{
cn.Open(); //Open the connection.
OleDbCommand cmd = new OleDbCommand(selectString, cn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string pallet;
if (reader["Status"].ToString() == "Blocked Location")
{
pallet = blackPallet;
return pallet;
}
if (reader["Status"].ToString() == "AP Purge")
{
pallet = redPallet;
return pallet;
}
if (reader["Status"].ToString() == "Open")
{
pallet = whitePallet;
return pallet;
}
if (reader["Status"].ToString() == "Order Complete")
{
pallet = greenPallet;
return pallet;
}
if (reader["Status"].ToString() == "Pallet Full")
{
pallet = bluePallet;
return pallet;
}
}
//Close the reader and the related connection.
reader.Close();
return null;
}
}
this is the instantiation of the class/method
'''
Definitions defs = new Definitions();
Image imgRacetrack = Image.FromFile(Server.MapPath(defs.Racetrack));
//Creating image panel to draw upon using w/h of racetrack image
Image img = new Bitmap(imgRacetrack.Width, imgRacetrack.Height);
using (Graphics gr = Graphics.FromImage(img))
{
//Background image
gr.DrawImage(imgRacetrack, new Point(0, 0));
//Defining the points on the left side:
Point p1 = new Point(125, 50);
Image imgPallet = Image.FromFile(Server.MapPath(defs.OpenConnection(connectString,selectString)));
gr.DrawImage(imgPallet, p1);
Point p2 = new Point(125, 100);
Image imgPallet2 = enter code hereImage.FromFile(Server.MapPath(defs.OpenConnection(connectString, selectString)));
gr.DrawImage(imgPallet2, p2);
}
I'm expecting to iterate through each record and then place the image with the correct color into the correct position, but it's only giving the results to each point/location based on the very first record only. What's wrong with my logic??
You declare pallet string pallet; then have several if statements in which you return pallet;.
First, you want to return a string, but you're doing
pallet = blackPallet; // pallet will not be a string.
pallet = "blackPallet"; // pallet will be a string.
Second, when you say return..., you leave the method; you don't continue after that, you are saying you are done - return this value and stop.
So you need to read the value from each row and store them, then return the collection of values. Then you can loop through the collection and plug in each value as needed.
That's one way. I didn't study what you have in complete detail so there might be a better way. Hope that's enough for now.

With OpenCSV, how do I append to existing CSV using a MappingStrategy?

With OpenCSV, how do I append to existing CSV using a MappingStrategy? There are lots of examples I could find where NOT using a Bean mapping stategy BUT I like the dynamic nature of the column mapping with bean strategy and would like to get it working this way. Here is my code, which just rewrites the single line to CSV file instead of appending.
How can I fix this? Using OpenCSV 4.5 . Note: I set my FileWriter for append=true . This scenario is not working as I expected. Re-running this method simply results in over-writing the entire file with a header and a single row.
public void addRowToCSV(PerfMetric rowData) {
File file = new File(PerfTestMetric.CSV_FILE_PATH);
try {
CSVWriter writer = new CSVWriter(new FileWriter(file, true));
CustomCSVMappingStrategy<PerfMetric> mappingStrategy
= new CustomCSVMappingStrategy<>();
mappingStrategy.setType(PerfMetric.class);
StatefulBeanToCsv<PerfMetric> beanToCsv
= new StatefulBeanToCsvBuilder<PerfMetric>(writer)
.withMappingStrategy(mappingStrategy)
.withSeparator(',')
.withApplyQuotesToAll(false)
.build();
try {
beanToCsv.write(rowData);
} catch (CsvDataTypeMismatchException e) {
e.printStackTrace();
} catch (CsvRequiredFieldEmptyException e) {
e.printStackTrace();
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Or, is the usual pattern to load all rows into a List and then re-write entire file? I was able to get it to work by writing two MappingStrategy mapping strategies and then conditionally using them with a if-file-exists but doing it that way leaves me with a "Unchecked assignment" warning in my code. Not ideal; hoping for an elegant solution?
I've updated OpenCSV to version 5.1 and got it working. In my case I needed the CSV headers to have a specific name and position, so I'm using both #CsvBindByName and #CsvBindByPosition, and needed to create a custom MappingStrategy to get it working.
Later, I needed to edit the MappingStrategy to enable appending, so when it's in Appending mode I don't need to generate a CSV header.
public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
private boolean useHeader=true;
public CustomMappingStrategy(){
}
public CustomMappingStrategy(boolean useHeader) {
this.useHeader = useHeader;
}
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
final int numColumns = FieldUtils.getAllFields(bean.getClass()).length;
super.setColumnMapping(new String[numColumns]);
if (numColumns == -1) {
return super.generateHeader(bean);
}
String[] header = new String[numColumns];
if(!useHeader){
return ArrayUtils.EMPTY_STRING_ARRAY;
}
BeanField<T, Integer> beanField;
for (int i = 0; i < numColumns; i++){
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField<T, Integer> beanField){
if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0){
return StringUtils.EMPTY;
}
//return value of CsvBindByName annotation
final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
Now if you use the default constructor it'll add the header to the generated CSV, and using a boolean you can tell it to add a header or to ignore it.
I never found an answer to this question and so what I ended up doing was doing a branch if-condition where .csv file exists or not. If file exists I used MappingStrategyWithoutHeader strategy, and if file didn't yet exist, I used MappingStrategyWithHeader strategy. Not ideal, but I got it working.

saving document in space with blank character in alfresco

I work with alfresco 4.0
I have a problem to save document in special space in alfresco named in arabic language.
for this example I didn't have problem :
/app:company_home/cm:تجربة
but I have problem when the space witch is created in alfresco is named in arabic language and have blank character . like this :
/app:company_home/cm:تجربة ثانية
in this case I can't save document in alfresco
updated :
also I have the same problem when I have a folder named in english and have escape character like this :
His Excellency the Secretary
Reporter Secretariat
this is the document to save document in alfresco
public String saveDocument(File file, String name, String folderName, String userName, String pwd, String code)
throws Exception {
File file_BC = file;
try {
BarCodeEngine barCodeEngine = new BarCodeEngine(file, code);
file_BC = barCodeEngine.setBarCode();
} catch (Exception e) {
e.printStackTrace();
}
byte[] contentByte = IOUtils.toByteArray(new FileInputStream(file_BC));
// Start the session
AuthenticationUtils.startSession(userName, pwd);
try {
// Create a reference to the parent where we want to create content
Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
ParentReference companyHomeParent = new ParentReference(storeRef, null, folderName, Constants.ASSOC_CONTAINS, null);
// Assign name
companyHomeParent.setChildName("cm:" + name);
// Construct CML statement to create content node
// Note: Assign "1" as a local id, so we can refer to it in subsequent
// CML statements within the same CML block
NamedValue[] contentProps = new NamedValue[1];
contentProps[0] = Utils.createNamedValue(Constants.PROP_NAME, name);
CMLCreate create = new CMLCreate("1", companyHomeParent, null, null, null, Constants.TYPE_CONTENT, contentProps);
// Construct CML statement to add titled aspect
NamedValue[] titledProps = new NamedValue[2];
titledProps[0] = Utils.createNamedValue(Constants.PROP_TITLE, name);
titledProps[1] = Utils.createNamedValue(Constants.PROP_DESCRIPTION, name);
CMLAddAspect addAspect = new CMLAddAspect(Constants.ASPECT_TITLED, titledProps, null, "1");
// Construct CML Block
CML cml = new CML();
cml.setCreate(new CMLCreate[] { create });
cml.setAddAspect(new CMLAddAspect[] { addAspect });
// Issue CML statement via Repository Web Service and retrieve result
// Note: Batching of multiple statements into a single web call
UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml);
Reference content = result[0].getDestination();
// Write some content
ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
//String text = "The quick brown fox jumps over the lazy dog";
ContentFormat contentFormat = new ContentFormat("text/plain", "UTF-8");
Content contentRef = contentService.write(content, Constants.PROP_CONTENT, contentByte, contentFormat);
System.out.println("Document are created successfully. UID:= " + content.getUuid());
return content.getUuid();
} catch (Throwable e) {
System.out.println(e.toString());
} finally {
// End the session
AuthenticationUtils.endSession();
//System.exit(0);
}
return null;
}
I try to replace espace with this character : + without success
saveAttachement(file,
fileName +
System.currentTimeMillis(), container.replace(" ","+"),
USER_NAME, PASSWORD,
code);
this is the old container with espace
/app:company_home/cm:His Excellency the Secretary/cm:Reporter Secretariat
and this is the container with +
/app:company_home/cm:His+Excellency+the Secretary/cm:Reporter+Secretariat
in alfresco's log I didn't find any error
Try encoding your folderName with ISO9075.encode(folderName).
Lucene search syntax needs encoding of spaces using ISO9075. I thik this is what happens somewhere behind the scenes of your ParentReference usage.

How to show HTTP response in Object Choice Field in Blackberry

I am reading a response from server using this code.
public static String getContentString(HttpConnection Connection) throws IOException
{
String Entity=null;
InputStream inputStream;
inputStream = Connection.openInputStream();//May give network io
StringBuffer buf = new StringBuffer();
int c;
while ((c = inputStream.read()) != -1)
{
buf.append((char) c);
}
//Response Formation
try
{
Entity = buf.toString();
return Entity;
}
catch(NullPointerException e)
{
Entity = null;
return Entity;
}
}
I need to show this Entity in object choice field.
For example:
suppose i get response Entity=ThisIsGoingToGood
then, I need to show below way in object choice drop down list.
This
Is
Going
To
Good
Please tell me how to achieve this.
This solution assumes:
The Camel Case format of your strings will always start with an upper case letter.
Only one upper case character in a row is used, even if the word is an acronym. For example, "HTTP response" would be written as "HttpResponse".
public static Vector getContentStrings(HttpConnection connection) throws IOException {
Vector words = new Vector();
InputStream inputStream = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int c;
while ((c = inputStream.read()) != -1)
{
char character = (char)c;
if (CharacterUtilities.isUpperCase(character)) {
// upper case -> new word
if (buf.length() > 0) {
words.addElement(buf.toString());
buf = new StringBuffer();
}
}
buf.append(character);
}
// add the last word
words.addElement(buf.toString());
return words;
}
Then, you'll have a nice Vector full of the choices for your ObjectChoiceField. You can then insert() them, as shown in Signare's answer.
Note: always remember to close your streams, too. I've leave it to you to decide when you're really finished with it, though.
With ref from Nate's Answer- try this -
ObjectListField ol = new ObjectListField(ObjectListField.ELLIPSIS);
ol.setSize(words.size()); //Where words is the vector
for (int i = 0; i < size; i++)
{
ol.insert(i, words.elementAt(i));
}
add(ol);

how can we store a html page into sqlite in blackberry on memory card / phone memory?

Below code specifies that we we can make http connection in blackberry and how to store html page as a string?
I am doing this but I am able to get that http request but when I get response i.e http_ok it is not correct so that I can save text oh html as a string and I can further store that into sqlite.
LabelField title = new LabelField("SQLite Create Database Sample",
LabelField.ELLIPSIS |
LabelField.USE_ALL_WIDTH);
setTitle(title);
add(new RichTextField("Creating a database."));
argURL="https://www.google.com:80";
try {
connDesc = connFact.getConnection(argURL);
if (connDesc != null) {
httpConn = (HttpConnection) connDesc.getConnection();
// //Send Data on this connection
// httpConn.setRequestMethod(HttpConnection.GET);
// //Server Response
StringBuffer strBuffer = new StringBuffer();
inStream = httpConn.openInputStream();
int chr;
int retResponseCode = httpConn.getResponseCode();
if (retResponseCode == HttpConnection.HTTP_OK) {
if (inStream != null) {
while ((chr = inStream.read()) != -1) {
strBuffer.append((char) chr);
}
serverResponceStr = strBuffer.toString();
// appLe.alertForms.get_userWaitAlertForm().append("\n"+serverResponceStr);
//returnCode = gprsConstants.retCodeSuccess;
}
} else {
//returnCode = gprsConstants.retCodeNOK;
}
}
} catch (Exception excp) {
//returnCode = gprsConstants.retCodeDisconn;
excp.printStackTrace();
} `enter code here`
The code does not perform any database functionality, however I tested and it does successfully perform an HttpRequest to an external URL. The data that comes back is based on the response of the server you are making the request to.
The code I used can be found here:
http://snipt.org/vrl7
The only modifications is to keep a running summary of various events, and the response is displayed in the RichTextField. Basically, this looks to be working as intended, and the resulting String should be able to be saved however you see fit; though you may need to be cautious of encoding when saving to a database so that special characters are not lost or misinterpreted.

Resources