I have the following class imp with inner class ScoringSummaryImplementation, when I tested the mean() method alone it works correctly, but when I test it as I show in the main method the answer goes incorrectly, I need to know the reason:
public class imp implements Normalizer {
public static List<BigDecimal> dataToBeNormalized = new ArrayList<>();
#Override
public ScoringSummary zscore(Path csvPath, Path destPath, String colToStandardize) {
ScoringSummary scoringObejct = new ScoringSummaryImplementation();
if (!Files.exists(csvPath)) {
throw new IllegalArgumentException("source file not found");
}
try {
readDataToBeNormalized(csvPath, destPath, colToStandardize);
} catch (IOException ex) {
Logger.getLogger(imp.class.getName()).log(Level.SEVERE, null, ex);
} catch (CsvValidationException ex) {
Logger.getLogger(imp.class.getName()).log(Level.SEVERE, null, ex);
}
//Z-score
for (int i = 0; i < dataToBeNormalized.size(); i++) {
BigDecimal sub = (dataToBeNormalized.get(i).subtract(scoringObejct.mean()));
try {
BigDecimal divide = sub.divide(scoringObejct.standardDeviation(), 2, RoundingMode.HALF_EVEN);
dataToBeNormalized.set(i, divide);
} catch (ArithmeticException e) {
}
}
return scoringObejct;
}
private void readDataToBeNormalized(Path csvPath, Path destPath, String colToStandardize) throws FileNotFoundException, IOException, CsvValidationException {
int indexOfTheCol = -1;
CSVReader reader = new CSVReader(new FileReader(csvPath.toString()));
String[] header = reader.readNext();
for (int i = 0; i < header.length; i++) {
if (header[i].equalsIgnoreCase(colToStandardize)) {
indexOfTheCol = i;
}
}
if (indexOfTheCol == -1) {
throw new IllegalArgumentException("column " + colToStandardize + " not found");
}
String[] values;
while ((values = reader.readNext()) != null) {
dataToBeNormalized.add(new BigDecimal(values[indexOfTheCol]));
}
}
//Inner class to implement ScoringSummary
public static class ScoringSummaryImplementation implements ScoringSummary {
#Override
public BigDecimal mean() {
BigDecimal sum = new BigDecimal("0");
BigDecimal sizeOfTheList = new BigDecimal(dataToBeNormalized.size());
for (int i = 0; i < dataToBeNormalized.size(); i++) {
sum = sum.add(dataToBeNormalized.get(i));
}
sum.divide(sizeOfTheList, 2, RoundingMode.HALF_EVEN);
return sum.divide(sizeOfTheList, 2, RoundingMode.HALF_EVEN);
}
}
}
// test in the main:
public class Test {
public static void main(String [] args){
Path p = Paths.get("C:\\Users\\DELL\\Documents\\GitHub\\J2EE\\demo\\src\\main\\java\\com\\mycompany\\demo\\d.csv");
Path p2 = Paths.get("C:\\Users\\DELL\\Documents\\GitHub\\J2EE\\demo\\src\\main\\java\\com\\mycompany\\demo\\des.csv");
Normalizer n1 = new imp ();
ScoringSummary n2 = n1.zscore(p, p2, "age");
BigDecimal mean = n2.mean();
System.out.println(mean);
}
}
Here is output:
0.82
Here is age column:
|age |
|5434|
|42423|
|54534|
|3333|
I am using CodeModel to programmatically generate .java files. This is a snippet of code to create a method:
JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");
//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");
When I run (assume all other necessary codes are there);
public String getCustomerInfo() { }
But I want to annotate above method like this:
#GET
#Path("/getCustomerInfo")
public String getCustomerInfo() { }
For which I tried below methods:
method.annotate(...) and method.annotate2(...)
But those methods accept only Class files as a arguments (ie like in the form SomeClass.class), but I want to be able to String as an argument and that class will be available dynamically at run time.
Say I should be able to do like this: method.annotate("Path").
Can anyone help me?
You can use JClass which can be constructed from a String or Class:
JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");
//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");
method.annotate(jCodeModel.ref("javax.ws.rs.GET"));
method.annotate(jCodeModel.ref("javax.ws.rs.Path")).param("value", "/getCustomerInfo");
or
method.annotate(jCodeModel.ref(javax.ws.rs.GET));
method.annotate(jCodeModel.ref(javax.ws.rs.Path)).param("value", "/getCustomerInfo");
There's also a variant that takes a JClass, so you have to either:
have the annotation on your classpath or
generate the annotation with the JCodeModel
As far as I can see, that's pretty much the same approach as with all other uses of classes, I don't see how annotations should be different here.
You can do on your Method something like this:
yourJMethod.annotate(YourClass.class);
public void setControllerMapping(Pagemaster pagemaster) throws Exception
{
// Instantiate a new JCodeModel
JCodeModel codeModel = new JCodeModel();
// Create a new class
JDefinedClass mappingController = codeModel._class("com.discom.springmvc.controllerTemp.ViewUrlController"+pagemaster.getUrl());
mappingController.annotate(codeModel.ref("org.springframework.stereotype.Controller"));
mappingController.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/");
mappingController.annotate(codeModel.ref("org.springframework.web.bind.annotation.SessionAttributes")).param("value", "roles");
JFieldVar jSearchDao = mappingController.field(JMod.NONE, SearchDao.class, "searchDao");
jSearchDao.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
JFieldVar jAddService = mappingController.field(JMod.NONE, AddService.class, "addService");
jAddService.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
JFieldVar httpSession = mappingController.field(JMod.PRIVATE, HttpSession.class, "httpSession");
httpSession.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
JFieldVar listService = mappingController.field(JMod.PRIVATE, ListService.class, "listService");
listService.annotate(codeModel.ref("org.springframework.beans.factory.annotation.Autowired"));
/*codeModel.directClass("java.util.Date");
codeModel.directClass("java.sql.Timestamp");
codeModel.directClass("org.springframework.http.HttpStatus");
codeModel.directClass("org.springframework.security.core.context.SecurityContextHolder");
codeModel.directClass("org.springframework.security.core.userdetails.UserDetails");
codeModel.directClass("com.fasterxml.jackson.databind.ObjectMapper");
codeModel.directClass("java.util.List");*/
JFieldVar saveDate = mappingController.field(JMod.NONE, Date.class, "saveDatee");
JFieldVar timeStampDate = mappingController.field(JMod.NONE, Timestamp.class, "timeStampDatee");
JFieldVar httpStatus = mappingController.field(JMod.NONE, HttpStatus.class, "httpStatuss");
JFieldVar securityContextHolder = mappingController.field(JMod.NONE, SecurityContextHolder.class, "securityContextHolder");
JFieldVar userDetails = mappingController.field(JMod.NONE, UserDetails.class, "userDetails");
JFieldVar objectMapper = mappingController.field(JMod.NONE, ObjectMapper.class, "objectMapperr");
JFieldVar listt = mappingController.field(JMod.NONE, List.class, "listt");
// Add Mapping method
JMethod mappingMethod = mappingController.method(JMod.PUBLIC, String.class, pagemaster.getUrl()+"URL");
JVar model = mappingMethod.param(ModelMap.class, "model");
mappingMethod.body().invoke(model, "addAttribute").arg("pagemaster").arg(jSearchDao.invoke("findPagemasterByUrl").arg(pagemaster.getUrl()));
mappingMethod.body().invoke(model, "addAttribute").arg("submenu").arg(jSearchDao.invoke("findSubMenuById").arg(jSearchDao.invoke("findPagemasterByUrl").arg(pagemaster.getUrl()).invoke("getSubmenuId").invoke("toString")));
mappingMethod.body().invoke(model, "addAttribute").arg("fieldsList").arg(jSearchDao.invoke("getTemplateFieldsList").arg(jSearchDao.invoke("findPagemasterByUrl").arg(pagemaster.getUrl()).invoke("getTemplateId").invoke("toString")));
mappingMethod.body()._return(JExpr.ref("\""+pagemaster.getUrl()+"Def\""));
mappingMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/"+pagemaster.getUrl()).param("method", RequestMethod.GET);
// Add Save method
JMethod saveMethod = mappingController.method(JMod.PUBLIC, codeModel.ref(ResponseEntity.class).narrow(String.class), "save"+pagemaster.getPageTitle().replace(" ", ""));
List<TemplateFields> reqFields = searchDao.getTemplateFieldsList(pagemaster.getTemplateId().toString());
for(TemplateFields tf:reqFields)
{
if(!tf.getFieldName().equals("id") && !tf.getFieldName().contains("created") && !tf.getFieldName().contains("updated"))
{
JVar reqParam = saveMethod.param(getDataType(tf.getFieldType()), tf.getFieldName());
if(tf.getIsNull()==false)
reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName());
else
reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName()).param("required", false);
}
}
Template template = reqFields.get(0).getTemplateId();
JFieldVar templateTableName = mappingController.field(JMod.NONE, codeModel.ref("com.discom.springmvc.pojo."+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)), template.getTablename()+"Obj");
saveMethod.body().directStatement("Date saveDate = new Date();");
saveMethod.body().directStatement("Timestamp timeStampDate = new Timestamp(saveDate.getTime());");
saveMethod.body().directStatement(template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" "+template.getTablename()+" = new "+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"();");
for(TemplateFields tf:reqFields)
{
if(tf.getFieldName().equals("id"))
{
saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(null);");
}
else if(tf.getFieldName().equals("createdBy") || tf.getFieldName().equals("updatedBy"))
{
saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(getPrincipal());");
}
else if(tf.getFieldName().equals("createdOn") || tf.getFieldName().equals("updatedOn"))
{
saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(timeStampDate);");
}
else
{
saveMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"("+tf.getFieldName()+");");
}
}
saveMethod.body().directStatement("boolean sts = false;");
saveMethod.body().directStatement("// create save method first");
saveMethod.body().directStatement("//sts = addService.save"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"("+template.getTablename()+");");
saveMethod.body().directStatement("if(sts==false){");
saveMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" not saved.\",HttpStatus.BAD_REQUEST);");
saveMethod.body().directStatement("}");
saveMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" Successfully saved.\",HttpStatus.OK);");
saveMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/save"+pagemaster.getPageTitle().replace(" ", "")).param("method", RequestMethod.POST);
// Add Update method
JMethod updateMethod = mappingController.method(JMod.PUBLIC, codeModel.ref(ResponseEntity.class).narrow(String.class), "update"+pagemaster.getPageTitle().replace(" ", ""));
for(TemplateFields tf:reqFields)
{
if(!tf.getFieldName().contains("created") && !tf.getFieldName().contains("updated"))
{
JVar reqParam = updateMethod.param(getDataType(tf.getFieldType()), tf.getFieldName());
if(tf.getIsNull()==false)
reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName());
else
reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName()).param("required", false);
}
}
updateMethod.body().directStatement("Date saveDate = new Date();");
updateMethod.body().directStatement("Timestamp timeStampDate = new Timestamp(saveDate.getTime());");
updateMethod.body().directStatement(template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" "+template.getTablename()+" = null; // create search methods //searchDao.find"+template.getTablename().substring(0, 1).toUpperCase()+template.getTablename().substring(1)+"ById(id.toString());");
for(TemplateFields tf:reqFields)
{
if(tf.getFieldName().equals("id"))
{
}
else if(tf.getFieldName().equals("updatedBy"))
{
updateMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(getPrincipal());");
}
else if(tf.getFieldName().equals("updatedOn"))
{
updateMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"(timeStampDate);");
}
else if(tf.getFieldName().equals("createdBy"))
{
}
else if(tf.getFieldName().equals("createdOn"))
{
}
else
{
updateMethod.body().directStatement(template.getTablename()+".set"+tf.getFieldName().substring(0, 1).toUpperCase() + tf.getFieldName().substring(1)+"("+tf.getFieldName()+");");
}
}
updateMethod.body().directStatement("boolean sts = false;");
updateMethod.body().directStatement("// create update method first");
updateMethod.body().directStatement("//sts = addService.update"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"("+template.getTablename()+");");
updateMethod.body().directStatement("if(sts==false){");
updateMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" not updated.\",HttpStatus.BAD_REQUEST);");
updateMethod.body().directStatement("}");
updateMethod.body().directStatement("return new ResponseEntity<>(\""+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" Successfully updated.\",HttpStatus.OK);");
updateMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/update"+pagemaster.getPageTitle().replace(" ", "")).param("method", RequestMethod.POST);
// Add DataTable List method
JMethod dtMethod = mappingController.method(JMod.PUBLIC, (codeModel.ref(String.class)), "list"+pagemaster.getPageTitle().replace(" ", ""));
dtMethod._throws(Exception.class);
JVar startReqParam = dtMethod.param(int.class, "start");
startReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam"));
JVar lengthReqParam = dtMethod.param(int.class, "length");
lengthReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam"));
JVar searchReqParam = dtMethod.param(String.class, "search");
searchReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", "search[value]");
List<String> filAssN = new ArrayList<String>();
List<String> filAssV = new ArrayList<String>();
String printS = "";
int fSize = 0;
for(TemplateFields tf:reqFields)
{
if(!tf.getFieldName().equals("id") && !tf.getFieldName().contains("created") && !tf.getFieldName().contains("updated"))
{
JVar reqParam = dtMethod.param(String.class, tf.getFieldName());
reqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", tf.getFieldName());
filAssN.add("list["+fSize+"]=null;");
filAssV.add("if("+tf.getFieldName()+"!=null && !"+tf.getFieldName()+".equals(\"\"))");
filAssV.add("list["+fSize+"]="+tf.getFieldName()+";");
if(fSize==0)
printS += "\""+tf.getFieldName()+" :\"+"+tf.getFieldName()+"";
else
printS += "+\" "+tf.getFieldName()+" :\"+"+tf.getFieldName()+"";
fSize++;
}
}
JVar datatReqParam = dtMethod.param(String.class, "datat");
datatReqParam.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestParam")).param("value", "datat");
dtMethod.body().directStatement("String list[]=new String["+fSize+"];");
for(String s:filAssN)
{
dtMethod.body().directStatement(s);
}
dtMethod.body().directStatement("System.out.println("+ printS +"+\" datat: \"+datat);");
for(String s:filAssV)
{
dtMethod.body().directStatement(s);
}
dtMethod.body().directStatement("DataTablesTO<"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"> dt = new DataTablesTO<"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+">();");
dtMethod.body().directStatement("String sessid=(String) httpSession.getId();");
dtMethod.body().directStatement(template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+" "+template.getTablename()+" = null; // create search methods //searchDao.find"+template.getTablename().substring(0, 1).toUpperCase()+template.getTablename().substring(1)+"ById(id.toString());");
dtMethod.body().directStatement("if(sessid!=null) {");
dtMethod.body().directStatement("String token= (String)httpSession.getAttribute(\"token\");");
dtMethod.body().directStatement("if(token.equals(datat)) {");
dtMethod.body().directStatement("List<"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"> accts = null; //create list method // listService.getAll"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"List(start,length, search, list);");
dtMethod.body().directStatement("int count = 0; //create list count method // listService.getAll"+template.getTablename().substring(0, 1).toUpperCase() + template.getTablename().substring(1)+"ListCount(search, list);");
dtMethod.body().directStatement("System.out.println(\"accts___ \"+accts.size()+\" count: \"+count);");
dtMethod.body().directStatement("dt.setAaData(accts);");
dtMethod.body().directStatement("dt.setiTotalDisplayRecords(count);");
dtMethod.body().directStatement("dt.setiTotalRecords(count);");
dtMethod.body().directStatement("dt.setsEcho(0);");
dtMethod.body().directStatement("}");
dtMethod.body().directStatement("}");
dtMethod.body().directStatement("System.out.println(\"toJson(dt)___ \"+toJson(dt));");
dtMethod.body().directStatement("return toJson(dt);");
dtMethod.annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping")).param("value", "/list"+pagemaster.getPageTitle().replace(" ", ""));
// getPrincipal Mapping method
JMethod principalMethod = mappingController.method(JMod.PRIVATE, String.class, "getPrincipal");
principalMethod.body().directStatement("String userName = null;");
principalMethod.body().directStatement("Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();");
principalMethod.body().directStatement("if (principal instanceof UserDetails) {");
principalMethod.body().directStatement("userName = ((UserDetails)principal).getUsername();");
principalMethod.body().directStatement("} else {");
principalMethod.body().directStatement("userName = principal.toString();");
principalMethod.body().directStatement("}");
principalMethod.body().directStatement("return userName;");
// getJson Mapping method
JMethod jsonMethod = mappingController.method(JMod.PRIVATE, String.class, "toJson");
//codeModel.ref(DataTablesTO.class).narrow(String.class)
jsonMethod.param(codeModel.ref(DataTablesTO.class).narrow(codeModel.ref(Object.class).wildcard()), "dt");
jsonMethod.body().directStatement("ObjectMapper mapper = new ObjectMapper();");
jsonMethod.body().directStatement("try {");
jsonMethod.body().directStatement("return mapper.writeValueAsString(dt);");
jsonMethod.body().directStatement("} catch (Exception e) {");
jsonMethod.body().directStatement("e.printStackTrace();");
jsonMethod.body().directStatement("return null;");
jsonMethod.body().directStatement("}");
// Generate the code
//JFormatter f = new JFormatter(codeModel.);
codeModel.build(new File("F:/UISOFT/uisoft/DISCOM/src/main/java/"));
//codeModel.build(new File(getPath()+"src/main/java/"));
}
public class AppendJavaCode {
public List<String> getExistingFileData(String permFile, String newPojoClassPath) throws Exception {
System.out.println("Existing File DATA...............................................\n");
List<String> listListFileAdd = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(new FileReader(permFile));
List<String> listListFile = new ArrayList<String>();
String str = in.readLine();
while (str!= null) {
listListFile.add(str);
str = in.readLine();
}
in.close();
int ii=0;
for(int i=0;i<listListFile.size();i++)
{
if(i==(listListFile.size()-1))
{
}
else
{
listListFileAdd.add(listListFile.get(i));
if(listListFile.get(i).contains("import") && ii==0)
{
listListFileAdd.add(newPojoClassPath);
ii++;
}
}
}
for(String s:listListFileAdd)
{
System.out.print(s+"\n");
}
} catch (Exception e) {
}
return listListFileAdd;
}
public List<String> getNewFileData(String tmpFile) throws Exception {
System.out.println("New File DATA...............................................\n");
List<String> listListFileAdd = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(new FileReader(tmpFile));
List<String> listListFile = new ArrayList<String>();
String str = in.readLine();
while (str!= null) {
listListFile.add(str);
str = in.readLine();
}
in.close();
int ind=0;
for(int i=0;i<listListFile.size();i++)
{
if(listListFile.get(i).contains("RequestMapping(va"))
{
ind = i;
break;
}
}
for(int i=0;i<listListFile.size();i++)
{
if(i>=ind)
{
listListFileAdd.add(listListFile.get(i));
}
}
for(String s:listListFileAdd)
{
System.out.print(s+"\n");
}
} catch (Exception e) {
}
return listListFileAdd;
}
public void appendDataInFile(String permFile, List<String> existedData, List<String> newData) throws Exception {
try {
// create a writer for permFile
BufferedWriter out = new BufferedWriter(new FileWriter(permFile, false));
for(int i=0;i<existedData.size();i++)
{
out.write(existedData.get(i)+"\n");
}
for(int i=0;i<newData.size();i++)
{
out.write(newData.get(i)+"\n");
}
out.close();
} catch (Exception e) {
}
}
public static void main(String[] args) throws Exception {
AppendJavaCode appendJavaCode = new AppendJavaCode();
// Define two filenames:
String permFile = "E:/ViewUrlController.java";
String tmpFile = "E:/ViewUrlControllerGen.java";
String newPojoClassPath = "import com.discom.springmvc.pojo.Studentinfo;";
List<String> existedData = appendJavaCode.getExistingFileData(permFile,newPojoClassPath);
List<String> newData = appendJavaCode.getNewFileData(tmpFile);
appendJavaCode.appendDataInFile(permFile, existedData, newData);
}
}
I have the following code to iterate over folders and files in the class path and determine the classes and get a field with a ID and print them out to a logger. This is working fine if I run this code in my IDE, but if I package my project into a JAR file and this JAR file into a EXE file with launch4j, I can't iterate over my classes again.
I get the following path if I try to iterate over my classes in the JAR/EXE file:
file:/C:/ENTWICKLUNG/java/workspaces/MyProject/MyProjectTest/MyProjectSNAPSHOT.exe!/com/abc/def
How can I achieve this to iterate over all my classes in my JAR/EXE file?
public class ClassInfoAction extends AbstractAction
{
/**
* Revision/ID of this class from SVN/CVS.
*/
public static String ID = "#(#) $Id ClassInfoAction.java 43506 2013-06-27 10:23:39Z $";
private ClassLoader classLoader = ClassLoader.getSystemClassLoader();
private ArrayList<String> classIds = new ArrayList<String>();
private ArrayList<String> classes = new ArrayList<String>();
private int countClasses = 0;
#Override
public void actionPerformed(ActionEvent e)
{
countClasses = 0;
classIds = new ArrayList<String>();
classes = new ArrayList<String>();
getAllIds();
Iterator<String> it = classIds.iterator();
while (it.hasNext())
{
countClasses++;
//here I print out the ID
}
}
private void getAllIds()
{
String tempName;
String tempAbsolutePath;
try
{
ArrayList<File> fileList = new ArrayList<File>();
Enumeration<URL> roots = ClassLoader.getSystemResources("com"); //it is a path like com/abc/def I won't do this path public
while (roots.hasMoreElements())
{
URL temp = roots.nextElement();
fileList.add(new File(temp.getPath()));
GlobalVariables.LOGGING_logger.info(temp.getPath());
}
for (int i = 0; i < fileList.size(); i++)
{
for (File file : fileList.get(i).listFiles())
{
LinkedList<File> newFileList = null;
if (file.isDirectory())
{
newFileList = (LinkedList<File>) FileUtils.listFiles(file, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
if (newFileList != null)
{
for (int j = 0; j < newFileList.size(); j++)
{
tempName = newFileList.get(j).getName();
tempAbsolutePath = newFileList.get(j).getAbsolutePath();
checkIDAndAdd(tempName, tempAbsolutePath);
}
}
}
else
{
tempName = file.getName();
tempAbsolutePath = file.getAbsolutePath();
checkIDAndAdd(tempName, tempAbsolutePath);
}
}
}
getIdsClasses();
}
catch (IOException e)
{
}
}
private void checkIDAndAdd(String name, String absolutePath)
{
if (name.endsWith(".class") && !name.matches(".*\\d.*") && !name.contains("$"))
{
String temp = absolutePath.replace("\\", ".");
temp = temp.substring(temp.lastIndexOf(/* Class prefix */)); //here I put in the class prefix
classes.add(FilenameUtils.removeExtension(temp));
}
}
private void getIdsClasses()
{
for (int i = 0; i < classes.size(); i++)
{
String className = classes.get(i);
Class<?> clazz = null;
try
{
clazz = Class.forName(className);
Field idField = clazz.getDeclaredField("ID");
idField.setAccessible(true);
classIds.add((String) idField.get(null));
}
catch (ClassNotFoundException e1)
{
}
catch (NoSuchFieldException e)
{
}
catch (SecurityException e)
{
}
catch (IllegalArgumentException e)
{
}
catch (IllegalAccessException e)
{
}
}
}
}
You cannot create File objects from arbitrary URLs and use the usual filesystem traversal methods. Now, I'm not sure if launch4j does make any difference, but as for iterating over the contents of plain JAR file, you can use the official API:
JarURLConnection connection = (JarURLConnection) url.openConnection();
JarFile file = connection.getJarFile();
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
JarEntry e = entries.nextElement();
if (e.getName().startsWith("com")) {
// ...
}
}
Above snippet lists all the entries in the JAR file referenced by url, i.e. files and directories.
Please review the following piece of code:
try {
db.beginTransaction();
db.execSQL(DBConstants.PRAG_FOR_KEYS_ON);
db.execSQL(DBConstants._BLDG_CREATE);
db.execSQL(DBConstants._BLDG_INDEX);
for(int x = 0; x < 28; x = x+1){
db.execSQL(DBConstants._BLDG_INSERT+x);
}
db.execSQL(DBConstants.PRAG_FOR_KEYS_OFF);
db.setTransactionSuccessful();
} catch (SQLException e) {
e.printStackTrace();
}finally{
db.endTransaction();
}
Each of the insert constants (representing a row of new data) are numbered thus:
public static final String _BLDG_INSERT0 = "<SQL insert statement>"
...all the way up to 28 ("_BLDG_INSERT28").
Is there ANY way i can execute these SQL statements in a for loop? If i can, how do i concactenate the number on to the name of the constant AND have it recognized by the java interpreter in the correct way?
Thanks!
It's not clear from the question whether you are able to change the constants. If you can, it would be better if you could put the statements in an array.
String[] _BLDG_INSERT = {"<SQL insert statement>", // 0
"<SQL insert statement>", // 1
...
"<SQL insert statement>" // 28
};
And then you can just access them like this.
for(int x = 0; x < 28; x = x+1){
db.execSQL(DBConstants._BLDG_INSERT[x]);
}
Or better still:
for(String s : DBConstants._BLDG_INSERT) {
db.execSQL(s);
}
public ArrayList<String> getAllRecord()
{
ArrayList<String> total = new ArrayList<String>();
Cursor cursor1 = null;
try
{
cursor1 = getDBobject().rawQuery(
"select * from "
+ Your table name + ";", null);
if (cursor1.moveToFirst())
{
do
{
String cid = cursor1.getString(1);
total.add(cid);
}
while (cursor1.moveToNext());
}
}
catch (Exception e)
{
System.out.println("" + TAG + " :" + e);
}
finally
{
if (cursor1 != null && !cursor1.isClosed())
{
cursor1.close();
}
}
return total;
}
This will return you all the datas according to your insertion order
Try something like this:
public class testeReflection {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException{
MyClass myClass = new MyClass();
Class aClass = MyClass.class;
for(int i = 0; i < 5; i++){
try {
Field field = aClass.getField("VAR" + i);
String s = (String)field.get(myClass);
System.out.println("myClass[" + i + "] = " + s);
} catch (NoSuchFieldException ex) {
Logger.getLogger(testeReflection.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(testeReflection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static class MyClass{
public static final String VAR0 = "VARIAVEL 01";
public static final String VAR1 = "VARIAVEL 02";
public static final String VAR2 = "VARIAVEL 03";
public static final String VAR3 = "VARIAVEL 04";
public static final String VAR4 = "VARIAVEL 05";
}
}
I am trying to learn something about JAVA and the best way to do this is creating something I would actually use and know what the purpose of it is.
I am trying to communicate with HyperV (WMI Library).
For example I found the following, my question is: how to use it? I am using Netbeans to create the GUI.
http://www.paulneve.com/wlab/javadoc/org/paulneve/wlab/virtualisation/VirtualisationAccessHyperVImpl.html
Also, how to load jInterop into my project so I can use it?
Thank you.
You can use JInterop for managing all operations of HyperV.
Download JInterop from here.
Add all JInterop jar files to your project build path.
Following is an example of getting all VMs of Hyper server:
public class ManageHyperV {
static final int RETURN_IMMEDIATE = 0x10;
static final int FORWARD_ONLY = 0x20;
private static final int STOP = 0;
private static final int START = 1;
static IJIDispatch msvmServices = null;
private static IJIDispatch createCOMServer(String namespace) { //root//virtualization
JIComServer comServer;
try {
JISystem.getLogger().setLevel(Level.WARNING);
JISystem.setAutoRegisteration(true);
JISession session = JISession.createSession(domainName,userName,password);
session.useSessionSecurity(false);
comServer = new JIComServer(valueOf("WbemScripting.SWbemLocator"),hostIP,session);
IJIDispatch wbemLocator = (IJIDispatch) narrowObject(comServer.createInstance().queryInterface(IID));
//parameters to connect to WbemScripting.SWbemLocator
Object[] params = new Object[] {
new JIString(hostIP),//strServer
new JIString(namespace),//strNamespace
// new JIString("ROOT\\CIMV2"),
JIVariant.OPTIONAL_PARAM(),//strUser
JIVariant.OPTIONAL_PARAM(),//strPassword
JIVariant.OPTIONAL_PARAM(),//strLocale
JIVariant.OPTIONAL_PARAM(),//strAuthority
new Integer(0),//iSecurityFlags
JIVariant.OPTIONAL_PARAM()//objwbemNamedValueSet
};
JIVariant results[] = wbemLocator.callMethodA("ConnectServer", params);
IJIDispatch wbemServices = (IJIDispatch) narrowObject(results[0].getObjectAsComObject());
return wbemServices;
} catch (JIException jie) {
System.out.println(jie.getMessage());
jie.printStackTrace();
} catch (JIRuntimeException jire) {
jire.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void getVMList() throws JIException {
String temp = "select * from Msvm_ComputerSystem";
String[] arrQuery = new String[]{temp};
for (int k=0;k<arrQuery.length;k++) {
Object[] params = new Object[] {
new JIString(arrQuery[k]),
JIVariant.OPTIONAL_PARAM(),
new JIVariant(new Integer(RETURN_IMMEDIATE + FORWARD_ONLY))
};
JIVariant[] servicesSet = msvmServices.callMethodA("ExecQuery", params);
iterateEnum(servicesSet);
}
}
private static void iterateEnum(JIVariant[] servicesSet) {
try {
IJIDispatch wbemObjectSet = (IJIDispatch) narrowObject(servicesSet[0].getObjectAsComObject());
JIVariant newEnumvariant = wbemObjectSet.get("_NewEnum");
IJIComObject enumComObject = newEnumvariant.getObjectAsComObject();
IJIEnumVariant enumVariant = (IJIEnumVariant) narrowObject(enumComObject.queryInterface(IJIEnumVariant.IID));
List<Object[]> respArr = getEnumIterations(enumVariant);
for (Object[] elements : respArr) {
JIArray aJIArray = (JIArray) elements[0];
JIVariant[] array = (JIVariant[]) aJIArray.getArrayInstance();
for (JIVariant variant : array) {
IJIDispatch wbemObjectDispatch = (IJIDispatch) narrowObject(variant.getObjectAsComObject());
JIVariant[] v = wbemObjectDispatch.callMethodA("GetObjectText_", new Object[] {});
System.out.println("----------------------------------------------------------------------");
System.out.println(v[0].getObjectAsString().getString());
System.out.println("----------------------------------------------------------------------");
}
}
} catch (JIRuntimeException e) {
e.printStackTrace();
} catch (JIException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
msvmServices = createCOMServer("root\\virtualization");
getVMList();
}
}
private static List<Object[]> getEnumIterations(IJIEnumVariant enumVariant) {
List<Object[]> list = new ArrayList<Object[]>();
int i=0;
for (i=0;i<100;i++) {
try {
list.add(enumVariant.next(1));
}catch (JIRuntimeException jre) {
break;
}
catch (JIException jie) {
break;
}
catch (Exception e) {
break;
}
}
return list;
}
Also, provide administrator username and password.
It should work.
Thanks.