How would I tidy this code into a loop in java? - java

public class TagHandler {
private final String START = "<START ";
private final String END = "<END ";
public String handleTag(String buf, String[] attrList) {
String startPattern1 = START+attrList[0]+">";
String endPattern1 = END+attrList[0]+">";
String startPattern2 = START+attrList[1]+">";
String endPattern2 = END+attrList[1]+">";
String startPattern3 = START+attrList[2]+">";
String endPattern3 = END+attrList[2]+">";
String startPattern4 = START+attrList[3]+">";
String endPattern4 = END+attrList[3]+">";
String startPattern5 = START+attrList[4]+">";
String endPattern5 = END+attrList[4]+">";
String extract1 = new String(buf);
String extract2 = new String(buf);
String extract3 = new String(buf);
String extract4 = new String(buf);
String extract5 = new String(buf);
extract1 = extract1.substring(extract1.indexOf(startPattern1)+startPattern1.length(), extract1.indexOf(endPattern1));
extract2 = extract2.substring(extract2.indexOf(startPattern2)+startPattern2.length(), extract2.indexOf(endPattern2));
extract3 = extract3.substring(extract3.indexOf(startPattern3)+startPattern3.length(), extract3.indexOf(endPattern3));
extract4 = extract4.substring(extract4.indexOf(startPattern4)+startPattern4.length(), extract4.indexOf(endPattern4));
extract5 = extract5.substring(extract5.indexOf(startPattern5)+startPattern5.length(), extract5.indexOf(endPattern5));
String s = ("BLOPABP"+extract1) + ("\nBLOPCALL"+extract2) +("\nBLOPEXP"+extract3) +("\nBLOPHEAD"+extract4)+("\nBLOPMAJ"+extract5);
return s;
}
How would I tidy up the code above into some sort of loop? Basically I have a file that i'm reading and extract the data within the tags and I'm passing the tags into this TagHandler method and returning the extracted data as a string with the tag headers without the "< START >" and "< END TAG"> leaving only the header on the start tag.

Here you go. This should do what you want.
public class TagHandler {
private final String START = "<START ";
private final String END = "<END ";
public String handleTag(String buf, String[] attrList) {
String[] blop = {"BLOPABP", "BLOPCALL", "BLOPEXP", "BLOPHEAD", "BLOPMAJ"};
String s = "";
for (int i = 0; i < attrList.length; i++) {
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = buf.substring(buf.indexOf(startPattern)+startPattern.length(), buf.indexOf(endPattern));
s += blop[i]+extract;
if (i < attrList.length-1) {
s += "\n";
}
}
return s;
}
}
Look out for an out of bounds exception, if attrList has more than 5 elements.

You can try something like this, optimize it if you can :
public String handleTag(String buf, String[] attrList) {
StringBuilder temp = new StringBuilder();
final String[] prefix = {"BLOPABP","\nBLOPCALL","\nBLOPEXP",
"\nBLOPHEAD","\nBLOPMAJ"};
for(int i=0;i<attrList.length;i++){
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = new String(buf);
extract = extract.substring(
extract.indexOf(startPattern)+startPattern.length(),
extract.indexOf(endPattern));
temp.append(prefix[i%5]+extract);
}
return temp.toString();
}

This should work. You can replace = new ArrayList<String> with = new ArrayList<>() if you're using java 7.
private final String START = "<START ";
private final String END = "<END ";
List<String> startPatterns = new ArrayList<String>();//can use ArrayList<> instead if java 1.7
List<String> stringExtracts = new ArrayList<String>();
final String[] tags = new String[]{"BLOPABP","\nBLOPCALL","\nBLOPEXP","\nBLOPHEAD","\nBLOPMAJ"};
public String handleTag(String buf, String[] attrList) {
int numPatterns = tags.length;
String s;
String extract = new String(buf);
for(int i=0; i<numPatterns; i++){
String startPattern = START+attrList[i]+">";
startPatterns.add(startPattern);
String endPattern = END+attrList[i]+">";
endPatterns.add(endPattern);
String extract = extract.substring(extract.indexOf(startPattern)+startPattern.length(), extract.indexOf(endPattern));
stringExtracts.add(extract);
s += tags[i] + extract;
}
return s;
}
This assumes that you need access to the individual startPatterns, endPatterns and stringExtracts again, not just s. If you only need s though then discard the ArrayLists - it will work like this:
private final String START = "<START ";
private final String END = "<END ";
final String[] tags = new String[]{"BLOPABP","\nBLOPCALL","\nBLOPEXP","\nBLOPHEAD","\nBLOPMAJ"};
public String handleTag(String buf, String[] attrList) {
int numPatterns = tags.length;
String s;
String extract = new String(buf);
for(int i=0; i<numPatterns; i++){
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = extract.substring(extract.indexOf(startPattern)+startPattern.length(), extract.indexOf(endPattern));
s += tags[i] + extract;
}
return s;
}

Related

Trying to save values to class Object

I posted a question in the past but didn't get any response so I'm assuming my question wasn't clear.
Can we define new Object[3][] without defining number of columns?
Hoping following code is more readable and easy to understand.
Question:
Why is retval[0] always null?
Please help.
Thanks,
package YTesting1.YTesting1;
import org.testng.annotations.Test;
public class Test1 {
#Test
public void MyTest() {
Object[][] retval = new Object[1][];
String mm = "Hello";
String o = "World";
String s = "Yeaah";
(new Object[1])[0] = new Test2(mm, o, s);
retval[0] = new Object[1];
System.out.println("retval = " +retval[0]);
}
}
package YTesting1.YTesting1;
public class Test2 {
private String str1 = "";
private String str2 = "";
private String str3= "";
public Test2(String lstr1, String lstr2, String lstr3){
this.str1 = lstr1;
this.str2 = lstr2;
this.str3 = lstr3;
}
}
retval[0] is not null, it is assigned to an empty array of Object.
It is possible to assign to retval[0] some another array and populate it without indicating the number of columns
public static void main(String ... args) {
Object[][] retval = new Object[1][];
String mm = "Hello";
String o = "World";
String s = "Yeaah";
//(new Object[1])[0] = new Test2(mm, o, s);
retval[0] = new Object[1];
System.out.println("retval[0] = " + retval[0]);
System.out.println("retval[0][0] = " +retval[0][0]);
System.out.println("retval = " + Arrays.deepToString(retval));
retval[0] = new String[] { // 3-element string array
mm, o, s
};
System.out.println("retval[0] = " + retval[0]);
System.out.println("retval[0][0] = " +retval[0][0]);
System.out.println("retval = " + Arrays.deepToString(retval));
}
Output:
retval[0] = [Ljava.lang.Object;#5479e3f
retval[0][0] = null
retval = [[null]]
retval[0] = [Ljava.lang.String;#66133adc
retval[0][0] = Hello
retval = [[Hello, World, Yeaah]]

java:get different parts of two similar strings

Get different parts of two similar strings
example:
1.String1="bjsqzctjjzxyxgs" String2="bjqzctjjxxzxyxgs" result:String[] s3 = {"s","xx"}
2.String1="bjssdwxxjsyxgs" String2="bjsdwxxjsyxgs" result:String[] s3 = {"s"}
3.String1="bjydcrwljskjyxgs" String2="bjydcrjswlkjyxgs" result:String[] s3 = {"wljs","jswl"}
for the example1,i make the string to the char array ,then i can get the String "sqzctjj" and "qzctjjxx",but i cant get the result like the example result {"s","xx"}.
I hope some friends can guide me out.
thanks
public static Map<String,String> getPreviousStrAndLastStr(String shortCompanyName, String shortSelectCompanyName){
char[] shortCompanyNameCharArray = (shortCompanyName).toCharArray();
char[] shortSelectCompanyNameCharArray = shortSelectCompanyName.toCharArray();
Map<String,String> map = new HashMap<String,String>();
int cirNum = 0;
int previousDifIndex = 0;
int lastDifIndex = 0;
String longSplitStr = "";
String shortSplitStr = "";
if(shortCompanyNameCharArray.length>shortSelectCompanyNameCharArray.length){
cirNum = shortSelectCompanyNameCharArray.length;
longSplitStr = shortCompanyName;
shortSplitStr = shortSelectCompanyName;
}else{
cirNum = shortCompanyNameCharArray.length;
longSplitStr = shortSelectCompanyName;
shortSplitStr = shortCompanyName;
}
for(int i=0;i<cirNum;i++){
if (shortCompanyNameCharArray[i]!=shortSelectCompanyNameCharArray[i]){
System.out.println(shortCompanyNameCharArray[i]+"--------"+shortSelectCompanyNameCharArray[i]);
previousDifIndex = i;
break;
}
}
if(previousDifIndex != 0){
for(int i=0;i<cirNum;i++){
if (shortCompanyNameCharArray[shortCompanyNameCharArray.length-i-1]!=shortSelectCompanyNameCharArray[shortSelectCompanyNameCharArray.length-i-1]){
System.out.println(shortCompanyNameCharArray[shortCompanyNameCharArray.length-i-1]+"--------"+shortSelectCompanyNameCharArray[shortSelectCompanyNameCharArray.length-i-1]);
lastDifIndex =shortSplitStr.length() - i;
break;
}
if(previousDifIndex==(cirNum-i)){
lastDifIndex = shortSplitStr.length() - i;;
break;
}
}
}
String previousStr = shortSplitStr.substring(0,previousDifIndex);
String lastStr = shortSplitStr.substring(lastDifIndex,shortSplitStr.length());
String diffStr1 = longSplitStr.replace(previousStr,"").replace(lastStr,"");
String diffStr2 = shortSplitStr.replace(previousStr,"").replace(lastStr,"");
map.put("previousStr",previousStr);
map.put("lastStr",lastStr);
map.put("diffStr1",diffStr1);
map.put("diffStr2",diffStr2);
map.put("previousDifIndex",previousDifIndex+"");
map.put("lastDifIndex",lastDifIndex+"");
return map;
}
input "bjydcrwljskjyxgs" and "bjqzctjjxxzxyxgs"
output {diffStr2=sqzctjj, previousStr=bj, diffStr1=qzctjjxx, lastDifIndex=9, lastStr=zxyxgs, previousDifIndex=2}
so i want to make the diffStr1="qzctjjxx"and the diffStr2="sqzctjj" how to be
the String[] s3 = {"s","xx"}

ArrayList to parse and return JSON data

iam student and i have this class for parse and return json data and i used a string array and i want to change the string array to ArrayList but i get stuck with it how can i use ArrayList to parse and return results
this is my attempts :
public static String[] getStringsFromJson(Context context, String JsonString)
throws JSONException {
final String RESULTS = "results";
final String SUBJECT = "subject";
ArrayList<ListItem> ItemsList;
JSONObject Object = new JSONObject(JsonString);
JSONArray ItemsList = Object.getJSONArray(RESULTS);
for(int i = 0; i < ItemsList.length; i++)
{
JSONObject object = ItemsList.getJSONObject(i);
Item ci = new Item();
String subject = object.getString(SUBJECT);
ci.toString(subject);
ItemsList.add(ci);
}
Instead of parsedMovieData, use this:
List<String> parsedMovieList = new ArrayList<>(moviesArray.length());
parsedMovieList.add(popularity + " - " + poster_path + " - " + original_title);
You forgot just to get a new instance of the array list here ArrayList<MovieItem> moviesItemsList = new ArrayList<MovieItem>();
Do it like this :
public static ArrayList<MovieItem> getSimpleMovieStringsFromJson(Context context, String moviesJsonString)
throws JSONException {
final String RESULTS = "results";
final String POPULARITY = "popularity";
final String POSTER_PATH = "poster_path";
final String ORIGINAL_TITLE = "original_title";
ArrayList<MovieItem> moviesItemsList = new ArrayList<MovieItem>();
JSONObject moviesObject = new JSONObject(moviesJsonString);
JSONArray moviesItemsList = moviesObject.getJSONArray(RESULTS);
for(int i = 0; i < moviesItemsList.length; i++)
{
JSONObject object = moviesItemsList.getJSONObject(i);
MovieItem ci = new MovieItem();
String original_title = object.getString(ORIGINAL_TITLE);
ci.toString(original_title);
moviesItemsList.add(ci);
}
return moviesItemsList;
}

How to remove the quotes while converting a file from sql to tbl

Below is the code which converts the .sql file for insert statements into .tbl file. As the input file is .sql file it contains varchar(string) values inside single quotes. How can I prevent these quotes from getting in my tbl file?
Input:
INSERT INTO
post_tran(post_tran_id,tran_nr,datetime_tran_local,system_trace_audit_nr,settle_
amount_rsp,settle_tran_fee_rsp,post_tran_cust_id,prev_post_tran_id,next_post_tra
n_id,message_type,tran_postilion_originated,sink_node_name,settle_entity_id,batc
h_nr,tran_completed,tran_type,rsp_code_rsp,auth_type,auth_reason,retrieval_refer
ence_nr,settle_amount_req,settle_tran_fee_req,settle_currency_code,datetime_req,
recon_business_date,realtime_business_date,acquiring_inst_id_code) VALUES(
1,2,'2002-04-02 19:02:28','008497',4120,10, 2, 0,0,'0200', 0, 'LinkSink',
1,1,0,'01','01','00',0,'000000000102',6000,0,'840', '', '2004-02-11
12:00:00', '2004-02-11 12:00:00', '2200017000')
For example:
While processing sink_node_name, its data value should be LinkSink instead of 'LinkSink'.
public class SqlToTblCoverter {
private File source_folder = null;
private File destination_folder = null;
private String source_absolute_path = null;
private String destination_absolute_path = null;
private String absolute_file_name = null;
private String absolute_new_file_name = null;
private List<String> column_name_list = null;
private List<String> column_values_list = null;
public SqlToTblCoverter(String source_folder_name,
String destination_folder_name) {
source_folder = new File(source_folder_name);
destination_folder = new File(destination_folder_name);
source_absolute_path = source_folder.getAbsolutePath();
destination_absolute_path = destination_folder.getAbsolutePath();
column_name_list = new ArrayList<String>();
column_values_list = new ArrayList<String>();
}
public void run() throws IOException {
validateInputs();
migrateFiles();
}
private void validateInputs() {
if (source_folder.isDirectory() == false) {
System.out.println("Source must be a FOLDER");
} else if (destination_folder.isDirectory() == false) {
System.out.println("Destination must be a FOLDER");
}
}
private void migrateFiles() throws IOException {
String[] file_list = source_folder.list();
String file_name1 = file_list[0];
// System.out.println(file_name1);
String file_name2 = file_list[1];
// System.out.println(file_name2);
String f1 = migrateFileContains(file_name1);
String f2 = migrateFileContains(file_name2);
Migrator mg = new Migrator();
mg.migrate(f1, f2);
}
private String migrateFileContains(String file_name) throws IOException {
absolute_file_name = source_absolute_path + File.separator + file_name;
absolute_new_file_name = destination_absolute_path + File.separator
+ getNewFileName(file_name);
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(absolute_file_name))));
String line_info = br.readLine();
StringBuffer new_query = new StringBuffer("");
FileWriter fw = new FileWriter(new File(absolute_new_file_name));
while (line_info != null) {
String convertQuery = convertQuery(line_info);
if (convertQuery.isEmpty()) {
line_info = br.readLine();
continue;
}
new_query.append(convertQuery);
new_query.append(System.getProperty("line.separator"));
fw.write(new_query.toString());
new_query.setLength(0);
line_info = br.readLine();
}
br.close();
fw.close();
return absolute_new_file_name;
}
private String convertQuery(String query) {
String new_query = "";
if (query.startsWith("INSERT")) {
int round_bracket_start = query.indexOf('(');
int round_bracket_end = query.indexOf(')');
int round_bracket_start_after_values = query.indexOf('(',
round_bracket_end);
String query_column_name = query.substring(round_bracket_start + 1,
round_bracket_end);
String query_column_values = query.substring(
round_bracket_start_after_values + 1, query.length() - 1);
covertColumnNameList(query_column_name);
covertColumnValueList(',' + query_column_values + ',');
new_query = createNewQuery() + "\n";
}
column_name_list.clear();
column_values_list.clear();
return new_query;
}
private void covertColumnNameList(String query_column_name) {
String[] column_list = query_column_name.split(",");
for (String column_name : column_list) {
column_name_list.add(column_name);
}
}
private void covertColumnValueList(String query_column_values) {
if (query_column_values.equals(",")) {
return;
}
String column_value = null;
int comma_index = query_column_values.indexOf(',');
int next_comma_index = 0;
if (query_column_values.charAt(comma_index + 1) == '\'') {
int quote_index = query_column_values.indexOf('\'', comma_index);
int next_quote_index = query_column_values.indexOf('\'',
quote_index + 1);
next_comma_index = query_column_values.indexOf(',',
next_quote_index);
column_value = query_column_values.substring(comma_index + 2,
next_comma_index - 1);
} else {
next_comma_index = query_column_values
.indexOf(',', comma_index + 1);
column_value = query_column_values.substring(comma_index + 1,
next_comma_index);
}
column_values_list.add(column_value);
covertColumnValueList(query_column_values.substring(next_comma_index));
}
private String createNewQuery() {
StringBuffer buffer = new StringBuffer("");
if (column_name_list.size() != column_values_list.size()) {
System.out.println("Error : " + absolute_file_name);
} else {
for (int index = 0; index < column_name_list.size(); index++) {
buffer.append(createNewColumn(column_name_list.get(index),
column_values_list.get(index)));
}
}
return buffer.toString();
}
private String createNewColumn(String column_name, String column_value) {
StringBuffer buffer = new StringBuffer("");
buffer.append("[name]".trim());
buffer.append(column_name.trim());
buffer.append("[/name]=[data]".trim());
buffer.append(column_value.trim());
buffer.append("[/data]".trim());
buffer.append("\r\n");
return buffer.toString();
}
private String getNewFileName(String file_name) {
String new_file_name = "";
int dot_index = file_name.indexOf('.');
new_file_name = file_name.subSequence(0, dot_index) + ".tbl";
return new_file_name;
}
}
You can replace covertColumnValueList with below code:
private void covertColumnValueList(String query_column_values) {
String temp_val = null;
for (String col_val : query_column_values.split(",")) {
if (col_val.contains("\'")) {
temp_val = col_val.replaceAll("\'", "");
column_values_list.add(temp_val.trim());
} else
column_values_list.add(col_val.trim());
}
}
I assume you have query_column_values something like below:
String query_column_values = "1,2,'2002-04-02 19:02:28','008497',4120,10, 2, 0,0,'0200', 0, 'LinkSink', 1,1,0,'01','01','00',0,'000000000102',6000,0,'840', '', '2004-02-11 12:00:00', '2004-02-11 12:00:00', '2200017000'";
replace '' by current date: Once you populate this list, replace list value at specified index.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
column_values_list.set( 23, dateFormat.format(cal.getTime()));
The code to remove the delimiting apostrophes is there in covertColumnValueList, but it doesn't handle the case where a space precedes the apostroph. See the simple fix below.
//....
int next_comma_index = 0;
// skip space(s)
while( query_column_values.charAt(comma_index + 1) == ' ' ){
comma_index++;
}
if (query_column_values.charAt(comma_index + 1) == '\'') {
//...
private void covertColumnValueList(String query_column_values) {
if (query_column_values.equals(",")) {
return;
}
String column_value = null;
int comma_index = query_column_values.indexOf(',');
int next_comma_index = 0;
if (query_column_values.charAt(comma_index + 1) == '\'') {
int quote_index = query_column_values.indexOf('\'', comma_index);
int next_quote_index = query_column_values.indexOf('\'',
quote_index + 1);
next_comma_index = query_column_values.indexOf(',',
next_quote_index);
column_value = query_column_values.substring(comma_index + 2,
next_comma_index - 1);
column_value=column_value.replace("\'","") ;
} else {
next_comma_index = query_column_values
.indexOf(',', comma_index + 1);
column_value = query_column_values.substring(comma_index + 1,
next_comma_index);
column_value=column_value.replace("\'","") ;
}
column_values_list.add(column_value);
covertColumnValueList(query_column_values.substring(next_comma_index));
}

java macroresolver

Hello I am a newbiew to java.
I am trying to write an macroresolver I have string which is represneted as
String s = '{object.attribute}' --> result of the resolver should be 'attribute'
String prefix = '{object.'
String suffix = '}'
that was easy.
i also want to extend to use the same resolver to resolve the following
String s = 'attrName1=$attrValue1$;&attrName2=$attrValue2$;' --> result of the resolver should be attrName1=attrValue1;&attrName2=attrValue2;
String prefix = '$'
String suffix = '$'
i can have a greneralized prefix and suffix passed to the method but not sure what the logic should be.
public class StringMacro {
/**
* #param args
*/
public static void main(String args[]) {
String s = "{article.article_type}";
String prefix = "{article.";
String suffix = "}";
int prefixLength = prefix.length();
int suffixLength = suffix.length();
int startIndex = s.indexOf("{article.");
int prevEndIndex =startIndex+s.indexOf(suffix);
StringBuffer output = new StringBuffer();
while (startIndex != -1 ) {
output.append(s.substring(startIndex+prefixLength,prevEndIndex));
int endIndex = s.indexOf(suffix,startIndex);
if ( endIndex == -1 ) {
output.append(s.substring(startIndex));
break;
}
String macro = s.substring(startIndex+prefixLength,endIndex-1);
prevEndIndex = endIndex+suffixLength;
startIndex = s.indexOf(prefix, prevEndIndex);
}
System.out.println(">>>"+output);
}
}
Help Please!!!!!
this should probably do the trick.
public static void main(String args[]) {
String s = "attr1=$attr1Value$&attr2=$attr2Value$Test"String;
String prefix = "$";
String suffix = "$";
String s1 = "{obj.attr}";
String prefix1 = "{obj";
String suffix1 = "}";
int prefixIndex = 0;
int startIndex = 0;
int endIndex = 0;
Map map = new HashMap();
map.put("attr1Value", "100W");
map.put("attr2Value", "123W");
map.put("attr", "columnist");
StringBuffer buffer = new StringBuffer();
while(prefixIndex != -1){
prefixIndex = s.indexOf(prefix, prefixIndex);
endIndex = s.indexOf(suffix, prefixIndex+prefix.length());
buffer.append(s.substring(startIndex, prefixIndex));
if(endIndex == -1){
break;
}
System.out.println(s.substring(prefixIndex+prefix.length(), endIndex));
buffer.append(map.get(s.substring(prefixIndex+prefix.length(), endIndex)));
prefixIndex = s.indexOf(prefix, endIndex+suffix.length());
startIndex= endIndex+suffix.length();
}
if(prefixIndex == -1){
buffer.append(s.substring(endIndex+suffix.length()));
}
System.out.println(buffer);
}
}

Categories

Resources