I have written the below code to parse a string in java but its not printing out a blank message.
How can I get specific parts from a SOAP message and get their values?
I want to get the error and the message in the request.
String xml = "<?xml version='1.0' encoding='UTF-8'?>"
+ "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<S:Body>"
+ "<ns2:processResponse xmlns:ns2=\"http://ws.xxxxx.com/\">"
+ "<response><direction>response</direction>"
+ "<reference>09FG10021008111306320</reference>"
+ "<amount>0.0</amount>"
+ "<totalFailed>0</totalFailed>"
+ "<totalSuccess>0</totalSuccess>"
+ "<error>1</error>"
+ "<message>Invalid</message>"
+ "<otherReference>6360e28990c743a3b3234</otherReference>"
+ "<action>FT</action>"
+ "<openingBalance>0.0</openingBalance>"
+ "<closingBalance>0.0</closingBalance>"
+ "</response>"
+ "</ns2:processResponse>"
+ "</S:Body>"
+ "</S:Envelope>\n";
SAXBuilder builder = new SAXBuilder();
Reader in = new StringReader(xml);
Document doc = null;
Element root = null;
Element meta = null;
Element error = null;
Element status_message = null;
String status_code= "";
String message = "";
try
{
doc = builder.build(in);
root = doc.getRootElement();
meta = root.getChild("processResponse").getChild("response");
error = meta.getChild("error");
status_message = meta.getChild("message");
status_code = error.getText();
message = status_message.getText();
}catch (Exception e)
{
// do what you want
}
System.out.println("status_code: " + status_code + "\nmessage: " + message);
The response being generated is
status_code:
message:
You are making some mistakes in your code while picking up elements in xml. You can use this code and check,
public static void main(String[] args) {
String xml = "<?xml version='1.0' encoding='UTF-8'?>"
+ "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<S:Body>"
+ "<ns2:processResponse xmlns:ns2=\"http://ws.xxxxx.com/\">"
+ "<response><direction>response</direction>" + "<reference>09FG10021008111306320</reference>"
+ "<amount>0.0</amount>" + "<totalFailed>0</totalFailed>" + "<totalSuccess>0</totalSuccess>"
+ "<error>1</error>" + "<message>Invalid</message>"
+ "<otherReference>6360e28990c743a3b3234</otherReference>" + "<action>FT</action>"
+ "<openingBalance>0.0</openingBalance>" + "<closingBalance>0.0</closingBalance>" + "</response>"
+ "</ns2:processResponse>" + "</S:Body>" + "</S:Envelope>\n";
SAXBuilder builder = new SAXBuilder();
Reader in = new StringReader(xml);
Document doc = null;
Element root = null;
Element error = null;
Element status_message = null;
String status_code = "";
String message = "";
try {
doc = builder.build(in);
root = doc.getRootElement();
Element body = root.getChild("Body", Namespace.getNamespace("S", "http://schemas.xmlsoap.org/soap/envelope/"));
Element processResponse = body.getChild("processResponse", Namespace.getNamespace("ns2", "http://ws.xxxxx.com/"));
Element response = processResponse.getChild("response");
error = response.getChild("error");
status_message = response.getChild("message");
status_code = error.getText();
message = status_message.getText();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("status_code: " + status_code + "\nmessage: " + message);
}
For me this is giving following output,
status_code: 1
message: Invalid
Related
I am facing a issue where I am not able to get the value in my hashmap as per the key of the XML while I am getting the parent key
Code I am using:
public static void main(String[] args) throws IOException {
try {
String XML="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
"<sj0:Msg>\r\n" +
" xmlns:sj0=\"http://fakesite.org/\"\r\n" +
" xmlns:sj1=\"http://fakesite.org/ind\"\r\n" +
" <sj0:Hdr>\r\n" +
" <sj2:Option>CreateTxn</sj2:Option>\r\n" +
" <sj2:ID>172246</sj2:ID>\r\n" +
" <sj2:CountryCode>CR</sj2:CountryCode>\r\n" +
" </sj0:Hdr>\r\n" +
" <sj0:ReqDet>\r\n" +
" <sj0:MReq>\r\n" +
" <sj0:qCore>\r\n" +
" <sj1:Reference>12345678</sj1:Reference>\r\n" +
" <sj1:BrnCode>CLM</sj1:BrnCode>\r\n" +
" <sj1:Source>M1T722</sj1:Source>\r\n" +
" <sj1:TxnLegCount>2</sj1:TxnLegCount>\r\n" +
" </sj0:qCore>\r\n" +
" </sj0:MReq>\r\n" +
" <sj0:LReq>\r\n" +
" <sj0:RCore>\r\n" +
" <sj1:Amt>19.28</sj1:Amt>\r\n" +
" <sj1:Dt>2019-09-04</sj1:Dt>\r\n" +
" <sj1:Date>2019-06-27</sj1:Date>\r\n" +
" </sj0:RCore>\r\n" +
" </sj0:LReq>\r\n" +
" <sj0:LReq>\r\n" +
" <sj0:RCore>\r\n" +
" <sj1:Ind>DC</sj1:Ind>\r\n" +
" <sj1:Currency>US</sj1:Currency>\r\n" +
" <sj1:LAmt>20.28</sj1:LAmt>\r\n" +
" </sj0:RCore>\r\n" +
" </sj0:LReq>\r\n" +
" </sj0:ReqDet>\r\n" +
"</sj0:Msg>";
String XString = XML;
System.out.println(XML);
HashMap<String, String> values = new HashMap<String, String>();
Document xml = convertStringToDocument(XString);
Node user = xml.getFirstChild();
NodeList childs = user.getChildNodes();
Node child;
for (int i = 0; i < childs.getLength(); i++) {
child = childs.item(i);
System.out.println(child.getNodeName());
System.out.println(child.getNodeType());
System.out.println(child.getUserData("Source"));
System.out.println(child.getTextContent());
values.put(child.getNodeName(), child.getTextContent());
}
System.out.println("Source name");
System.out.println(values.toString());
System.out.println(values.get("Source"));
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xmlStr.getBytes("UTF-8"))));
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Output:
{sj0:ReqDet=
12345678
CLM
M1T722
2
19.28
2019-09-04
2019-06-27
DC
US
20.28
, #text= , sj0:Hdr= CreateTxn 172246 CR }
I need to add Source in haspmap key not ReqDet.
I am facing issue to traverse through the XML.
Any idea where I am going wrong and also please explain how I can get the value of other keys-value i.e. Ind key of RCore parent key.
I am fine with any other approach or library to do achieve this task if this library have issue
below line of code having "*" which means it will select all nodes/key-values from the XML
NodeList nodeList = doc.getElementsByTagName("*");
Below is the full code works for me:
public static void main(String[] args) throws IOException {
String XML="YOUR XML";
HashMap<String, String> values =convertStringToDocument(XML);
System.out.println("values = "+values.get("sj1:Source"));
}
public static HashMap<String, String> convertStringToDocument(String xmlStr) {
HashMap<String, String> values = new HashMap<String, String>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
EntityResolver resolver = new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) {
String empty = "";
ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
System.out.println("resolveEntity:" + publicId + "|" + systemId);
return new InputSource(bais);
}
};
builder.setEntityResolver(resolver);
Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xmlStr.getBytes("UTF-8"))));
NodeList nodeList = doc.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
values.put(node.getNodeName(), node.getTextContent());
}
}
return values;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Im working on a MapReduce (Map only task) which reads the JSON file and extracts the elements from JSON input. Input data:
{"type":"cloud_monitor","format":"default","version":"1.0","id":"71101cb85441995d11a43bb","start":"1413585245.921","cp":"254623","message":{"proto":"http","protoVer":"1.1","status":"403","cliIP":"23.79.231.14","reqPort":"80","reqHost":"ksd.metareactor.com","reqMethod":"GET","reqPath":"%2findex.php","reqQuery":"path%3d57%26product_id%3d49%26route%3d%255Cwinnt%255Cwin.ini%2500.","respCT":"text/html","respLen":"286","bytes":"286","UA":"mozilla-saturn","fwdHost":"origin-demo2-akamaized.scoe-sil.net"},"reqHdr":{"accEnc":"gzip,%20deflate","cookie":"PHPSESSID%3dkkqoodvfe0rt9l7lbvqghk6e15%3bcurrency%3dUSD%3blanguage%3den"}}
I've declared String variables for the JSON Arrays: Message & reqHdr and you can see them in the context.write() method
Map Class:
public class JsonMapper extends Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String type;
String format;
String version;
String id;
String start;
String cp;
// variables for message and reqHdr
String[] line = value.toString().split("\\n");
if (line.length > 0) {
for(int i=0; i<line.length; i++) {
try {
JSONObject jsonobj = new JSONObject(line[i]);
type = (String) jsonobj.get("type");
format = (String) jsonobj.get("format");
version = (String) jsonobj.get("version");
id = (String) jsonobj.get("id");
start = (String) jsonobj.get("start");
cp = (String) jsonobj.get("cp");
// Message Variable array
JSONArray messageArray = (JSONArray) jsonobj.get("message");
for(int j=0; j<messageArray.length(); j++) {
JSONObject jsonmessageobject = messageArray.getJSONObject(j);
proto = jsonmessageobject.getString("proto");
protoVer = jsonmessageobject.getString("protoVer");
cliIP = jsonmessageobject.getString("cliIP");
reqPort = jsonmessageobject.getString("reqPort");
reqHost = jsonmessageobject.getString("reqHost");
reqMethod = jsonmessageobject.getString("reqMethod");
reqPath = jsonmessageobject.getString("reqPath");
reqQuery = jsonmessageobject.getString("reqQuery");
reqCT = jsonmessageobject.getString("reqCT");
reqLen = jsonmessageobject.getString("reqLen");
sslVer = jsonmessageobject.getString("sslVer");
status = jsonmessageobject.getString("status");
redirURL = jsonmessageobject.getString("redirURL");
respCT = jsonmessageobject.getString("respCT");
respLen = jsonmessageobject.getString("respLen");
bytes = jsonmessageobject.getString("bytes");
UA = jsonmessageobject.getString("UA");
fwdHost = jsonmessageobject.getString("fwdHost");
}
// reqHdr variable array
JSONArray reqHdrArray = (JSONArray) jsonobj.get("reqHdr");
for(int k=0; k<reqHdrArray.length(); k++) {
JSONObject jsonreqHdrobject = reqHdrArray.getJSONObject(i);
accEnc = jsonreqHdrobject.getString("accEnc");
accLang = jsonreqHdrobject.getString("accLang");
auth = jsonreqHdrobject.getString("auth");
reqHdr_cacheCtl = jsonreqHdrobject.getString("cacheCtl");
reqHdr_conn = jsonreqHdrobject.getString("conn");
reqHdr_contMD5 = jsonreqHdrobject.getString("contMD5");
cookie = jsonreqHdrobject.getString("cookie");
DNT = jsonreqHdrobject.getString("DNT");
expect = jsonreqHdrobject.getString("expect");
ifMatch = jsonreqHdrobject.getString("ifMatch");
ifMod = jsonreqHdrobject.getString("ifMod");
ifNone = jsonreqHdrobject.getString("ifNone");
ifRange = jsonreqHdrobject.getString("ifRange");
ifUnmod = jsonreqHdrobject.getString("ifUnmod");
range = jsonreqHdrobject.getString("range");
referer = jsonreqHdrobject.getString("referer");
te = jsonreqHdrobject.getString("te");
upgrade = jsonreqHdrobject.getString("upgrade");
reqHdr_via = jsonreqHdrobject.getString("via");
xFrwdFor = jsonreqHdrobject.getString("xFrwdFor");
xReqWith = jsonreqHdrobject.getString("xReqWith");
}
context.write(new Text("cloud_monitor"), new Text(type + format + version + id + start + cp + proto + protoVer + cliIP + reqPort +
reqHost + reqMethod + reqPath + reqQuery + reqCT + reqLen + sslVer + status + redirURL + respCT + respLen + bytes + UA + fwdHost + accEnc + accLang + auth +
reqHdr_cacheCtl + reqHdr_conn + reqHdr_contMD5 + cookie + DNT + expect + ifMatch + ifMod + ifNone + ifRange + ifUnmod + range + referer + te +
upgrade + reqHdr_via + xFrwdFor + xReqWith ));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
I'm getting the following error message:
Error: java.lang.ClassNotFoundException: org.json.JSONException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.Class.forName(Class.java:270)
at org.apache.hadoop.conf.Configuration.getClassByNameOrNull(Configuration.java:2138)
at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:2103)
at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2197)
at org.apache.hadoop.mapreduce.task.JobContextImpl.getMapperClass(JobContextImpl.java:196)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:745)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1693)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)
Could anyone tell me if I am doing the JSON Parsing correctly, especially the JSON Arrays (message, reqHdr) part or how I can fix the bug ?
You have to download the org.json far file, and then add it to your project.
You can download the jar : here
I am using twitter home_timeline API for showing tweets.For first time I run this it works fine, but when I call it again (pull to load more), it doesn't responds. I am passing auth headers and in params I passed count, it doesn't worked too.
I don't know where am I stuck..
Here is code for pulling tweets:
if (auth != null && auth.token_type.equals("bearer")) {
HttpGet httpget = new HttpGet(TwitterStreamURL);
String oAuthConsumerKey = CONSUMER_KEY;
String oAuthConsumerSecret = CONSUMER_SECRET;
String oAuthAccessToken = HomeActivity.twitter_access_token;
String oAuthAccessTokenSecret = HomeActivity.twitter_access_token_secret;
String oAuthNonce = String.valueOf(System.currentTimeMillis());
String oAuthSignatureMethod = "HMAC-SHA1";
String oAuthTimestamp = time();
String oAuthVersion = "1.0";
String signatureBaseString1 = methods;
String signatureBaseString2 = TwitterStreamURL;
String signatureBaseString3Templ = "oauth_consumer_key=%s&oauth_nonce=%s&oauth_signature_method=%s&oauth_timestamp=%s&oauth_token=%s&oauth_version=%s";
String signatureBaseString3 = String.format(signatureBaseString3Templ,
oAuthConsumerKey,
oAuthNonce,
oAuthSignatureMethod,
oAuthTimestamp,
oAuthAccessToken,
oAuthVersion);
String signatureBaseStringTemplate = "%s&%s&%s";
try {
signatureBaseString = String.format(signatureBaseStringTemplate,
URLEncoder.encode(signatureBaseString1, "UTF-8"),
URLEncoder.encode(signatureBaseString2, "UTF-8"),
URLEncoder.encode(signatureBaseString3, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
compositeKey = URLEncoder.encode(oAuthConsumerSecret, "UTF-8") + "&" + URLEncoder.encode(oAuthAccessTokenSecret, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
String oAuthSignature = computeSignature(signatureBaseString, compositeKey);
oAuthSignatureEncoded = URLEncoder.encode(oAuthSignature, "UTF-8");
String authorizationHeaderValueTempl = "OAuth oauth_consumer_key=\"%s\", oauth_nonce=\"%s\", oauth_signature=\"%s\", oauth_signature_method=\"%s\", oauth_timestamp=\"%s\", oauth_token=\"%s\", oauth_version=\"%s\"";
String authorizationHeaderValue = String.format(authorizationHeaderValueTempl,
oAuthConsumerKey,
oAuthNonce,
oAuthSignatureEncoded,
oAuthSignatureMethod,
oAuthTimestamp,
oAuthAccessToken,
oAuthVersion);
} catch (Exception e) {
e.printStackTrace();
}
String vf = "oauth_consumer_key=" + oAuthConsumerKey + ",oauth_signature_method=" + oAuthSignatureMethod + ",oauth_timestamp=" + oAuthTimestamp + ",oauth_nonce=" + oAuthNonce + ",oauth_version=" + oAuthVersion + ",oauth_token=" + oAuthAccessToken + ",oauth_signature=" + oAuthSignatureEncoded + "";
httpget.setHeader("Authorization", "OAuth " + "oauth_consumer_key=" + oAuthConsumerKey + ",oauth_signature_method=" + oAuthSignatureMethod + ",oauth_timestamp=" + oAuthTimestamp + ",oauth_nonce=" + oAuthNonce + ",oauth_version=" + oAuthVersion + ",oauth_token=" + oAuthAccessToken + ",oauth_signature=" + oAuthSignatureEncoded + "");
httpget.setHeader("Content-Type", "application/json");
// update the results with the body of the response
checkTwitRes = true;
results = getResponseBody(httpget);
}
div {
color:#000;
font-weight:800
}
p {
color:red;
background:url("mypicture.png")
}
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]);
I created a button that allows to create a zip file., the function that zips the file works correctly, but when I call her via the button (in the JS file) it crashes and it gives a blank page (I think I do not manage the output stream)
would please an idea
here is my code:
Button
isc.ToolStripButton.create({
ID: "BooksApp_GetXmlImage_Button"
,autoDraw:false
,icon: getUIIcon("icon_xml_16")
,prompt: getUIMsg("book_report_get_xml",4)
,showHover:true
,hoverStyle:"book_hover_style"
,click : function () {
BooksApp_Action_loadFile("objx");
// isc.say("test");
}
});
function to call the zipfile() method:
function BooksApp_Action_loadFile(p_UsedFormat) {
var tmpBookID = BooksApp_Application.FP_BookID;
var tmpIDs = BooksApp_Application.FP_fct_getSelectedPOVIDs();
var tmpUsr_ID = FPIUser.FP_fct_getID();
var tmpFormat = p_UsedFormat;
var showInWindow=false;
books_objects.exportData(
{
r_book_idnum : tmpBookID
,sBook_ID : tmpBookID
,sPOV_IDs : tmpIDs
,sUser_ID : tmpUsr_ID
,sFormat : tmpFormat
}
,{ operationId: "customExport"
,exportDisplay: (showInWindow ? "window" : "download") }
,function (dsResponse, data, dsRequest) {
//Never called
BooksApp_Action_Log("BooksApp_Action_loadFile:"+data);
}
);
}
customExport() function
public static String customExport(RPCManager rpc,
HttpServletResponse response) throws Exception {
String sReturn = _Return_OK;
try {
// setting doCustomResponse() notifies the RPCManager that we'll
// bypass RPCManager.send
// and instead write directly to the servletResponse output stream
rpc.doCustomResponse();
RequestContext.setNoCacheHeaders(response);
writeServerDebug("customExport : start");
DSRequest req = rpc.getDSRequest();
List<?> results = req.execute().getDataList();
String sReqData = (String) req.getParameter("exportDisplay");
String sReqData_sBook_ID = "" + req.getCriteriaValue("sBook_ID");
String sReqData_sPOV_IDs = "" + req.getCriteriaValue("sPOV_IDs");
String sReqData_sUser_ID = "" + req.getCriteriaValue("sUser_ID");
String sReqData_sFormat = "" + req.getCriteriaValue("sFormat");
StringBuilder content = new StringBuilder("get (sReqData:"
+ sReqData + ",sBook_ID:" + sReqData_sBook_ID
+ ",sPOV_IDs:" + sReqData_sPOV_IDs + ",sUser_ID:"
+ sReqData_sUser_ID + ",sFormat:" + sReqData_sFormat + ")"
+ results.size() + " line(s):");
for (Iterator<?> i = results.iterator(); i.hasNext();) {
Map<?, ?> record = (Map<?, ?>) i.next();
content.append("\n" + Books.Column_IDNum + ":"
+ record.get(Books.Column_IDNum));
content.append("\n" + Books.Column_Name + ":"
+ record.get(Books.Column_Name));
}
writeServerDebug("The content is \n" + content.toString());
// Create the new Office Engine
OfficeEngine myOfficeEngine = new OfficeEngine();
boolean bIsConnected = myOfficeEngine._RepositoryBridge
.connectSourceDataBase(false);
if (bIsConnected) {
//Connected to the repository, so get the files
if (sReqData_sFormat.equalsIgnoreCase("pdf") || sReqData_sFormat.equalsIgnoreCase("pptx")) {
//The book end user format
String sReturnPptx = myOfficeEngine.performGeneratePptx(
req.getHttpServletRequest(), response,
sReqData_sBook_ID, sReqData_sPOV_IDs,
sReqData_sUser_ID, sReqData_sFormat);
writeServerDebug("customExport call performGeneratePptx, return is "
+ sReturnPptx);
}
else {
AppZip appZip = new AppZip();
appZip.ZipFile(" ", " ");
String r = "sReturn_OK";;
return r;
}
//Free the connection to repository
myOfficeEngine._RepositoryBridge.freeConnectionSource();
} else {
response.setContentType("text/plain");
response.addHeader("content-disposition",
"attachment; filename=book.txt");
ServletOutputStream os = response.getOutputStream();
os.print(content.toString());
os.flush();
}
} catch (Exception e) {
writeServerDebug("ERROR:" + e.getLocalizedMessage());
sReturn = Repository._Return_KO;
}
return sReturn;
}