While i am trying to convert below code snippet using java8 getting "Local variable sId defined in an enclosing scope must be final or effectively final" error.
Existing code:
String sId = "";
String uId = "";
FinalResp resp = new FinalResp();
List<LiqResp> liqRespList = getResp.getLiqRespList();
for(LiqResp liqResp : liqRespList){
List<ListOfAcq> listAcq = liqResp.getLiqList();
for(ListOfAcq acqList : listAcq){
List<Acq> acqs = acqList.getAcqList();
for(Acq acq :acqs){
if(sId.equalIgnoreCase(acq.getId()) || uId.equalIgnoreCase(acq.getId())){
resp.setId(acqList.getId());
}
}
}
}
return resp;
Below is the snippet which i tried to convert using java8:
String sId = "";
String uId = "";
FinalResp resp = new FinalResp();
List<LiqResp> liqRespList = getResp.getLiqRespList();
liqRespList.parallelStream.forEach(liqResp -> liqResp.getLiqList().parallelStream.
forEach(acqList->acqList.getAcqList().stream.map(acq -> {
return conversion(acq, acqList, sId,uId,resp); //getting error here as "Local variable sId
//defined in an enclosing scope must be final
// or effectively final"
})));
private FinalResp conversion(Acq acq, ListOfAcq acqList, String sId,String uId,FinalResp resp){
if(sId.equalIgnoreCase(acq.getId()) || uId.equalIgnoreCase(acq.getId())){
resp.setId(acqList.getId());
}
return resp;
}
Performance wise is this correct approach.thanks in advance for help.
Related
I'm using the follow code to generate random e-mails on the dataMap class:
public static String generateRandomEmail(int length) {
String allowedChars = "abcdefghijklmnopqrstuvwxyz" + "_-.";
String email = "";
String temp = RandomStringUtils.random(length, allowedChars);
email = temp.substring(0, temp.length() - 1)+"#mailinator.com";
System.out.println(email);
return email;
}
On my steps class, I need to use this email value, but I'm calling the method again, so it's generate another "email".
#Dado("que realizo a chamada no (.*) da (.*) informando (.*) e um email e (.*) novos")
public void verificarAmbiente(String srtAmbiente, String srtAPI, String srtToken, String srtSenha) {
System.out.println(srtAmbiente+srtAPI);
dataMap data = new dataMap();
int length = 15;
data.generateRandomEmail(length);
Map<String, String> emailContent = new HashMap<String,String>();
emailContent.put("email", data.generateRandomEmail(length));
Map<String, Object> postContent = new HashMap<String,Object>();
postContent.put("customer", emailContent);
postContent.put("password", srtSenha);
given().contentType(ContentType.JSON)
.header("Authorization", "Bearer "+srtToken)
.with().body(postContent)
.when().post(srtAmbiente+srtAPI).prettyPeek()
.then().statusCode(200);
}
I wanna transform the "return email" in a variable and call it in another class without execute the method again and change the value. Can you help me?
Thanks!
You need to store the generated email in a variable:
String email = data.generateRandomEmail(length);
And then you can just use the email variable later when you need the same email address.
I am new to Java programming and need some help here.
I am running below code and getting appropriate response i.e.
{"name1":"Name2","date1":"2016-05-13","message1":"Message2"}
{"name1":"Name0","date1":"2016-05-13","message1":"Message0"}
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("loc", "message", "AVSoemK55hnvwxeDfgCc", "AVSoemK55hnvwxeDfgCa").get();
for(MultiGetItemResponse itemResponse: multiGetItemResponses){
GetResponse response2 = itemResponse.getResponse();
if(response2.isExists()){
String json2 = response2.getSourceAsString();
System.out.println(json2);
}
}
however, when i am trying to parameterise the search text, its not returning any value. Can anyone please guide what might be going wrong here? I have checked that variable abc is returning correct value i.e. "AVSoemK55hnvwxeDfgCc", "AVSoemK55hnvwxeDfgCa"
public static boolean getData(String ids){
String idAry[] = ids.split(",");
ArrayList<String> idStr = new ArrayList<String>();
for (String id:idAry){
idStr.add('"'+id+'"');
}
String abc = idStr.toString().replace("[", "").replace("]", "");
System.out.println(abc);
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("loc", "message", abc).get();
// MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
// .add("loc", "message", "AVSoemK55hnvwxeDfgCc", "AVSoemK55hnvwxeDfgCa").get();
//
for(MultiGetItemResponse itemResponse: multiGetItemResponses){
GetResponse response2 = itemResponse.getResponse();
if(response2.isExists()){
String json2 = response2.getSourceAsString();
System.out.println(json2);
}
}
return true;
}
You don't need the abc variable, i.e. you don't need to transform your list to string. You simply need to construct your query like this, by passing idList to your add() call as this call will take the index, the type and an Iterable<String>, so the idList already fits the job.
public static boolean getData(String ids){
String idAry[] = ids.split(",");
List<String> idList = Arrays.asList(idAry);
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("loc", "message", idList).get();
...
I've been trying to get this bit of Android code working for a while, and eclipse is giving me the ever so helpful Syntax Error when there shouldn't be one. I checked my brackets and I have the right number, and I believe they are all where they should be. This is code copied and pasted from a tutorial, and slightly tweaked. The code provided, in its entirety, works, but my version of it gives the errors. I didn't change that much.
public class MainActivity extends Activity{
Button Pull_Data;
// Define the TextViews
TextView client_Address1;
TextView client_Address2;
TextView client_Address3;
TextView client_Id;
// XML node keys
static final String KEY_ITEM = "Address"; // parent node
static final String KEY_PERSON = "addedByPerson";
static final String KEY_CITY = "addressCity";
static final String KEY_LINE_ONE = "addressLineOne";
static final String KEY_LINE_TWO = "addressLineTwo";
static final String KEY_STATE = "addressState";
static final String KEY_TYPE_ID = "addressTypeId";
static final String KEY_ZIP = "addressZip";
static final String KEY_CLIENT_ID = "clientId";
static final String KEY_COUNTRY_CODE = "countryCode";
static final String KEY_OBJECT_ID = "objectId";
static final String KEY_RECORD_ADDED_DATE = "recordAddedDate";
static final String KEY_RECORD_UPDATED_DATE = "recordUpdatedDate";
static final String KEY_RECORD_UPDATED_PERSON = "recordUpdatedPerson";
static final String KEY_SYNC_STATUS = "syncStatus"; //Syntax error is flagged here
// XML Data to Retrieve
Address = "";
addedByPerson = "";
addressCity = "";
addressLineOne = "";
addressLineTwo = "";
addressState = "";
addressTypeId = "";
addressZip = "";
clientId = "";
countryCode = "";
objectId = "";
recordAddedDate = "";
recordUpdatedDate = "";
recordUpdatedPerson = "";
syncStatus = "";
// Holds values pulled from the XML document using XmlPullParser
String[][] xmlPullParserArray = {{"Address", "0"},{"addedByPerson", "0"},{"addressCity", "0"},{"addressLineOne", "0"},{"addressLineTwo", "0"},
{"addressState", "0"},{"addressTypeId", "0"},{"addressZip", "0"},{"clientId", "0"},
{"countryCode", "0"},{"objectId", "0"},{"recordAddedDate", "0"},{"recordUpdatedDate", "0"},
{"recordUpdatedPerson", "0"},{"syncStatus", "0"}};
int parserArrayIncrement = 0;
// END OF NEW STUFF
#Override
protected void onCreate(Bundle savedInstanceState){ //Another error here, tagged at the first paren after onCreate
super.onCreate(savedInstanceState);
I have no clue what could be wrong. Structurally the code hasn't changed. The first error by static final String KEY_SYNC_STATUS = "syncStatus"; is a Synatx Error on token ";", { expected after this token
The two errors on the OnCreate method are Syntax Error on token "(" expected ; and Syntax Error on token ")" expected ; Any help is appreciated
Your error is here:
// XML Data to Retrieve
Address = "";
addedByPerson = "";
addressCity = "";
Your missing the types. What is Address, a String? What is addedByPerson?
// XML Data to Retrieve
String Address = "";
String addedByPerson = "";
String addressCity = "";
...
What is this? It is not valid parts of Java class:
//XML Data to Retrieve
Address = "";
Eclipse has it's own compiler that tries to compile file by parts. It is called incremental compiler.
Maybe it just can not split your class to compilable blocks? Try to solve these problems.
I have a URL and I need to get the value of v from this URL.
Here is my URL: http://www.youtube.com/watch?v=_RCIP6OrQrE
How can I do that?
I think the one of the easiest ways out would be to parse the string returned by URL.getQuery() as
public static Map<String, String> getQueryMap(String query) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
return map;
}
You can use the map returned by this function to retrieve the value keying in the parameter name.
If you're on Android, you can do this:
Uri uri = Uri.parse(url);
String v = uri.getQueryParameter("v");
I have something like this:
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
private String getParamValue(String link, String paramName) throws URISyntaxException {
List<NameValuePair> queryParams = new URIBuilder(link).getQueryParams();
return queryParams.stream()
.filter(param -> param.getName().equalsIgnoreCase(paramName))
.map(NameValuePair::getValue)
.findFirst()
.orElse("");
}
I wrote this last month for Joomla Module when implementing youtube videos (with the Gdata API). I've since converted it to java.
Import These Libraries
import java.net.URL;
import java.util.regex.*;
Copy/Paste this function
public String getVideoId( String videoId ) throws Exception {
String pattern = "^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(videoId);
int youtu = videoId.indexOf("youtu");
if(m.matches() && youtu != -1){
int ytu = videoId.indexOf("http://youtu.be/");
if(ytu != -1) {
String[] split = videoId.split(".be/");
return split[1];
}
URL youtube = new URL(videoId);
String[] split = youtube.getQuery().split("=");
int query = split[1].indexOf("&");
if(query != -1){
String[] nSplit = split[1].split("&");
return nSplit[0];
} else return split[1];
}
return null; //throw something or return what you want
}
URL's it will work with
http://www.youtube.com/watch?v=k0BWlvnBmIE (General URL)
http://youtu.be/k0BWlvnBmIE (Share URL)
http://www.youtube.com/watch?v=UWb5Qc-fBvk&list=FLzH5IF4Lwgv-DM3CupM3Zog&index=2 (Playlist URL)
Import these libraries
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
Similar to the verisimilitude, but with the capabilities of handling multivalue parameters. Note: I've seen HTTP GET requests without a value, in this case the value will be null.
public static List<NameValuePair> getQueryMap(String query)
{
List<NameValuePair> queryMap = new ArrayList<NameValuePair>();
String[] params = query.split(Pattern.quote("&"));
for (String param : params)
{
String[] chunks = param.split(Pattern.quote("="));
String name = chunks[0], value = null;
if(chunks.length > 1) {
value = chunks[1];
}
queryMap.add(new BasicNameValuePair(name, value));
}
return queryMap;
}
Example:
GET /bottom.gif?e235c08=1509896923&%49%6E%...
Using pure Java 8
Assumming you want to extract param "v" from url:
String paramV = Stream.of(url.split("?")[1].split("&"))
.map(kv -> kv.split("="))
.filter(kv -> "v".equalsIgnoreCase(kv[0]))
.map(kv -> kv[1])
.findFirst()
.orElse("");
Assuming the URL syntax will always be http://www.youtube.com/watch?v= ...
String v = "http://www.youtube.com/watch?v=_RCIP6OrQrE".substring(31);
or disregarding the prefix syntax:
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
String v = url.substring(url.indexOf("v=") + 2);
I believe we have a better approach to answer this question.
1: Define a function that returns Map values.
Here we go.
public Map<String, String> getUrlValues(String url) throws UnsupportedEncodingException {
int i = url.indexOf("?");
Map<String, String> paramsMap = new HashMap<>();
if (i > -1) {
String searchURL = url.substring(url.indexOf("?") + 1);
String params[] = searchURL.split("&");
for (String param : params) {
String temp[] = param.split("=");
paramsMap.put(temp[0], java.net.URLDecoder.decode(temp[1], "UTF-8"));
}
}
return paramsMap;
}
2: Call your function surrounding with a try catch block
Here we go
try {
Map<String, String> values = getUrlValues("https://example.com/index.php?form_id=9&page=1&view_id=78");
String formId = values.get("form_id");
String page = values.get("page");
String viewId = values.get("view_id");
Log.d("FormID", formId);
Log.d("Page", page);
Log.d("ViewID", viewId);
} catch (UnsupportedEncodingException e) {
Log.e("Error", e.getMessage());
}
If you are using Jersey (which I was, my server component needs to make outbound HTTP requests) it contains the following public method:
var multiValueMap = UriComponent.decodeQuery(uri, true);
It is part of org.glassfish.jersey.uri.UriComponent, and the javadoc is here. Whilst you may not want all of Jersey, it is part of the Jersey common package which isn't too bad on dependencies...
I solved the problem like this
public static String getUrlParameterValue(String url, String paramName) {
String value = "";
List<NameValuePair> result = null;
try {
result = URLEncodedUtils.parse(new URI(url), UTF_8);
value = result.stream().filter(pair -> pair.getName().equals(paramName)).findFirst().get().getValue();
System.out.println("--------------> \n" + paramName + " : " + value + "\n");
} catch (URISyntaxException e) {
e.printStackTrace();
}
return value;
}
this will work for all sort of youtube url :
if url could be
youtube.com/?v=_RCIP6OrQrE
youtube.com/v/_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE&feature=whatever&this=that
Pattern p = Pattern.compile("http.*\\?v=([a-zA-Z0-9_\\-]+)(?:&.)*");
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
Matcher m = p.matcher(url.trim()); //trim to remove leading and trailing space if any
if (m.matches()) {
url = m.group(1);
}
System.out.println(url);
this will extract video id from your url
further reference
My solution mayble not good
String url = "https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test";
int start = url.indexOf("v=")+2;
// int start = url.indexOf("list=")+5; **5 is length of ("list=")**
int end = url.indexOf("&", start);
end = (end == -1 ? url.length() : end);
System.out.println(url.substring(start, end));
// result: XcHJMiSy_1c
work fine with:
https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test
https://www.youtube.com/watch?v=XcHJMiSy_1c
public static String getQueryMap(String query) {
String[] params = query.split("&");
for (String param : params) {
String name = param.split("=")[0];
if ("YourParam".equals(name)) {
return param.split("=")[1];
}
}
return null;
}
I would like to return a string from an IF statement. Below is the code. I am parsing a JSON object and need to insert the data into a sql lite table.
if (object.has("message")) {
JSONObject message = object.getJSONObject("message");
String newtype_mod = object.getJSONObject("message").getString("type");
String newcontent_mod = object.getJSONObject("message").getString("content");
objSample = new GetSetMethod();
objSample.setnewcontent_mod(newcontent_mod);
objSample.setnewtype_mod(newtype_mod);
Log.v("##" + newcontent_mod, "V " + newtype_mod);
}
objSample = new GetSetMethod();
objSample.setNewreportid(newreportid);
objSample.setnewcontent_mod(newcontent_mod);
objSample.setnewtype_mod(newtype_mod);
Log.v("" + newcontent_mod, "" + newtype_mod);
As you would have understood newcontent_mod and newtype_mod will not be accessible from the IF statement. And I need the IF statement compulsorily.
I understand the question is basic. Please help a fellow newbie !
Thanks!
Can you not simply declare them outside the if?
String newtype_mod = "";
String newcontent_mode = "";
if ((object.has("message"))) {
//
// do stuff here
//
}
// continue as before...
You can declare it outside the if statement and just assign the value to these variables
for example:
String newtype_mod="";
String newcontent_mod="";
if ((object.has("message")))
{
JSONObject message = object.getJSONObject("message");
newtype_mod = object.getJSONObject("message")
.getString("type");
newcontent_mod = object.getJSONObject("message")
.getString("content");
objSample = new GetSetMethod();
objSample.setnewcontent_mod(newcontent_mod);
objSample.setnewtype_mod(newtype_mod);
Log.v("##"+newcontent_mod,"V "+newtype_mod);
}
otherwise
You can declare both at Global level i.e. class level variables
Declare the 2 string outside the if statement like
String newcontent_mod,newtype_mod;
if ((object.has("message"))) {
JSONObject message = object.getJSONObject("message");
newtype_mod = object.getJSONObject("message")
.getString("type");
newcontent_mod = object.getJSONObject("message")
.getString("content");
objSample = new GetSetMethod();
objSample.setnewcontent_mod(newcontent_mod);
objSample.setnewtype_mod(newtype_mod);
Log.v("##"+newcontent_mod,"V "+newtype_mod);
}