problem in recognizing duplicated code in the line bellow - java

I have trouble finding which part of the code is duplicated and how to fix it ?
try {
String template = new String(sourceTemplate);
// Substitute for %CODE%
int templateSplitBegin = template.indexOf("%CODE%");
int templateSplitEnd = templateSplitBegin + 6;
String templatePartOne = new String(
template.substring(0, templateSplitBegin));
String templatePartTwo = new String(
template.substring(templateSplitEnd, template.length()));
code = new String(reqId);
template = new String(templatePartOne + code + templatePartTwo);
// Substitute for %ALTCODE%
templateSplitBegin = template.indexOf("%ALTCODE%");
templateSplitEnd = templateSplitBegin + 9;
templatePartOne = new String(
template.substring(0, templateSplitBegin));
templatePartTwo = new String(
template.substring(templateSplitEnd, template.length()));
altcode = code.substring(0, 5) + "-" + code.substring(5, 8);
out.print(templatePartOne + altcode + templatePartTwo);
} catch (Exception e) {
System.out.println("Error in substitute()");
}

Try making a method with (String template, String splitBy, int offset) as parameters.
also, you can try using stringBegin = template.split(splitBy)[0] and stringEnd = template.split(splitBy)[1] instead of using indexOf() and then substring()

this two parts are duplicated. you can make a method to process the string
try {
String template = new String(sourceTemplate);
// Substitute for %CODE%
code = new String(reqId);
template = processString(template, 6, "%CODE%", code);
// Substitute for %ALTCODE%
altcode = code.substring(0, 5) + "-" + code.substring(5, 8);
template = processString(template, 9, "%ALTCODE%", altcode);
out.print(template);
} catch (Exception e) {
}
private String processString(String template, int length, String code, String mid) {
int templateSplitBegin = template.indexOf(code);
int templateSplitEnd = templateSplitBegin + len;
String templatePartOne = new String(
template.substring(0, templateSplitBegin));
String templatePartTwo = new String(
template.substring(templateSplitEnd, template.length()));
return new String(templatePartOne + mid + templatePartTwo);
}

Related

How to Verify Mobile no and email id from Secure QR code of Aadhaar card

Official Document for How to Read QR code data from Secure QR code of UIDAI Aadhaar card: https://uidai.gov.in/images/resource/User_manulal_QR_Code_15032019.pdf
Have used zxing scanner to scan Secure QR code,
And was able to get details of aadhar card with the help of follow project in Github:
https://github.com/dimagi/AadharUID
Some how I figured out how to extract photo and bit_indicator_value from converted byte array with the help of instructions on document
But I am unable to get hashed exact hashed value of email and mobile from Secure QR code of Aadhar card byte array to verify
I am bit confused from this line of above mentioned document in page no 6:
Post getting signature value, check the value of
Email_mobile_present_bit_indicator_value:
if its 3 then first read mobile from index (Byte array length – 1-256) and then email from index (Byte array length – 1- 256- 32) in
reverse order. Each value will be of fix size of 32 byte.
If Email_mobile_present_bit_indicator_value is 1 then only mobile
is present.
If Email_mobile_present_bit_indicator_value is 2 then only email is
present.
If Email_mobile_present_bit_indicator_value is 0 then no mobile or
email present.
Email and Mobile value will available in byte. Convert into Hexadecimal
String.
.
I have also prepared last step in document page no 6 but the users mobile/email hash value and documents mobile/email byte arrays hash value never matches
Code snippet:
public ScanResult(String input) {
rawString = input;
// copied from http://www.java-samples.com/showtutorial.php?tutorialid=152
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document dom;
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// Replace </?xml... with <?xml...
if (input.startsWith("</?")) {
input = input.replaceFirst("</\\?", "<?");
}
// Replace <?xml...?"> with <?xml..."?>
input = input.replaceFirst("^<\\?xml ([^>]+)\\?\">", "<?xml $1\"?>");
//parse using builder to get DOM representation of the XML file
dom = db.parse(new ByteArrayInputStream(input.getBytes("UTF-8")));
} catch (ParserConfigurationException | SAXException | IOException e) {
dom = null;
}
if (rawString.matches("[0-9]*")) {
type = QR_CODE_TYPE_SECURE;
byte[] msgInBytes = null;
try {
msgInBytes = decompressByteArray(new BigInteger(rawString).toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
if (msgInBytes != null) {
int[] delimiters = locateDelimiters(msgInBytes);
String referenceId = getValueInRange(msgInBytes, delimiters[0] + 1, delimiters[1]);
uid = referenceId.substring(0, 4);
name = getValueInRange(msgInBytes, delimiters[1] + 1, delimiters[2]);
dob = formatDate(getValueInRange(msgInBytes, delimiters[2] + 1, delimiters[3]),
new String[] {"dd-MM-yyyy", "dd/MM/yyyy"});
yob = dob.substring(0, 4);
gender = getValueInRange(msgInBytes, delimiters[3] + 1, delimiters[4]);
co = getValueInRange(msgInBytes, delimiters[4] + 1, delimiters[5]);
dist = getValueInRange(msgInBytes, delimiters[5] + 1, delimiters[6]);
lm = getValueInRange(msgInBytes, delimiters[6] + 1, delimiters[7]);
house = getValueInRange(msgInBytes, delimiters[7] + 1, delimiters[8]);
loc = getValueInRange(msgInBytes, delimiters[8] + 1, delimiters[9]);
pc = getValueInRange(msgInBytes, delimiters[9] + 1, delimiters[10]);
po = getValueInRange(msgInBytes, delimiters[10] + 1, delimiters[11]);
state = getValueInRange(msgInBytes, delimiters[11] + 1, delimiters[12]);
street = getValueInRange(msgInBytes, delimiters[12] + 1, delimiters[13]);
subdist = getValueInRange(msgInBytes, delimiters[13] + 1, delimiters[14]);
vtc = getValueInRange(msgInBytes, delimiters[14] + 1, delimiters[15]);
statusCode = STATUS_SUCCESS;
} else {
statusCode = STATUS_PARSE_ERROR;
uid = "";
name = "";
gender = "";
yob = "";
co = "";
house = "";
street = "";
lm = "";
loc = "";
vtc = "";
po = "";
dist = "";
subdist = "";
state = "";
pc = "";
dob = "";
}
} else {
type = QR_CODE_TYPE_UNKNOWN;
statusCode = STATUS_PARSE_ERROR;
uid = "";
name = "";
gender = "";
yob = "";
co = "";
house = "";
street = "";
lm = "";
loc = "";
vtc = "";
po = "";
dist = "";
subdist = "";
state = "";
pc = "";
dob = "";
}
dobGuess = getDobGuess(dob, yob);
statusText = getStatusText(statusCode);
}
private static int[] locateDelimiters(byte[] msgInBytes) {
int[] delimiters = new int[NUMBER_OF_PARAMS_IN_SECURE_QR_CODE + 1];
int index = 0;
int delimiterIndex;
for (int i = 0; i <= NUMBER_OF_PARAMS_IN_SECURE_QR_CODE; i++) {
delimiterIndex = getNextDelimiterIndex(msgInBytes, index);
delimiters[i] = delimiterIndex;
index = delimiterIndex + 1;
}
return delimiters;
}
private static String getValueInRange(byte[] msgInBytes, int start, int end) {
return new String(Arrays.copyOfRange(msgInBytes, start, end), Charset.forName("ISO-8859-1"));
}
private static int getNextDelimiterIndex(byte[] msgInBytes, int index) {
int i = index;
for (; i < msgInBytes.length; i++) {
if (msgInBytes[i] == -1) {
break;
}
}
return i;
}
private static byte[] decompressByteArray(byte[] bytes) throws IOException {
java.io.ByteArrayInputStream bytein = new ByteArrayInputStream(bytes);
java.util.zip.GZIPInputStream gzin = new GZIPInputStream(bytein);
java.io.ByteArrayOutputStream byteout = new ByteArrayOutputStream();
int res = 0;
byte buf[] = new byte[1024];
while (res >= 0) {
res = gzin.read(buf, 0, buf.length);
if (res > 0) {
byteout.write(buf, 0, res);
}
}
return byteout.toByteArray();
}
private String formatDate(String rawDateString, String[] possibleFormats) {
if (rawDateString.equals("")) {
return "";
}
SimpleDateFormat toFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
ParseException parseException = null;
for (String fromFormatPattern : possibleFormats) {
try {
SimpleDateFormat fromFormat = new SimpleDateFormat(fromFormatPattern);
date = fromFormat.parse(rawDateString);
break;
} catch (ParseException e) {
parseException = e;
}
}
if (date != null) {
return toFormat.format(date);
} else if (parseException != null) {
System.err.println("Expected dob to be in dd/mm/yyyy or yyyy-mm-dd format, got " + rawDateString);
return rawDateString;
} else {
throw new AssertionError("This code is unreachable");
}
}
#NonNull
protected String formatGender(String gender) throws ParseException {
String lowercaseGender = gender.toLowerCase();
if (lowercaseGender.equals("male") || lowercaseGender.equals("m")) {
return "M";
} else if (lowercaseGender.equals("female") || lowercaseGender.equals("f")) {
return "F";
} else if (lowercaseGender.equals("other") || lowercaseGender.equals("o")) {
return "O";
} else {
throw new ParseException("404 gender not found", 0);
}
}
#NonNull
private String getStatusText(int statusCode) {
switch (statusCode) {
case ScanResult.STATUS_SUCCESS:
return "✓";
default:
return "✗";
}
}
#NonNull
private String getDobGuess(String dob, String yob) {
if (dob.equals("")) {
Integer yearInt;
try {
yearInt = Integer.parseInt(yob);
} catch (NumberFormatException e) {
return "";
}
// June 1 of the year
return Integer.toString(yearInt) + "-06-01";
} else {
return dob;
}
}
Github Code Link
Just now got the solution, fetched exact mobile and email hash value from byte array
first remove last 256 bytes from byte array then,
if only mobile present then take last 32 bytes from byte array for mobile
i.e. (array.length - 32 to array.length)
else if only email present then take last 32 bytes from byte array for email i.e. (array.length - 32 to array.length)
else if both email and mobile present then take last 32 bytes from byte array for mobile, take next last 32 bytes for email
i.e. (mobile = array.length - 32 to array.length and
email = array.length - 64 to array.length - 32)
From the byte array you need to read values from index byte_array_length - 256 - 32 to byte_array_length - 256 to get the mobile hash in bytes(you can easily convert the bytes to hexadecimal string) and similarly for email you need to read from index byte_array_length - 256 - 32 - 32 to byte_array_length - 256 - 32.
I have implemented a library for decoding the same but the implementation is in Python.
The question is a bit old but future readers might find these resources useful.
PyPI: aadhaar-py
Github: https://github.com/vishaltanwar96/aadhaar-py

How to get line number in file from the character position using java

I have one JSON file and having some issue in it. When parsing the json file I will get the ParserException. From parser exception I have extracted the position where the is problem.
Now I want the line number of the that particular position in file.
JSONObject json;
try {
if (!file.exists()) {
throw new ExceptionDoesNotExist(file);
}
scanner = new Scanner(file, Charset.defaultCharset().toString());
String data = scanner.useDelimiter("\\Z").next();
json = (JSONObject) new JSONParser().parse(data);
return json;
} catch (ParseException e) {
this.log.logException(e);
int position = e.getPosition();
String reason = e.getUnexpectedObject().toString();
return new JSONObject();
}
if (!file.exists()) {
throw new ExceptionDoesNotExist(file);
}
scanner = new Scanner(file, Charset.defaultCharset().toString());
String data = scanner.useDelimiter("\\Z").next();
try {
return new JSONParser().parse(data);
} catch (ParseException e) {
String lineAndColumn = lineAndColumn(data, e, 4);
...;
return new JSONObject();
}
public static String lineAndColumn(String text, ParseException e, int tabSize) {
int position = e.getPosition();
int lineNo = 1 + (int) text.substring(0, position).codePoints()
.filter(cp -> cp == '\n')
.count();
int columnNo = 1 + text.substring(0, position).lastIndexOf('\n') + 1; // no \n okay too.
// Tabs
int cI = 0;
for (int i = 0; i < columnNo - 1; ++i) {
if (text.charAt(posion - (columnNo - 1) + i) == '\t') {
cI += tabSize;
cI %= tabSize;
} else {
++cI;
}
}
columnNo = cI + 1;
return String.format("%d:%d"), lineNo, ColumnNo);
}

Reading text between quotation marks

Here's a piece of text I'm trying to work with:
lat="52.336575" lon="6.381008">< time>2016-12-19T12:12:27Z< /time>< name>Foto 8 </name>< desc>Dag 4 E&F
Geb 1.4
Hakhoutstoof < /desc>< /wpt>
I'm trying to extract the coördinates between the "" and put the values between the "" into a string, but I can't get it to work...
Here's my code (so far):
public void openFile() {
Chooser = new JFileChooser("C:\\Users\\danie\\Desktop\\");
Chooser.setAcceptAllFileFilterUsed(false);
Chooser.setDialogTitle("Open file");
Chooser.addChoosableFileFilter(new FileNameExtensionFilter("*.gpx",
"gpx"));
int returnVal = Chooser.showOpenDialog(null);
try {
Dummy = new Scanner(Chooser.getSelectedFile());
} catch (FileNotFoundException E) {
System.out.println("Error: " + E);
}
}
public void createDummy() {
Dummy.useDelimiter("<wpt");
if (Dummy.hasNext()) {
String Meta = Dummy.next();
}
Dummy.useDelimiter("\\s[<wpt]\\s|\\s[</wpt>]\\s");
try {
while (Dummy.hasNext()) {
String Test = Dummy.next();
DummyFile = new File("Dummy.txt");
Output = new PrintWriter(DummyFile);
Output.print(Test);
Output.println();
Output.flush();
Output.close();
}
Reader = new FileReader(DummyFile);
Buffer = new BufferedReader(Reader);
TestFile = new File("C:\\Users\\danie\\Desktop\\Test.txt");
Writer = new PrintWriter(TestFile);
String Final;
while ((Final = Buffer.readLine()) != null) {
String WPTS[] = Final.split("<wpt");
for (String STD:WPTS) {
Writer.println(STD);
Writer.flush();
Writer.close();
}
}
} catch (IOException EXE) {
System.out.println("Error: " + EXE);
}
Dummy.close();
}
}
I'm really new to Java :(
I think the following code will do the trick ...
the "string" is only used to test the regex
final String string = "lat=\"52.336575\" lon=\"6.381008\">< time>2016-12-19T12:12:27Z< /time>< name>Foto 8 </name>< desc>Dag 4 E&F \nGeb 1.4 \n" + "Hakhoutstoof < /desc>< /wpt>";
final String latitudeRegex = "(?<=lat=\")[0-9]+\\.[0-9]*";
final Pattern latitudePattern = Pattern.compile(latitudeRegex);
final Matcher latitudeMatcher = latitudePattern.matcher(string);
//finds the next (in this case first) subsequence matching the given regex
latitudeMatcher.find();
String latitudeString = latitudeMatcher.group();
double lat = Double.parseDouble(latitudeString); //group returns the match matched by previous match
System.out.println("lat: " + lat);
to get the longitude, just replace lat by lon in the regex
this site is very useful for creating a regex
https://regex101.com/
you can even create the java code at this site

My array Printing NULL

In the method, i have all these initialize
Scanner input = new Scanner(System.in);
File file = new File("order.dat");
File viewOrder = new File("ViewOrder.dat");
String orderNo, itemNo, itemNameHolder, qtyHolder, priceHolder, status;
int hold, count = 0, countArray = 0;
double tempPriceHolder, totalPrice = 0;
String tempStatus = "";
String[] holdItemNo = null;
String[] holdName = null;
Integer[] holdQty = null;
Double[] holdTotal = null;
String[] holdStatus = null;
After, i try to read all my content in the file and store the content into holdX array
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while ((line = br.readLine()) != null) {
String tokens[] = line.split(";");
orderNo = tokens[0];
itemNo = tokens[1];
itemNameHolder = tokens[2];
qtyHolder = tokens[3];
priceHolder = tokens[4];
status = tokens[5];
if (orderNo.equalsIgnoreCase(userOrderNo)) {
tempPriceHolder = Double.parseDouble(priceHolder);
hold = Integer.parseInt(qtyHolder);
tempPriceHolder = tempPriceHolder * hold;
totalPrice += tempPriceHolder;
countArray++;
holdItemNo = new String[countArray];
holdName = new String[countArray];
holdQty = new Integer[countArray];
holdTotal = new Double[countArray];
holdStatus = new String[countArray];
if (status.matches("s")) {
tempStatus = "Success";
} else if (status.matches("p")) {
tempStatus = "Partially Full";
} else if (status.matches("o")) {
tempStatus = "Out of Stock";
}
holdItemNo[count] = itemNo;
holdName[count] = itemNameHolder;
holdQty[count] = hold;
holdTotal[count] = tempPriceHolder;
holdStatus[count] = tempStatus;
count++;
}
}
} catch (Exception e) {
System.out.println("Error");
}
Final, i write all my array into a new file.
System.out.printf("%s %15s %15s %10s %10s\n", "Item No", "Description", "Quantity", "Total", "Status");
for (int i = 0; i < holdItemNo.length; i++) {
System.out.printf("\n%-11s %-18s %-13s $%-8s %s \n", holdItemNo[i], holdName[i], holdQty[i], holdTotal[i], holdStatus[i]);
}
System.out.println("-----------------------------------------------------------------------");
System.out.printf("%46s %s\n", "$", totalPrice);
System.out.print("Print Order to file Y/N: ");
String choice = input.next();
if (choice.equalsIgnoreCase("y")) {
try {
PrintWriter bw = new PrintWriter(new FileWriter("ViewOrder.dat", true));
for (int i = 0; i < holdItemNo.length; i++) {
bw.write(userOrderNo + ";" + holdItemNo[i] + ";" + holdName[i] + ";" + holdQty[i] + ";" + holdTotal[i] + ";" + holdStatus[i] + "\n");
bw.flush();
}
bw.flush();
bw.close();
System.out.println("Sucessfull!");
} catch (Exception e) {
System.out.println("Error");
}
} else if (choice.equalsIgnoreCase("n")) {
System.out.println("");
}
but the problem is even my code is working but the output is not what i expected. It printed out the printed out the last content and also the sub price is working as well but the rest is only printed out NULL.
Example
Also, it gave me warning of Derefencing possible null pointer on the array.length
for (int i = 0; i < holdItemNo.length; i++) {
bw.write(userOrderNo + ";" + holdItemNo[i] + ";" + holdName[i] + ";" + holdQty[i] + ";" + holdTotal[i] + ";" + holdStatus[i] + "\n");
bw.flush();
}
Guessing:
holdItemNo = new String[countArray];
and the following lines: you are creating these new array objects within your reading loop (inside a condition).
So probably that condition never goes true; therefore your arrays stay all null. But even when the condition is met - you probably expect that to happen more then once. And guess what: you are creating completely new arrays then. While throwing away the previously created array. Each time the if condition turns true you will lose previously stored values!
So the answer is: create your arrays before entering the loop. This means that you either have to query "how many slots to create" upfront; or you have to create an array with say 100 empty slots; and within your loop you then have to check if you still have free slots.
Or you start using java.util.List resp. ArrayList - which allows for dynamic adding of elements.

Splitting String based on this six characters 0102**

How can I split a flat string based on 0102**? string tokenizer is working for only **. Is there any way to split based on 0102**? Please suggest
Here is my complete method
private String handleCibil(InterfaceRequestVO ifmReqDto, String szExtIntType) throws MalformedURLException, org.apache.axis.AxisFault, RemoteException {
/* Declaration and initiliazation */
ConfVO confvo = ifmReqDto.getExtConfVo();
String szResponse = null;
String cibilResponse = null;
String errorResponse = null;
String endpointURL = null;
long timeOut = confvo.getBurMgr().getBurInfo(szExtIntType).getTimeOut();
endpointURL = formWebServiceURL(confvo, szExtIntType);
URL url = new URL(endpointURL);
log.debug("Input xml for cibil "+ifmReqDto.getIfmReqXML());
BasicHttpStub stub= new BasicHttpStub(url,new org.apache.axis.client.Service());
szResponse = stub.executeXMLString(ifmReqDto.getIfmReqXML());
//szResponse=szResponse.replaceAll("&", "&");
log.debug("szResponse "+szResponse);
/* Validate if the obtained response is as expected by IFM */
try {
extDao = new ExtInterfaceXMLTransDAO(ifmReqDto.getSemCallNo(), ifmReqDto.getIdService());
extDao.updateRqstRespXML10g(ifmReqDto.getInterfaceReqNum(), szResponse, GGIConstants.IFM_RESPONSE);
//log.debug("CIBIL_RESPONSE_XPATH " + GGIConstants.CIBIL_RESPONSE_XPATH);
Document xmlDocument = DocumentHelper.parseText(szResponse);
String xPath = GGIConstants.RESPONSE_XPATH;
List<Node> nodes = xmlDocument.selectNodes(xPath);
for (Node node : nodes) {
String keyValue = node.valueOf(GGIConstants.RESPONSE_XPATH_KEY);
// log.debug("keyValue : " + keyValue);
if (keyValue.equalsIgnoreCase(GGIConstants.RESPONSE_XPATH_KEY_VALUE)) {
// log.debug("node value : " + node.getText());
cibilResponse = node.getText();
}
}
log.debug("cibilResponse " + cibilResponse);
String errorResponseXPATH = GGIConstants.CIBIL_ERROR_RESPONSE_XPATH;
List<Node> errorResponseNode = xmlDocument.selectNodes(errorResponseXPATH);
for (Node node : errorResponseNode) {
errorResponse = node.getText();
}
log.debug("errorResponse " + errorResponse);
if(cibilResponse!=null && cibilResponse.length()>0)
{
StringTokenizer cibilResponseResults = new StringTokenizer(cibilResponse,"**");
String tempResponse="";
ArrayList probableMatchList = new ArrayList();
while (cibilResponseResults.hasMoreElements()) {
tempResponse = (String) cibilResponseResults.nextElement();
if(tempResponse.length()>=80)
{
String memberRefNo = tempResponse.substring(69, 80).replaceAll(" ", "");
log.debug("memberRefNo " + memberRefNo);
if (memberRefNo.length() > 0) {
if (Integer.parseInt(memberRefNo) > 0) {
cibilResponse = tempResponse;
cibilResponse = cibilResponse+"**";
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
cibilResponse = tempResponse+"**";
}
}
log.debug("After finding the Member reference number cibilResponse " + cibilResponse);
log.debug("After finding the Probable reference list " + probableMatchList);
// TKN 008
cibilResponse=StringEscapeUtils.unescapeXml(cibilResponse).replaceAll("[^\\x20-\\x7e]","");
ifmReqDto.setIfmTransformedResult(cibilResponse);
ifmReqDto.setProbableMatchList(probableMatchList);
}
if (errorResponse!=null && errorResponse.length()>0) {
throw new GenericInterfaceException(errorResponse
+ " for the seq_request " + ifmReqDto.getSeqRequest() + " Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.CIBIL_ERROR_CODE);
}
else if (cibilResponse==null || StringUtils.isEmpty(cibilResponse) ) {
throw new GenericInterfaceException("Cibil TUEF response is empty >> cibil Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.INTERFACE_ERROR_RESPONSE);
}
/* Setting Instinct response to ifmReqDto object */
} catch (SQLException e) {
log.error("SQLException while connecting to DataBase. Exception message is ", e);
throw new GenericInterfaceException("SQLException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.DB_OPERATION_ERROR);
} catch (GenericInterfaceException exp) {
log.error("Exception occured while valid:", exp);
throw exp;
} catch (Exception exp) {
log.error("Exception occured while valid:", exp);
throw new GenericInterfaceException("GeneralException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.UNKNOWN_ERROR);
}
return szResponse;
}
I recommend checking out the Java documentation, it provides a really good reference to start with. The .split method uses a regex to split up a string based on a delimiter.
String[] tokens = myString.split("0102\\*\\*");
For now I suspect that you forgot to escape * in split regex.
Try maybe
String[] resutl = yourString.split("0102\\*\\*");
In case you want * to represent any character then use . instead of *
String[] resutl = yourString.split("0102..");
In case you want * to represent any digit use \\d instead
String[] resutl = yourString.split("0102\\d\\d");
String string = "blabla0102**dada";
String[] parts = string.split("0102\\*\\*");
String part1 = parts[0]; // blabla
String part2 = parts[1]; // dada
Here we have a String: "blabla0102**dada", we call it string. Every String object has a method split(), using this we can split a string on anything we desire.
Do you mean literally split by "0102**"? Couldn't you use regex for that?
String[] tokens = "My text 0102** hello!".split("0102\\*\\*");
System.out.println(tokens[0]);
System.out.println(tokens[1]);

Categories