public class Readparam
{
private static String method_name;
public static HashMap<String, Vector<String>> getParameters(String file_name)
{
HashMap temp_map = new HashMap();
String current_dir = System.getProperty("user.dir");
File new_file = new File(current_dir + "\\parameters\\" + file_name);
StringTokenizer stringtok = null;
StringBuffer temp_contents = new StringBuffer();
BufferedReader input = null;
try
{
input = new BufferedReader(new FileReader(new_file));
String current_line = null;
while (((current_line = input.readLine()) != null) && (current_line.length() > 0))
{
stringtok = new StringTokenizer(current_line, "(");
method_name = stringtok.nextToken();
String parsed_parameters = current_line.subSequence(current_line.indexOf("(") + 1, current_line.indexOf(")")).toString();
StringTokenizer paramtok = new StringTokenizer(parsed_parameters, ",");
String[] parsed_string = parsed_parameters.split(", ");
String parsing = method_name + "(";
for (int i = 0; i < parsed_string.length; i++)
{
String[] temp_parse = parsed_string[i].split(" ");
if (i < parsed_string.length - 1)
parsing = parsing + temp_parse[0] + ", ";
else {
parsing = parsing + temp_parse[0];
}
}
parsing = parsing + ")";
Vector temp_vector = new Vector();
for (String s : parsed_string) {
temp_vector.add(s);
}
temp_map.put(parsing, temp_vector);
}
}
catch (FileNotFoundException ex)
{
System.out.println("File not found: " + file_name);
String method_name = null;
return method_name;
}
any help on this is aprreciated
I have the last line "return method_name that does not compile
i recieve an error incompatible types, expected java.util.hashmap found java.lang.String
the last line return method_name does not compile
System.out.println("File not found: " + file_name);
HashMap<String, Vector<String>> method_name = null;
return method_name;
Since your method is of a certain type, you need to 'cast' the value that's being returned to that type.
If you are coding using Eclipse, you can just click on the little error icon, and it will offer to fix the error for you, and it will cast it for you. If you are not using Eclipse, you might consider it in the future. (NetBeans works in a similar manner)
Your method is declared to return HashMap<String, Vector<String>> (which is odd to start with - usually you'd use List rather than Vector if you're using the Java 2 collections). But then your only return statement is here:
String method_name = null;
return method_name;
That's clearly not returning a HashMap<String, Vector<String>>, is it? What do you expect that to do? You could just write
return null;
which would return a null reference as a HashMap<String, Vector<String>>. (Personally I'd just let the exception bubble up, but that's a different matter.)
(It also doesn't help that you haven't shown the end of your method, and that some of the indentation is decidedly odd.)
Related
am getting a json from the server and i managed to save it into storage,
{"FirstName":"Festus","MiddleName":"Kilaka","LastName":"Mutinda","MemberNo":"1886","IdNumber":"3125638","PayRollNumber":"87","PhoneNumber":"254743901110","EmailAddress":"FESTUS#GMAIL.COM"}
all i need is to read through it and get each variable and attach them to my strings.
i tried the code below but am getting an error.
private String str_response;
private String memberNoLabel = "";
private String nameLabel = "";
private String idNoLbl = "";
private String staffNoLbl = "";
private String emailAddLbl = "";
private String PhoneNumber = ""; //Storage.getInstance().readObject("PhoneNumber").toString();
private String AccBalanceLable = "50,500";
str_response = (String) Storage.getInstance().readObject("profile.json");
Log.p("Reading profile.json from storage.", 1);
byte[] bytes_mydetails = str_response.getBytes();
JSONParser json_mysaccos = new JSONParser();
try (Reader is_mysaccos = new InputStreamReader(new ByteArrayInputStream(bytes_mydetails), "UTF-8"))
{
Map<String, Object> map_saccos = json_mysaccos.parseJSON(is_mysaccos);
java.util.List<Map<String, Object>> objMydetails = (java.util.List<Map<String, Object>>) map_saccos.get("MemberDetails");
System.out.println("No of Details: ---------> " + objMydetails.size());
for (Map<String, Object> objDetails : objMydetails)
{
String name1 = (String) objDetails.get("FirstName");
String name2 = (String)objDetails.get("MiddleName");
String name3 = (String)objDetails.get("LastName");
nameLabel = name1+name2+name3;
memberNoLabel = (String)objDetails.get("MemberNo");
idNoLbl = (String)objDetails.get("IdNumber");
staffNoLbl = (String)objDetails.get("PayRollNumber");
PhoneNumber = (String)objDetails.get("PhoneNumber");
emailAddLbl = (String)objDetails.get("EmailAddress");
}
}
catch (Exception e)
{
System.out.println("Error # saccos: " + e);
e.printStackTrace();
}
am getting this error
Error # saccos: java.lang.NullPointerException
java.lang.NullPointerException
and it says its from the line
System.out.println("No of Details: ---------> " + objMydetails.size());
have tried all available documents and tutorials i could get, but i cant figure out this, help...
My problem is in the part where I'm doing the "if/else" conditions, when I call the function that will perform the comparisons and will define if the test passed or not and will send some information, I'm receiving null.
Problems are among the asterisks. If anyone can help me
This is my code :
public static void fxSpot_GBP_JPY(TradeData data, TradeData output) throws Exception {
if (data == null) {
fail("The input data object was not correctly filled");
}
if (output == null) {
fail("The output data object was not correctly filled");
}
//Used to set the comment, the status and update to JIRA
FieldsJSON fields = new FieldsJSON();
String assertionError = "";
List<String> inputs = new ArrayList<String>();
List<String> outputs = new ArrayList<String>();
String newDate = Utils.formatTimeZoneMinute(data.getTradeDate());
String asOfTrade = Utils.formatTimeZoneMinute(data.getAsOfTradeDate());
String executionDate = Utils.formatTimeZoneMinute(output.getExecutionDateTime());
try {
//Add the data in the list
inputs.add(data.getTransactionNumber()); outputs.add(output.getBloombergId());
inputs.add(newDate); outputs.add(output.getTradeDate());
inputs.add(asOfTrade); outputs.add(executionDate);
inputs.add(data.getSettlementDate()); outputs.add(output.getValueDate());
inputs.add(data.getTradeAmount()); outputs.add(output.getAmount2());
inputs.add(data.getCustomerAccountCounterparty()); outputs.add(output.getMiPartyId());
inputs.add(data.getPrincipalLoanAmount()); outputs.add(output.getAmount());
inputs.add(data.getSecurityPrice()); outputs.add(output.getRate());
inputs.add(data.getISOCodeOf1stCurrency()); outputs.add("BRL");//output.getCurrency2()
inputs.add(data.getISOCodeOf2ndCurrency()); outputs.add(output.getCurrency1());
//Compare values
System.out.println("-------------------");
int y = 0;
int x = 0;
for(String input : inputs) {
for(String out : outputs) {
if(y == x) {
if(input.equals(out)) {
WriterCSV.setOk("Ok");
**String comment = input + " = " + out;
fields.setComment(comment);
fields.setStatus("PASS");**
System.out.println("ok - " + input + " = " + out);
}else {
WriterCSV.setOk("not Ok");
**String comment = input + " = " + out;
fields.setComment(comment);
fields.setStatus("FAIL");**
System.out.println("not Ok - " + input + " = " + out);
}
}
x = x+1; // count of the list of output
}
y = y+1; // count of the list of inputs
x = 0; // reset to 0 the count of outputs
}
// evidence with the name and value of fields compared
WriterCSV.reportSpot_CSV(data,output);
}
Here is my test:
#Test
#Tag("compare")
public void CompareSpot() throws Exception {
//Create a list to read the CSVfile
List<DTOTradeData> dto;
//Used to get the TradeData of list dto.
DTOTradeData dtd = new DTOTradeData();
// Read a csvFile and return a list with the values to new xml
dto = CSVReader.readCSV("spot.csv");
//The xpath of xml
FileDriverSpot spot = new FileDriverSpot();
FileDriver output = new FileDriverSpotOutput();
FieldsJSON fields = new FieldsJSON();
//new xml = dataInput and the outputFile = dataOutput
TradeData dataInput = new TradeData();
TradeData dataOutput = new TradeData();
for (int i = 0; i < dto.size(); i++) {
dtd = dto.get(i); // get TradeData
dtd.getTradeData().setDriver(spot); // set the driver
if (fileExist(Setup.xmlPath + dtd.getInputFile() + ".xml")) {
dataInput = Reader.read(spot, Setup.xmlPath + dtd.getInputFile() + ".xml");
dataOutput = Reader.read(output, Setup.spotPath + dtd.getOutputFile());
try {
// make the comparison
**FunctionalTest.fxSpot_GBP_JPY(dataInput, dataOutput);**
}
catch(AssertionError e) {
String comment = e.toString();
fields.setComment(comment);
}
} else {
fail("The file: " + dtd.getTemplateFile()
+ " needs to go through the writing process before being compared.");
}
//Convert the file to base64
String inputData = UpdateTestStatus.convertToBase64(Setup.xmlPath + dtd.getInputFile() + ".xml");
String outputData = UpdateTestStatus.convertToBase64(Setup.spotPath + dtd.getOutputFile());
String evidenceCompared = UpdateTestStatus.convertToBase64(Setup.reportPath+"ReportSpot.csv");
System.out.println(UpdateTestStatus.updateTestRun(**fields.getStatus(),fields.getComment()**,
inputData,dtd.getInputFile()+ ".xml", //data of the XML and the name of the file
outputData,dtd.getOutputFile(),
evidenceCompared,"ReportSpot.csv",
Setup.testExec, dtd.getJiraId()).asString()); // ID testExecution and ID of
}
}
The test and the code under test each create a separate instance of FieldsJSON. Data set in one instance will not be visible in the other (unless the data is declared static, in which case there's no need to create instances).
You can fix this by using a single instance, either passed to the fxSpot_GBP_JPY method from the test, or returned from that method to the test.
I am getting following values in my String variable:
យោងតាមឯកឧត្តមតាំង សាមឿនលេខាសម្តេចកិត្តិព្រឹទ្ធបណ្ឌិតប៊ុន រ៉ានីហ៊ុនសែនបានប្រាប់ក្រុមអ្នក\r\nសារព័ត៌មានថា៖ក្នុងជំនួបសម្តែងការគួរសមនិងទទួលថវិការ៦រយដុល្លាអាមេរិក និងសម្ភារៈឧបករណ៍\r\nព្រមទាំងបរិក្ខារពេទ្យ មួយចំនួនពីក្រុមយុវជនកម្ពុជាជូនលោកជំទាវ អាន្នីសុខអានអនុប្រធានតំណាង\r\nដ៏ខ្ពង់ខ្ពស់សម្តេចកិត្តិព្រឹទ្ធបណ្ឌិតប៊ុន រ៉ានីហ៊ុន សែនប្រធានកាកបាទក្រហមកម្ពុជានៅទីស្នាក់ការកណ្តាល\r\nកាកបាទក្រហមកម្ពុជាអូរបែកក្អមក្នុងរាជធានីភ្នំពេញនាថ្ងៃទី២ខែកញ្ញាឆ្នាំ២០១៤។\r\n\r\nលោកជំទាវអាន្នីសុខ អានបានកោតសសើរចំពោះក្រុមយុវជនកម្ពុជាដែលបានយកថវិកានិងសម្ភារៈមកជូន\r\nកាកបាទក្រហមកម្ពុជាសកម្មភាពនេះបង្ហាញពីអោយឃើញពីបេះដូងមនុស្សធម៌នៃវប្បធម៌ចែ
in which i have \r\n with different sequence
for example:
\r\n
\r\n\r\n
\r\n\r\n\r\n\r\n
i have used following all functions none of them works, any one guide me what mistake am i doing?
private List<ContentValues> parseJsonBreakingNews(String json) throws JSONException {
List<ContentValues> result = new ArrayList<ContentValues>();
JSONArray allItems = new JSONArray(json);
JSONObject item;
for (int i = 0; i < allItems.length(); i++) {
item = allItems.getJSONObject(i);
ContentValues values = new ContentValues();
values.put(TableBreakingNews._ID, item.getInt("id"));
String x = item.getString("title_kh");
String y = item.getString("content_kh");
String title = RemoveSpecialCharacters(x);
String description = RemoveSpecialCharacters(y);
values.put(TableBreakingNews.TITLE_KH, title);
values.put(TableBreakingNews.CONTENT_KH,description);
values.put(TableBreakingNews.DATE, item.getString("dt"));
result.add(values);
}
return result;
}
private String RemoveSpecialCharacters(String JunkData)
{
JunkData = JunkData.replaceAll("\\r", "");
JunkData = JunkData.replaceAll("\\n", "");
//JunkData = JunkData.replaceAll("[\n\r]+", " ");
//JunkData = JunkData.replaceAll("[\r\n]+", " ");
//JunkData = JunkData.replaceAll("\\r", "2222222222222");
//JunkData = JunkData.replaceAll("\\n", "111111111111");
//JunkData = JunkData.replaceAll("\\r\\n", "0000000000000000");
// String newLine = System.getProperty("line.separator");
//JunkData = JunkData.replace(newLine, "");
//JunkData = JunkData.replace('\n', '');
//JunkData = RemoveLineTerminationCharacters(JunkData);
//JunkData = RemoveLineTabs(JunkData);
return JunkData;
}
any help would be appreciated.
I can't see the whole code, but i think your problem is the reference from this String, have a look at my test:
Maybe you are calling your method but not updating your real reference of the object.
I don't know exactly what is your problem. if you could, please explain better what you want.
--- Edited ----
Try your method this way:
private String removeSpecialCharacters(String junkData) {
junkData = junkData.replaceAll("(\r\n|\n)", "");
return junkData;
}
Try
replace("\n", "");
or
private static final String newLine = System.getProperty("line.separator");
replace(newline, "");
Something like that should work for you
I built a HashMap in a class like so:
public static HashMap<String, String> makeMap(String file) {
HashMap wordMap = new HashMap<String, String>();
try {
Scanner dictionFile = new Scanner(new FileInputStream(file));
while(dictionFile.hasNextLine()) {
String[] values = new String[2];
values = dictionFile.nextLine().split(",");
wordMap.put(values[0], values[1]);
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
return wordMap;
}
I then call my makeMao function as follows:
HashMap dictionaryMap = Maintainance.makeMap("dictionary.txt");
String button = e.getActionCommand();
String homeUrl = "http://www.catb.org/jargon/html/";
String glossUrl = "http://www.catb.org/jargon/html/go01.html";
String searchedValue;
String completeUrl;
URL searchedUrl;
String msgPart1 = "The word you are searching for cannot be found. ";
String msgPart2 = "You are being rerouted to the glossary.";
String message = msgPart1 + msgPart2;
String title = "word Not Found";
if (button == "Search") {
String searchKey = textField.getText();
searchedValue = dictionaryMap.get(searchKey);
I cannot figure out why it is giving me the error saying:incompatible types it is pointing at my searchKey variable inside of my searchedValue statement. required is String and found is Object.
if (button == "Search")
In your above code its wrong , in Java String are compare as
if(button.equals("Search"))
Referrence
You should type-caste map
HashMap wordMap = new HashMap();
to
Map<Object,Object> wordMap =new HashMap<Object,Object>();
Now in your code
String searchKey = textField.getText();
searchedValue = dictionaryMap.get(searchKey);
I think your dicionarymap is returning an Object but you are setting it to a String.You will need to convert an Object to String first.
For example: { "primary:title":"Little Red Riding Hood"}
My Parser in Java (Android) is always getting stuck because of the colon between primary and title. I can parse anything else with ease, I just need help in this.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView txtViewParsedValue;
private JSONObject jsonObject;
private JSONArray jsonArray;
String [] titles, links, mediaDescriptions, mediaCredits, descriptions, dcCreators, pubDates, categories;
String [] permalinks, texts; // guid
String [] rels, hrefs;
String [] urls, media, heights, widths; // media:content
String strParsedValue = "";
private String strJSONValue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
strJSONValue = readRawTextFile(this, R.raw.jsonextract);
txtViewParsedValue = (TextView) findViewById(R.id.text_view_1);
try {
parseJSON();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseJSON() throws JSONException
{
txtViewParsedValue.setText("Parse 1");
jsonObject = new JSONObject(strJSONValue);
jsonArray = jsonObject.getJSONArray("item");
titles = new String[jsonArray.length()];
links = new String[jsonArray.length()];
permalinks = new String[jsonArray.length()];
texts = new String[jsonArray.length()];
mediaDescriptions = new String[jsonArray.length()];
mediaCredits = new String[jsonArray.length()];
descriptions = new String[jsonArray.length()];
dcCreators = new String[jsonArray.length()];
pubDates = new String[jsonArray.length()];
categories = new String[jsonArray.length()];
txtViewParsedValue.setText("Parse 2");
for (int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
titles[i] = object.getString("title");
links[i] = object.getString("link");
JSONObject guidObj = object.getJSONObject("guid");
permalinks[i] = guidObj.getString("isPermaLink");
texts[i] = guidObj.getString("text");
//mediaDescriptions[i] = object.getString("media:description");
//mediaCredits[i] = object.getString("media:credit");
// *** THE PARSER FAILS IF THE COMMENTED LINES ARE IMPLEMENTED BECAUSE
// OF THE : IN BETWEEN THE NAMES ***
descriptions[i] = object.getString("description");
//dcCreators[i] = object.getString("dc:creator");
pubDates[i] = object.getString("pubDate");
categories[i] = object.getString("category");
}
for (int i=0; i<jsonArray.length(); i++)
{
strParsedValue += "\nTitle: " + titles[i];
strParsedValue += "\nLink: " + links[i];
strParsedValue += "\nPermalink: " + permalinks[i];
strParsedValue += "\nText: " + texts[i];
strParsedValue += "\nMedia Description: " + mediaDescriptions[i];
strParsedValue += "\nMedia Credit: " + mediaCredits[i];
strParsedValue += "\nDescription: " + descriptions[i];
strParsedValue += "\nDC Creator: " + dcCreators[i];
strParsedValue += "\nPublication Date: " + pubDates[i];
strParsedValue += "\nCategory: " + categories[i];
strParsedValue += "\n";
}
txtViewParsedValue.setText(strParsedValue);
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
//text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
For one, and to answer your question, there is no issue with JSONObject and the org.json.* classes parsing keys with colons in them if they're properly formed. The following unit test passed which means it was able to parse your example scenario:
public void testParsingKeysWithColons() throws JSONException {
String raw = "{ \"primary:title\":\"Little Red Riding Hood\"}";
JSONObject obj = new JSONObject(raw);
String primaryTitle = obj.getString("primary:title");
assertEquals("Little Red Riding Hood", primaryTitle);
}
Another suggestion is that using arrays of Strings for your data is clumsy and you'd be much better organized using a data structure to represent your objects. Instead of string arrays for titles, links, descriptions; use an object that has these properties and make a list of the objects. For example:
public class MyDataStructure {
public String title;
public String primaryTitle;
public String link;
public String mediaDescription;
public static class Keys {
public static String title = "title";
public static String primaryTitle = "primary:title";
public static String link = "link";
public static String mediaDescription = "media:description";
}
}
And then you can make a "translator" class that does all the parsing for you and returns a list of your object. This is much easier to work with and keep track of. You never have to think about data misaligning or having more or less data in one of your arrays than you expected. You also have a much easier time testing where the problem is if your input data is missing anything or any of your json is malformed.
public class MyDataStructureTranslator {
public static List<MyDataStructure> parseJson(String rawJsonData) throws JSONException {
List<MyDataStructure> list = new ArrayList<MyDataStructure>();
JSONObject obj = new JSONObject(rawJsonData);
JSONArray arr = obj.getJSONArray("item");
for(int i = 0; i < arr.length(); i++) {
JSONObject current = arr.getJSONObject(i);
MyDataStructure item = new MyDataStructure();
item.title = current.getString(MyDataStructure.Keys.title);
item.primaryTitle = current.getString(MyDataStructure.Keys.primaryTitle);
item.link = current.getString(MyDataStructure.Keys.link);
item.mediaDescription = current.getString(MyDataStructure.Keys.mediaDescription);
list.add(item);
}
return list;
}
}
Since Java identifiers cannot have colons, just specify a json property name that maps to the exact json name like:
#JsonProperty("primary:title")
public String primaryTitle;