java:get different parts of two similar strings - java

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

Related

How to Call RPGIV program from java that returns more than one record

I am calling a RPGIV program from java, the rpgiv program returnes multi record as an output parameter.
I tried the following to return all the rows returned from rpgiv.
// Define Output Data Structure
AS400DataType[] outputData =
{
new AS400Text(20), // parentOperationsItemId;
new AS400Text(10), // parentOperationsItemType;
new AS400Text(10), // parentOperationsItemSubType;
new AS400Text(20), // parentKnownbyId;
new AS400Text(10), // parentInternalStatus;
new AS400Text(1), // parentLeafIndicator;
new AS400Text(20), // childOperationsItemId;
new AS400Text(10), // childOperationsItemType;
new AS400Text(10), // childOperationsItemSubType;
new AS400Text(20), // childKnownbyId;
new AS400Text(10), // childInternalStatus;
new AS400Text(1), // childLeafIndicator;
new AS400Text(10) // InternalStatus;
};
AS400Structure [] outputDataConverter2 = new AS400Structure[3];
outputDataConverter2[0] = new AS400Structure(outputData);
outputDataConverter2[1] = new AS400Structure(outputData);
outputDataConverter2[2] = new AS400Structure(outputData);
Object[] dataInputInformation =
{
sSqlSelect,
sFetchDirection,
sOperationsItemId,
sparentOperationsItemTypeList,
sparentOperationsItemSubTpeList,
sparentInternalStatusList,
schildOperationsItemType,
schildOperationsItemSubTpeList,
schildInternalStatusList,
sLinkStatus
};
Object[] dataInputInformationControl =
{
sPosition,
new BigDecimal(sRowsFetched)
};
// Set up the parameter list
ProgramParameter[] parameterList = new ProgramParameter[4];
parameterList[0] = new ProgramParameter(7); //ReturnStatus
parameterList[1] = new ProgramParameter(inputDataConverter.toBytes(dataInputInformation)); //Input
parameterList[2] = new ProgramParameter(inputDataControlConverter.toBytes(dataInputInformationControl)); //Control
parameterList[3] = new ProgramParameter(outputDataConverter2[0].getByteLength()*3); //Output
try
{
// Set the program name and parameter list.
program.setProgram(programName, parameterList);
// Run Function
if (program.run() != true)
{
// Calling Error
AS400Message[] messagelist = program.getMessageList();
for (int i = 0; i < messagelist.length; ++i)
{
output[0].ReturnStatus += messagelist[i] + "\n";
}
}
else
{
// Set the output
output[0] = new GetPlannedRoute();
output[1] = new GetPlannedRoute();
output[2] = new GetPlannedRoute();
output[0].SetOutput(parameterList, outputDataConverter2[0]);
output[1].SetOutput(parameterList, outputDataConverter2[1]);
output[2].SetOutput(parameterList, outputDataConverter2[2]);
}
}
This is in the output class
public void SetOutput(ProgramParameter[] parameterList, AS400Structure outputPlannedRouteConverter)
{
ReturnStatus = P6Entity.CallingRPGFunction.ConvertReturnStatus(parameterList[0]);
Object[] outputData = (Object[]) outputPlannedRouteConverter.toObject(parameterList[3].getOutputData());
parentOperationsItemId = ((String) outputData[0]).trim();
parentOperationsItemType = ((String) outputData[1]).trim();
parentOperationsItemSubType = ((String) outputData[2]).trim();
parentKnownbyId = ((String) outputData[3]).trim();
parentInternalStatus = ((String) outputData[4]).trim();
parentLeafIndicator = ((String) outputData[5]).trim();
childOperationsItemId = ((String) outputData[6]).trim();
childOperationsItemType = ((String) outputData[7]).trim();
childOperationsItemSubType = ((String) outputData[8]).trim();
childKnownbyId = ((String) outputData[9]).trim();
childInternalStatus = ((String) outputData[10]).trim();
childLeafIndicator = ((String) outputData[11]).trim();
InternalStatus = ((String) outputData[12]).trim();
}
I am not sure how to define parameterList[3] to be able to receive multiple rows back or multiple data structures. And how to get a specific instance of the output parameterList[3].
The RPGIV code:
https://www.dropbox.com/s/a29wf1ft0f07sx1/functionCode.txt?dl=0
The * FetchedData Occures OCCURS(64) INZ is the output data set that I want to return to java.
Edited to show how to convert a packed value.
Let's cut this down a bit. Here is a small RPG program that has a similar structure to yours:
D V00001 DS OCCURS(64)
D F0000G 20A
D F0000H 10A
D F0000I 10A
D F0000J 20A
D F0000K 9p 0
D F0000L 1A
D F0000M 20A
D F0000N 10A
D F0000O 10A
D F0000P 20A
D F0000Q 10A
D F0000R 1A
D F0000S 10A
c *entry plist
c parm v00001
// populate the first entry
%occur(v00001) = 1;
F0000G = *ALL'1234567890';
F0000H = *ALL'A';
F0000I = *ALL'B';
F0000J = *ALL'C';
F0000K = 123456789;
F0000L = *ALL'E';
F0000M = *ALL'F';
F0000N = *ALL'G';
F0000O = *ALL'H';
F0000P = *ALL'I';
F0000Q = *ALL'J';
F0000R = *ALL'K';
F0000S = *ALL'a';
// populate the 2nd entry
%occur(v00001) = 2;
F0000G = *ALL'1234567890';
F0000H = *ALL'1234567890';
F0000I = *ALL'1234567890';
F0000J = *ALL'1234567890';
F0000K = 200;
F0000L = *ALL'1234567890';
F0000M = *ALL'1234567890';
F0000N = *ALL'1234567890';
F0000O = *ALL'1234567890';
F0000P = *ALL'1234567890';
F0000Q = *ALL'1234567890';
F0000R = *ALL'1234567890';
F0000S = *ALL'b';
// populate the third entry
%occur(v00001) = 3;
F0000G = *ALL'1234567890';
F0000H = *ALL'1234567890';
F0000I = *ALL'1234567890';
F0000J = *ALL'1234567890';
F0000K = 300;
F0000L = *ALL'1234567890';
F0000M = *ALL'1234567890';
F0000N = *ALL'1234567890';
F0000O = *ALL'1234567890';
F0000P = *ALL'1234567890';
F0000Q = *ALL'1234567890';
F0000R = *ALL'1234567890';
F0000S = *ALL'c';
// reset back to the beginning
%occur(v00001) = 1;
dump(a);
*inlr = *on;
Here is the Java (I AM NOT A Java PROGRAMMER!) that successfully reads the various 'records':
public String testSO(AS400 system, String programName) {
boolean success = false;
final int ONE_ROW_LEN = 147;
final int DS_ROWS = 64;
AS400Text dsText = new AS400Text(ONE_ROW_LEN * DS_ROWS);
AS400Text p0000g = new AS400Text(20);
AS400Text p0000h = new AS400Text(10);
AS400Text p0000i = new AS400Text(10);
AS400Text p0000j = new AS400Text(20);
int p0000k; // packed(9, 0) is 5 bytes
AS400Text p0000l = new AS400Text( 1);
AS400Text p0000m = new AS400Text(20);
AS400Text p0000n = new AS400Text(10);
AS400Text p0000o = new AS400Text(10);
AS400Text p0000p = new AS400Text(20);
AS400Text p0000q = new AS400Text(10);
AS400Text p0000r = new AS400Text( 1);
AS400Text p0000s = new AS400Text(10);
String ds = null;
String returnString = null;
try
{
ProgramCall program = new ProgramCall(system);
// Set up the parameter list
ProgramParameter[] parameterList = new ProgramParameter[1];
parameterList[0] = new ProgramParameter(ONE_ROW_LEN * DS_ROWS);
program.setProgram(programName, parameterList);
success = program.run();
if(success!=true){
AS400Message[] messagelist = program.getMessageList();
System.out.println("\nMessages received:\n");
for (int i = 0; i < messagelist.length; i++) {
System.out.println(messagelist[i]);
}
} else {
// RPG is returning a giant chunk of memory
//allBytes = parameterList[0].getOutputData();
ds = (String)dsText.toObject(parameterList[0].getOutputData());
System.out.println("ds=" + ds);
System.out.println("ds len=" + ds.length());
// Need to index our way into the block of memory
// zero-based!
int row = 0;
int x = row * ONE_ROW_LEN;
System.out.println("x=" + x);
// parse out the individual elements for this row
int len = p0000g.getByteLength();
String s0000g = ds.substring(x, x+len);
x += len;
len = p0000h.getByteLength();
String s0000h = ds.substring(x, x+len);
x += len;
len = p0000i.getByteLength();
String s0000i = ds.substring(x, x+len);
x += len;
len = p0000j.getByteLength();
String s0000j = ds.substring(x, x+len);
// this is packed(9, 0)
x += len;
len = 5;
byte[] b0000k = dsText.toBytes(ds.substring(x, x+len));
BigDecimal d0000k = (BigDecimal)new AS400PackedDecimal(9, 0).toObject(b0000k);
p0000k = d0000k.intValue();
String s0000k = d0000k.toString();
x += len;
len = p0000l.getByteLength();
String s0000l = ds.substring(x, x+len);
x += len;
len = p0000m.getByteLength();
String s0000m = ds.substring(x, x+len);
x += len;
len = p0000n.getByteLength();
String s0000n = ds.substring(x, x+len);
x += len;
len = p0000o.getByteLength();
String s0000o = ds.substring(x, x+len);
x += len;
len = p0000p.getByteLength();
String s0000p = ds.substring(x, x+len);
x += len;
len = p0000q.getByteLength();
String s0000q = ds.substring(x, x+len);
x += len;
len = p0000r.getByteLength();
String s0000r = ds.substring(x, x+len);
x += len;
len = p0000s.getByteLength();
String s0000s = ds.substring(x, x+len);
returnString = s0000s;
System.out.println("Return=" + returnString);
System.out.println("g=" + s0000g);
System.out.println("h=" + s0000h);
System.out.println("i=" + s0000i);
System.out.println("i=" + s0000i);
System.out.println("j=" + s0000j);
System.out.println("k=" + s0000k);
System.out.println("l=" + s0000l);
System.out.println("m=" + s0000m);
System.out.println("n=" + s0000n);
System.out.println("o=" + s0000o);
System.out.println("p=" + s0000p);
System.out.println("q=" + s0000q);
System.out.println("r=" + s0000r);
System.out.println("r=" + s0000s);
}
} catch (Exception e) {
System.out.println("\ne:\n");
System.out.println(e);
System.out.println("\nStack trace:\n");
e.printStackTrace();
}
return returnString;
}
The key part to understand in the Java are that with this design, Parameter.getOutputData() is returning byte[]. I am not a Java programmer, so my Java code is ugly. I cast the returned byte[] to String and assigned it as a block to ds. I then brute-forced a section of code that substrings out the individual variables one by one. If I knew more Java I'd probably have put that junk in a constructor and maybe exposed it as a List.
Having posted all that, there is no way I would operate this way with production code. I would have the IBM programmers write me a wrapper around the SuperUltimateBlockFetch - that wrapper would call SuperUltimateBlockFetch and build a result set for use by Java. They could even make it into a stored procedure. This would decouple your dependence on understanding the internals of how the RPG structure is built and make it much more natural to deal with the individual variables in the Java code. Then all you would do would be to call the stored procedure and write a while rs.next() loop.
I would suggest that you not try to pass the data as parameters.
Instead, use a data queue to pass the data back.
Have the java program create a data queue and pass it's name to the RPG program as a parameter.
The RPG program would then send the data to the queue using the QSNDDTAQ API.
When control returns to the Java program, have it read the entries from the data queue.

Need help in creating a regular expression in Java

I am trying to apply regex on a string to obtain the output in the below format.
Input string:
params=Param1{index}~[Value1|Value2|....]^Param2~[Value1|Value2|....]
Output should be in the form of Map<String,List<String>>
Eg.
Key1: Param1
Value : Value1,Value2 upto ValueN
Key2 :Param2
Value: Value1,Value2 uptoValueN
Code:
Her is the code that I am trying to do.
String textPatt = "params";
String key = textPatt.replace("/[\\[]/", "\\[").replace("/[\\]]/", "\\]");
String pattern = new String("[\\?&]" + key + "=([^&#]*)");
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(masterUrl);
List<String> paramList = new ArrayList<String>();
if (m.find()) {
String param = m.group();
if(param != null){
String[] multiParamArr = null;
if(param.indexOf("^") != -1){
multiParamArr = param.split("\\^");
}else{
multiParamArr = new String[1];
multiParamArr[0] = param;
}
if(multiParamArr != null && multiParamArr .length > 0){
Pattern refinePattern = null;
Matcher refineMatcher = null;
String paramKeyy = null;
String paramVal = null;
HashMap<String,List<String>> ParamMap = new HashMap<String,List<String>>();
List<String list = new ArrayList<String>();
for(int i=0;i<multiParamArr.length;i++){
String[] multiParam = null;
String patternKey = "^[^\\~]*";
refinePattern = Pattern.compile(patternKey);
refineMatcher = refinePattern.matcher(multiRefineArr[i]);
if(refineMatcher.find()){
paramKey = refineMatcher.group();
if(paramKey.indexOf("=") !=-1){
patternKey = patternKey.substring(patternKey.indexOf("=")+1);
}
if(paramKey.indexOf("{") !=-1){
patternKey = patternKey.substring(patternKey.indexOf("=")+1,patternKey.indexOf("{"));
}
}
if(multiParamArr[i].indexOf("|") != -1){
multiParam = multiParamArr[i].split("\\|");
int startIndex;
int endIndex;
for(int j=0;j<multiParam.length;j++){
startIndex = 0;
endIndex = 0;
ifmultiParamArr[j].indexOf("[") > -1){
startIndex = multiParamArr[j].indexOf("[")+1;
}
ifmultiParamArr[j].indexOf("]") > -1){
endIndex = multiParamArr[j].indexOf("]");
}else{
endIndex = multiParamArr[j].length();
}
paramVal = multiParamArr[j].substring(startIndex,endIndex);
}
}else{
paramVal = multiParamArr[i].substring(multiParamArr[i].indexOfmultiParamArr[i].indexOf("]"));
}
list.add(paramVal);
}
paramMap.put((paramKey,list);
}
}
}
how to apply a single regex and achieve the output
Instead of trying to create a complex regex and maintain it, you can do it simpler and in a more readable way, in a few steps:
Split on ^
Now you have an array of Strings, each of which contains one of the parameters with its values
Split each string on ~ - you'll get an array of two strings, extract from the first the Param1 (Param2 etc)
From the second you can extract the list of values by splitting on
| (pipe).

Process Large Files in Java

I have a requirement like, need to process records from a text file and insert/update in to a table. Following is the code that I have written. But when the records in the file are 50,000 its taking more than 30 minutes to process the records, and if the records are close to 80k, out of memory error is thrown. Can anyone please suggest a way to optimize the code that I have written to improve performance ?
public static String insertIntoCHG_PNT_Table(String FILE_NAME) throws NumberFormatException, IOException
{
Date DATE_INSERTED = new Date();
String strLine = "";
FileReader fr = new FileReader(FILE_NAME);
BufferedReader br = new BufferedReader(fr);
long SEQ = 0;
double consumption = 1;
String returnString = "";
CHG_PNT insertObj = null;
long KY_PREM_NO = 0;
long KY_SPT = 0;
String COD_COT_TYP = "";
String DT_EFF = "";
String TS_KY_TOT = "";
String COD_COT = "";
String ACL_VLE = "";
String ACL_QTY = "";
String WTR_VLE = "";
String WTR_QTY = "";
String SWG_VLE = "";
String SWG_QTY = "";
String CD_TYPE_ACT = "";
String DT_TERM = "";
String CD_STAT = "";
String DT_STAT = "";
String VLN_PPE_SIZ_COD = "";
String WTR_PPE_SIZ_MTD = "";
String SWG_PPE_SIZ_MTD = "";
while( (strLine = br.readLine()) != null){
/*
* Meter Serial No, Property No, Current Meter Index, Previous meter index, Consumption needs to be added
*
*
*/
String[] split = strLine.split("\\;");
KY_PREM_NO = Long.parseLong(split[0].trim());
KY_SPT = Long.parseLong(split[1].trim());
COD_COT_TYP = split[2].trim();
DT_EFF = split[3].trim();
TS_KY_TOT = split[4].trim();
COD_COT = split[5].trim();
ACL_VLE = split[6].trim();
ACL_QTY = split[7].trim();
WTR_VLE = split[8].trim();
WTR_QTY = split[9].trim();
SWG_VLE = split[10].trim();
SWG_QTY = split[11].trim();
CD_TYPE_ACT = split[12].trim();
DT_TERM = split[13].trim();
CD_STAT = split[14].trim();
DT_STAT = split[15].trim();
VLN_PPE_SIZ_COD = split[16].trim();
WTR_PPE_SIZ_MTD = split[17].trim();
SWG_PPE_SIZ_MTD = split[18].trim();
long counter = 0;
long newCounter = 0;
CHG_PNT checkRecordCount = null;
checkRecordCount = checkAndUpdateRecord(KY_PREM_NO,KY_SPT,COD_COT_TYP,TS_KY_TOT);
try {
if(checkRecordCount == null)
insertObj = new CHG_PNT();
else
insertObj = checkRecordCount;
insertObj.setKY_PREM_NO(KY_PREM_NO);
//insertObj.setSEQ_NO(SEQ);
insertObj.setKY_SPT(KY_SPT);
insertObj.setCOD_COT_TYP(COD_COT_TYP);
insertObj.setDT_EFF(DT_EFF);
insertObj.setTS_KY_TOT(TS_KY_TOT);
insertObj.setCOD_COT(COD_COT);
insertObj.setACL_VLE(Double.parseDouble(ACL_VLE));
insertObj.setACL_QTY(Double.parseDouble(ACL_QTY));
insertObj.setWTR_VLE(Double.parseDouble(WTR_VLE));
insertObj.setWTR_QTY(Double.parseDouble(WTR_QTY));
insertObj.setSWG_VLE(Double.parseDouble(SWG_VLE));
insertObj.setSWG_QTY(Double.parseDouble(SWG_QTY));
insertObj.setCD_TYPE_ACT(CD_TYPE_ACT);
insertObj.setDT_TERM(DT_TERM);
insertObj.setCD_STAT(Double.parseDouble(CD_STAT));
insertObj.setDT_STAT(DT_STAT);
insertObj.setVLN_PPE_SIZ_COD(VLN_PPE_SIZ_COD);
insertObj.setWTR_PPE_SIZ_MTD(WTR_PPE_SIZ_MTD);
insertObj.setSWG_PPE_SIZ_MTD(SWG_PPE_SIZ_MTD);
insertObj.setDATE_INSERTED(DATE_INSERTED);
if(checkRecordCount == null)
{
insertObj.setDATE_INSERTED(DATE_INSERTED);
insertObj.insert();
}
else
{
insertObj.setDATE_MODIFIED(DATE_INSERTED);
insertObj.update();
}
BSF.getObjectManager()._commitTransactionDirect(true);
}catch(Exception e)
{
String abc = e.getMessage();
}
}
fr.close();
br.close();
String localPath = FILE_NAME;
File f = new File(FILE_NAME);
String fullPath = f.getParent();
String fileName = f.getName();
String SubStr1 = new String("Processing");
int index = fullPath.lastIndexOf(SubStr1);
String path = fullPath.substring(0, index);
String destPath = path+"\\Archive\\"+fileName;
PMP_PROPERTIES.copyFile(new File(localPath),new File(destPath));
File file = new File(FILE_NAME);
file.delete();
return null;
}
There are two main problems. The first one is a performance problem - and, contrary to your intuition, the problem is the database insertion speed.
You are inserting each item in a separate transaction. You should not do that if you want your inserts to be quick. Introduce a counter variable and perform a commint only each N inserts and at the end.
int commitStep = 100;
int modCount = 0;
while() {
//... your code
modCount++;
if ( modCount % commitStep == 0 ) {
BSF.getObjectManager()._commitTransactionDirect(true);
}
}
You can read more about sql insert speed-up here: Sql insert speed up
The second problem is, possibly, file reading scalability. It will work for smaller files, but not for larger ones. This question Read large files in Java has some good answers to your problem.

How would I tidy this code into a loop in 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;
}

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