How to generate field and initialize value - java

How to initialize a field that is generated. Or in the code example below, where can the AssignExpr object be added for the code to work?
private void addConfigField(ClassOrInterfaceDeclaration clazz) {
var className = "BlaConfig";
var configField = clazz.addField(className, "blaConfig", Modifier.PRIVATE);
var configFieldExpr = new NameExpr("blaConfig");
var newConfigObj = new ObjectCreationExpr(null, JavaParser.parseClassOrInterfaceType(className), new NodeList<>());
var assign = new AssignExpr(configFieldExpr, newConfigObj, Operator.ASSIGN);
}
Using com.github.javaparser:javaparser-core:3.2.4

You can get the variable declared in the 'configField'. That variable may be initialized.
configField.getVariable(0).setInitializer(/* Your code */);

Related

Accessing Scala Variable: 'not found value: variable_name' Issue

I have two Scala Objects.
common_code
dependent_code
In common_code I have one method in which I am writing my common code and declaring some variables. I want to use these variables and code in my 2nd object but when I am trying to access these Varibales I'm getting common_method not found value: variable name issue.
I'm using below code.
object comman_code{
def common_method(args: Array[String]) {
val properties: Properties = new Properties()
val hdfsConf = new Configuration();
val fs: FileSystem = FileSystem.get(hdfsConf);
val is = fs.open(new Path(args(0)));
properties.load(is)
//created sparkSesssion
//Table_Name i want to use in 2nd program
val Table_Name = properties.getProperty("Table_Name")
}
}
object dependent_code {
def main(args: Array[String]):Unit = {
val common_method = helper_class.common_method(args)
val mydf=sparksesssion.sql(s"select * from ${Table_Name}").show() //not able to acess getting not found value: Table_Name
}
}
Can someone please suggest how I can access Table_Name variable in my other object?
As you are working with Scala Objects they are instantiated automatically and you can easily access them like shown below.
object common_code {
def common_method(args: Array[String]): String = {
val properties: Properties = new Properties()
val hdfsConf = new Configuration();
val fs: FileSystem = FileSystem.get(hdfsConf);
val is = fs.open(new Path(args(0)));
properties.load(is)
//created sparksesssion
val Table_Name: String = properties.getProperty("Table_Name")
Table_Name
}
}
object dependent_code {
def main(args: Array[String]):Unit = {
val tableName: String = common_code.common_method(args)
val mydf=sparksesssion.sql(s"""select * from ${tableName}""").show()
}
}
One important thing here is that you cannot access to fields which are located inside method.
You should not assign to a variable (val Table_Name) on the last line in common_method, but return it. Otherwise your method is just Unit, meaning that nothing will return after invoke. Here is little improvement that you can try understand:
object comman_code {
def common_method(args: Array[String]): String = {
val properties: Properties = new Properties()
val hdfsConf = new Configuration();
val fs: FileSystem = FileSystem.get(hdfsConf);
val is = fs.open(new Path(args(0)));
properties.load(is)
//created sparksesssion
properties.getProperty("Table_Name")
}
}
object dependent_code {
def main(args: Array[String]): Unit = {
val tableName = comman_code.common_method(args)
val mydf = sparksesssion.sql(s"select * from $tableName").show()
}
}
Note: I called common_method from common_code object and the result is assigned to a variable called tableName. Then in turn tableName is used in string interpolation.
Couple of another suggestions:
Naming Conventions
How to post a question

Java 8 shows this error. Local variable itemList defined in an enclosing scope must be final or effectively final

I am writing the code using java 8 but I iterate a List and then find RestaurantOrderBook using category type. and put that List into a Map. it shows this error:
Local variable itemList defined in an enclosing scope must be final or effectively final
Query query = new Query();
String categ = category;
query.addCriteria(Criteria.where("restaurantId").is(restaurantId));
List<RestaurantOrderBook> itemList = new ArrayList<RestaurantOrderBook>();
itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
System.out.println("size : " + itemList.size());
Map<String , List<RestaurantOrderBook>> map = new HashMap<String , List<RestaurantOrderBook>>();
Arrays.asList("TakeAway", "Dining").forEach(e ->{
//Following line throws error:
List<RestaurantOrderBook> list = itemList.stream().filter(a -> !a.getOrderType().isEmpty() && a.getOrderType().equals(e)).collect(Collectors.toList());
map.put(e, list);
});
I have an another situation:
#Override
public EventReportRewardsPoints eventReportRewardsPoints(String organizerId) {
try{
List<Event> listOfEvents = eventRepo.findByOrganizerId(organizerId);
EventReportRewardsPoints eventTransReport = new EventReportRewardsPoints();
Integer soldTics = 0;
Double totalRevenue = 0d;
Integer soldToday = 0;
Integer findTotalAvailableTics = 0;
Integer findTotalQtytics = 0;
for (Event event : listOfEvents) {
List<EventTicket> eventTicket = eventTicketRepo.findByEventId(event.getId());
Integer sumOfAvailabletics = eventTicket.stream()
.mapToInt(EventTicket::getRemainingTickets).sum();
findTotalAvailableTics = findTotalAvailableTics + sumOfAvailabletics;
Integer sumOfQtytics = eventTicket.stream().mapToInt(EventTicket::getQty).sum();
findTotalQtytics = findTotalQtytics + sumOfQtytics;
List<EventTicketBook> listOfEventsTic = eventTicketBookRepository.findByEventId(event.getId());
for (EventTicketBook eventTicketBook : listOfEventsTic) {
Double sumOfSales = eventTicketBook.getTickets().stream().mapToDouble(EventTicket::getPrice).sum();
totalRevenue = totalRevenue + sumOfSales;
Date now = new Date();
System.out.println("create date : " + eventTicketBook.getCreateOn());
/*if(now.compareTo(eventTicketBook.getCreateOn()) == 0){
Integer sumOfSoldToday = eventTicketBook.getTickets().stream().mapToInt(EventTicket::getQty).sum();
soldToday = soldToday + sumOfSoldToday;
}*/
}
}
System.out.println("findTotalQtytics : " + findTotalQtytics);
System.out.println("findTotalAvailableTics : " + findTotalAvailableTics);
soldTics = findTotalQtytics - findTotalAvailableTics;
eventTransReport.setTotalRevenue(totalRevenue);
eventTransReport.setSoldToday(soldToday);
eventTransReport.setTicketsSold(soldTics);
return eventTransReport;
}catch(Exception e ){
e.printStackTrace();
}
return null;
}
How do i achive this using lamda expression.??
You are using itemList within a lambda expression. Therefore it has to be final.
Java 8 introduces the new concept of effectivly final, which means, the compiler checks, if a used variable is final in usage and does not force the developer to explicitly declare it as final.
So if you change your code to
final List<RestaurantOrderBook> itemList = new ArrayList<RestaurantOrderBook>();
you will see, that the compiler gives you an error at:
itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
because you are reasigning itemList. That is why itemList is not effectivly final as well. If you squash these two lines to
List<RestaurantOrderBook> itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
it should work.
Declare your variable itemList final:
final List<RestaurantOrderBook> itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
As noted in the accepted answer by wumpz, the reason is that the variable being used has to be final or effectively final.
I would like to add the reason as to why it is so:
When we write a Lambda expression, we are effectively authoring an anonymous inner class. For Ex:
#FunctionalInterface
interface MyInterface{
public void print();
}
Used in our code as:
public static void main(String[] args) {
int i = 6;
new MyInterface() {
#Override
public void print() {
System.out.println(++i); // Remove ++ to resolve error
}
}.print();
}

Flash AS3 Pass my var data to another frame

I'm using AS3 / AIR 3.2 for Android.
I'm having a trouble about passing my variable data to another frame. I read some forums about this but I'm only new this so I don't have yet any idea.
I have an input text and button in my frame 1 where the user will input a name then the data entered will be save. (I used SharedObject) but all the data inputted will appear on frame 2.
While my frame 2 is a dynamic text where all the data will appear.
This is the code for my frame 1
import flash.net.SharedObject;
var myName:String;
myResult.text = "";
var mySO:SharedObject = SharedObject.getLocal("test");
if (mySO1.data.myName != null){
myResult.text = mySO1.data.myName;
}
else {
myResult.text = "No Name";
}
submit_btn.addEventListener(MouseEvent.CLICK, gotomyNextFrame);
function gotomyNextFrame(event:MouseEvent):void
{
nextFrame();
myName = myInputName.text;
trace(myName);
myResult.text = myName;
mySO.data.myResult = myInputName.text;
mySO.flush();
trace(mySO.data.myResult);
}
Error: Error #1009: Cannot access a property or method of a null object reference. I think this is because I'm wrong in passing of data into frame.
Attempt: I tried show the output on the same frame and I didn't encounter any error.
Your SharedObject var is mySO and not mySO1, and to share data between frames, you can use a variable like this :
frame 1 :
...
var shared_data:String = txt_input.text
nextFrame()
...
frame 2 :
// get shared_data and use it as you like
another_input.text = shared_data
shared_object.data.current_name = shared_data
...
Edit :
/* frame 01 */
// shared_data should be declared here to be a global var not inside a function
var shared_data:String
submit_btn.addEventListener(MouseEvent.CLICK, gotomyNextFrame)
function gotomyNextFrame(event:MouseEvent):void {
// here you should just assign a value to shared_data var
shared_data = yourName.text
nextFrame()
}
/* frame 2 */
stop()
import flash.net.SharedObject
// if you redefine shared_data var here you will lost it's value and you will get a null value
// var shared_data:String
var mySO:SharedObject = SharedObject.getLocal("test1")
myResult.text = shared_data
// here your SharedObject object is named mySO and not SharedObject
//SharedObject.data.mySO = shared_data
mySO.data.yourName = shared_data

How to get java class in CF

I want to access the return value from a java method in my coldfusion file. I have loaded all the jar files in coldfusion file and got the java class object successfully. Using the class object, I want to access java class method which returns a Set; but I can't get any return value.
Here is my Java Code:
public Set getSession(String url) {
result+="hello";
try {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability("takesScreenshot", false);
caps.setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"E:\\TicketScraper\\phantomjs\\phantomjs.exe"
);
driver = new PhantomJSDriver(caps);
driver.get(url);
driver.findElement(By.id("login:loginName")).sendKeys("XXXX");
driver.findElement(By.id("login:password")).sendKeys("XXXX");
waitForJQueryProcessing(driver, 5);
driver.findElement(By.id("login:j_idt145")).click();
Thread.sleep(10000);
Set<org.openqa.selenium.Cookie> allCookies=driver.manage().getCookies();
for ( org.openqa.selenium.Cookie loadedCookie : allCookies) {
System.out.println(String.format("%s -> %s", loadedCookie.getName(),loadedCookie.getValue()));
}
} catch(Exception e) {
System.out.println(e);
}
return allCookies;
}
The java code runs the Phantom JS driver, logs in to the URL in the above code, and gets all cookies. All cookies are collected in a Set variable and returned from the method. I want to get this set variable in CF code.
But when I have tried to access the java method's Set variable in CF it doesn't return any value. By contrast, when I have commented out all the Phantom JS code and return only a String variable then CF can access the string value.
Here is my CF code:
<cfscript>
paths = arrayNew(1);
paths[1] = expandPath("lib\apache-mime4j-0.6.jar");
paths[2] = expandPath("lib\bsh-1.3.0.jar");
paths[3] = expandPath("lib\cglib-nodep-2.1_3.jar");
paths[4] = expandPath("lib\commons-codec-1.9.jar");
paths[5] = expandPath("lib\commons-collections-3.2.1.jar");
paths[6] = expandPath("lib\commons-exec-1.1.jar");
paths[7] = expandPath("lib\commons-io-2.4.jar");
paths[8] = expandPath("lib\commons-jxpath-1.3.jar");
paths[9] = expandPath("lib\commons-lang3-3.3.2.jar");
paths[10] = expandPath("lib\commons-logging-1.1.3.jar");
paths[11] = expandPath("lib\Counsel_Cookies_Phantom.jar");
paths[12] = expandPath("lib\cssparser-0.9.14.jar");
paths[13] = expandPath("lib\gson-2.3.jar");
paths[14] = expandPath("lib\guava-18.0.jar");
paths[15] = expandPath("lib\hamcrest-core-1.3.jar");
paths[16] = expandPath("lib\hamcrest-library-1.3.jar");
paths[17] = expandPath("lib\htmlunit-2.15.jar");
paths[18] = expandPath("lib\htmlunit-core-js-2.15.jar");
paths[19] = expandPath("lib\httpclient-4.3.4.jar");
paths[20] = expandPath("lib\httpcore-4.3.2.jar");
paths[21] = expandPath("lib\httpmime-4.3.4.jar");
paths[22] = expandPath("lib\ini4j-0.5.2.jar");
paths[23] = expandPath("lib\jcommander-1.29.jar");
paths[24] = expandPath("lib\jetty-websocket-8.1.8.jar");
paths[25] = expandPath("lib\jna-3.4.0.jar");
paths[26] = expandPath("lib\jna-platform-3.4.0.jar");
paths[27] = expandPath("lib\junit-dep-4.11.jar");
paths[28] = expandPath("lib\netty-3.5.7.Final.jar");
paths[29] = expandPath("lib\nekohtml-1.9.21.jar");
paths[30] = expandPath("lib\operadriver-1.5.jar");
paths[31] = expandPath("lib\phantomjsdriver-1.1.0.jar");
paths[32] = expandPath("lib\protobuf-java-2.4.1.jar");
paths[33] = expandPath("lib\sac-1.3.jar");
paths[34] = expandPath("lib\selenium-java-2.44.0.jar");
paths[35] = expandPath("lib\selenium-java-2.44.0-srcs.jar");
paths[36] = expandPath("lib\serializer-2.7.1.jar");
paths[37] = expandPath("lib\testng-6.8.5.jar");
paths[38] = expandPath("lib\xalan-2.7.1.jar");
paths[39] = expandPath("lib\xercesImpl-2.11.0.jar");
paths[40] = expandPath("lib\xml-apis-1.4.01.jar");
paths[41] = expandPath("lib\Selenium_Cookies.jar");
paths[42] = expandPath("lib\selenium-server-2.0b2.jar");
//writeDump(paths);
//create the loader
loader = createObject("component", "javaloader.JavaLoader").init(paths,true);
//writeDump(loader);
excelObject = loader.create("counsel_cookies_phantom.Counsel_Cookies_Phantom");
//writeDump(excelObject);
//abort;
</cfscript>
<cfdump var=#excelObject.getSession("https://pacer.login.uscourts.gov/csologin/login.jsf")#/>
<cfabort>
Please provide your suggestions of how to access the Phantom JS value in CF.
Assuming your Set is a java.util.Set, then calling toArray() would give you an array that's easily accessible in CF.
e.g.
<cfscript>
s = createObject("java", "java.util.HashSet").init();
s.add("foo");
s.add("bar");
s.add("bob");
arr = s.toArray();
writeDump(arr);
</cfscript>
Run this on TryCF.com

Java array[] with unknow size - what's wrong?

ImageItem imageItems[] = new ImageItem[data.length()];
for (int i=0; i<data.length(); i++) {
JSONObject object = data.getJSONObject(i);
Log.e("RESPONSE INFO::::", "id:" + object.get("id").toString());
imageItems[i].imageId = object.get("id").toString(); //NullPointerException
imageItems[i].imageURI = object.get("source").toString();
imageItems[i].thumbURI = object.get("picture").toString();
imageItems[i].createdTime = object.get("created_time").toString();
imageItems[i].link = object.get("link").toString();
}
Above is some kind of banal problem that can't resolve. Im still getting the NullPointerException at line with comment. At first I thought somethin's wrong with JSONobjects, but I'm sure that object.get("id").toString(); returns the right String. Something must be wrong with imageItems[] array.
ImageItem is a simple class with few String fields:
public class ImageItem {
public String imageId = null;
public String imageURI = null;
public String thumbURI = null;
public String createdTime = null;
public String link = null;
}
Any ideas what i'm missing here?
EDIT: I should mention that the ImageItem class is inner class of another class AlbumGallery. Now I'm getting error: No enclosing instance of type AlbumGallery is accessible. Must qualify the allocation with an enclosing instance of type AlbumGallery (e.g. x.new A() where x is an instance of AlbumGallery). with imageItems[i] = new ImageItem()
at the top of your for loop add imageItems[i] = gallery.new ImageItem()

Categories

Resources