Get Values of variables under an Enum - java

I want to write into a file/print the constants of an enum, as well as the values of their variables.
For example, here is what I thought of doing:
id, field_name_1, field_name_2, ...
enum_id, field_value_1, field_value_2, ...
...
However, I am not fully sure on how to do such a thing, as I only recently began working with reflection.
This is the code that I currently have.
public static void writeEnum(String filename, Enum e, SnelPlugin plugin){
SnelTextFile file = new SnelTextFile(plugin, new File(plugin.getDataFolder() + "/" + filename + ".txt"));
Logger.debug("Starting an EnumWriter for " + filename + ".txt for plugin " + plugin.getPluginName());
try {
file.openWriter(true);
Field[] fields = e.getClass().getFields();
// HEADER
String info = "";
for(Field f: fields) {
info += ", " + f.getName();
Logger.debug("Detected value: " + f.getName());
}
info = info.replaceFirst(", ", "");
file.addLine(info);
// CONTENT
for(Object current: e.getDeclaringClass().getEnumConstants()){
Logger.debug(current.toString());
String result = "";
for(Field f: fields){
result += ", " + f.get(current);
}
result = result.replaceFirst(", ", "");
file.addLine(result);
Logger.debug("Added row: " + result);
}
}catch (Exception ex){
ex.printStackTrace();
}finally {
try {
file.closeWriter();
} catch (IOException e1) {
}
}
Logger.log(LColor.GREEN + "Finished an EnumWriter action on " + filename + ".txt from " + plugin.getPluginName());
}
Here is the Enum (APIPerm), which I setup for a simple test:
COMMANDS_SNELAPI,
COMMANDS_SNELAPI_INFO;
private String id;
APIPerm(){
id = getID();
}
#Override
public String getPrefix() {
return "snelapi";
}
#Override
public String getID(){
return getPrefix() + "." + this.toString().toLowerCase().replaceAll("_", ".");
}
However, I get an NPE in for(Object current: e.getDeclaringClass().getEnumConstants())
Thanks for your help,
Sneling.

Thanks to #Pshemo and #MarkusFisher, I've come to a solution.
Note that this method DOES include other classes and methods, but they don't affect the way this method works.
If you want to test for yourself:
Logger.debug can be replaced with System.out.println, LColor should
be deleted
SnelPlugin is only needed for the Logger.debug and locating a directory.
SnelTextFile is just a class to make creating text files easier. Remove if you're only printing.
Method Code:
public static <E extends Enum<E>> void writeEnum(String fileName, Class<E> c, SnelPlugin plugin){
SnelTextFile file = new SnelTextFile(plugin, new File(plugin.getDataFolder() + "/" + fileName + ".txt"));
Logger.debug("Starting EnumWriter for " + file.getFile().getName(), plugin);
try {
file.openWriter(true);
Logger.debug("Opened FileWriter", plugin);
Field[] classFields = c.getDeclaredFields();
String header = "Value";
for(Field f: classFields){
if(!Modifier.isStatic(f.getModifiers())) {
header += ", " + f.getName();
Logger.debug("Discovered variable '" + f.getName() + "'", plugin);
}
}
file.addLine(header);
file.addLine("");
for(E en: c.getEnumConstants()){
Logger.debug("Reading Enum Constant: " + en.toString(), plugin);
Field[] fields = en.getDeclaringClass().getDeclaredFields();
String current = en.toString();
for(Field f: fields){
if(!Modifier.isStatic(f.getModifiers())){
f.setAccessible(true);
current += ", " + f.get(en);
Logger.debug("Value for '" +f.getName() + "' = '" + f.get(en) + "'" , plugin);
}
}
file.addLine(current);
}
}catch (Exception ex){
ex.printStackTrace();
}finally {
try {
file.closeWriter();
Logger.debug("Closer FileWriter");
} catch (IOException ex) {
}
}
Logger.log(LColor.GREEN + "Finished EnumWriter for " + file.getFile().getName() + ". It can be found at " + file.getFile().getPath(), plugin);
}

If you want to get the values of the Enum, normally you would just call the values() method on the Enum class. But since you are starting with an instance you need to get the class and call it. I don't see any way to just cast the class to Enum, so I used reflection to get the public static Enum[] values() method like this.
/**
* Get the Enum values for this Enum instance.
* #param e the enum value
* #return all the values for this type of enum
*/
private Enum[] getValues(Enum e) {
Enum[] values = new Enum[0];
try {
Class<? extends Enum> enumClass = e.getDeclaringClass();
Method mtd = enumClass.getMethod("values");
values = (Enum[])mtd.invoke(null);
}
catch (Exception ex) {
ex.printStackTrace();
}
return values;
}
Obviously you should do better error handling. I am not sure what else you wanted from the Enum class in regards to fields.

Related

When using the JShare API, how do I get the field values for a specific file?

I'm trying to extend the GetFile example that comes with JShare to replicate the Properties page of a document where I can see the field names and values associated with the File. The Name and Title are available fields by default, and I've added some additional ones under Site Settings -> Site Columns, though I'd be happy with just getting (and setting) Name and Title for starters.
Trying to combine the GetFile example (below) with the GetFieldValues example (really just the service.getFieldValues() call), the getFieldValues() call seems to need a list id and and item id [getFieldValues(java.lang.String listId, int itemId)], to which I have neither for a com.independentsoft.share.File. How would I get the com.independentsoft.share.List that the File is in such that I can then get its field values?
Is there a better way to go about this? Thanks.
[Yes, I'm using my own servername, username, password.]
import com.independentsoft.share.File;
import com.independentsoft.share.Service;
import com.independentsoft.share.ServiceException;
public class Example {
public static void main(String[] args)
{
try
{
Service service = new Service("https://independentsoft.sharepoint.com", "username", "password");
File file = service.getFile("/Shared Documents/Test.docx");
System.out.println("Name: " + file.getName());
System.out.println("Title: " + file.getTitle());
System.out.println("MajorVersion: " + file.getMajorVersion());
System.out.println("MinorVersion: " + file.getMinorVersion());
System.out.println("Length: " + file.getLength());
System.out.println("LastModifiedTime: " + file.getLastModifiedTime());
System.out.println("CheckOutType: " + file.getCheckOutType());
System.out.println("CheckInComment: " + file.getCheckInComment());
}
catch (ServiceException ex)
{
System.out.println("Error: " + ex.getMessage());
System.out.println("Error: " + ex.getErrorCode());
System.out.println("Error: " + ex.getErrorString());
System.out.println("Error: " + ex.getRequestUrl());
ex.printStackTrace();
}
}
}
Okay, figured this out. The how is really convuluted....
import com.independentsoft.share.FieldValue;
import com.independentsoft.share.ListItem;
import com.independentsoft.share.Service;
import com.independentsoft.share.ServiceException;
public class Example
{
public static void main(String[] args)
{
try
{
Service service = new Service(...);
com.independentsoft.share.List pse = service.getListByTitle("Documents");
java.util.List<ListItem> items = service.getListItems(pse.getId());
for (ListItem item : items)
{
java.util.List<FieldValue> values = service.getFieldValues(pse.getId(), item.getId());
for (FieldValue value : values)
{
if (value.getName().equals("FileLeafRef") && value.getValue().equals("New File.txt"))
{
for (FieldValue mine : values)
{
System.out.println(mine.getName() + ": " + mine.getValue());
}
break;
}
}
}
}
catch (ServiceException ex)
{
System.out.println("Error: " + ex.getMessage());
System.out.println("Error: " + ex.getErrorCode());
System.out.println("Error: " + ex.getErrorString());
System.out.println("Error: " + ex.getRequestUrl());
ex.printStackTrace();
}
}
}

Java - Hibernate could not initialize proxy - no session

public List getPayslipsOfEmployees(String empids, Date paydate) {
initializeTransaction();
String strSQL = "SELECT "
+ " pd.* "
+ " FROM "
+ " payroll_d pd "
+ " INNER JOIN "
+ " payroll_h ph "
+ " ON pd.pay_uid = ph.pay_uid "
+ " WHERE pd.employee_id IN ("+empids+") "
+ " AND ph.pay_date = DATE('"+sql_dateformat.format(paydate)+"')";
SQLQuery q = session.createSQLQuery(strSQL);
q.addEntity("pd", PayrollD.class);
List pdlist = q.list();
commit();
List<Payslip> pslips = new ArrayList<Payslip>();
if (!pdlist.isEmpty()) {
Iterator it = pdlist.iterator();
while (it.hasNext()) {
try {
PayrollD payd = (PayrollD)it.next();
Payslip ps = new Payslip();
ps.setDepartment(payd.getEmployeeCatalog().getDepartmentCatalog().getDeptName());
ps.setEmployeeID(payd.getEmployeeCatalog().getEmployeeId());
ps.setEmployeeName(payd.getEmployeeCatalog().getEmpLastname(), payd.getEmployeeCatalog().getEmpFirstname(), payd.getEmployeeCatalog().getEmpMiddlename());
ps.setStartPayPeriod(payd.getPayrollH().getPayFromdate());
ps.setEndPayPeriod(payd.getPayrollH().getPayTodate());
ps.setDesignation(payd.getEmployeeCatalog().getJobDesignation());
EmployeeExemption exmptn = (EmployeeExemption)getCurrentExemption(payd.getEmployeeCatalog().getEmployeeId());
ps.setExemption((exmptn != null) ? exmptn.getExemptionCode() : SysConstants.DEFAULT_EXEMPTION);
List<PayslipEarning> earnings = new ArrayList<PayslipEarning>();
List<PayslipDeduction> deductions = new ArrayList<PayslipDeduction>();
ps.setNetPay(getPayslipNetPay(payd, earnings, deductions));
ps.setPrevTotalTaxableEarning(getPrevTotalTaxableEarning(payd));
ps.setTotalWithheld(getTotalWithheld(payd));
ps.setEarnings(earnings);
ps.setDeductions(deductions);
pslips.add(ps);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Somethings wrong " + e.getMessage());
}
}
}
return pslips;
}
I am getting this function by this funtion
private void generatePaySummary() {
try {
Map params = new HashMap();
params = getOrganizationInfo(params);
params.put("rptsubtitle", "Payroll Date: "+date_formatter.format(tbpaydate.getDate()));
int i = cboDept.getSelectedIndex();
int deptno = 0;
if (i != -1) deptno = (Integer)deptnos.get(i);
ReportService srv = new ReportService();
List empids = srv.getEmployeesInPayroll(deptno, tbpaydate.getDate());
if (!empids.isEmpty()) {
PayslipService.setEmployees(empids);
PayslipService.setPayDate(tbpaydate.getDate());
RepGenService repsrv = new RepGenService();
JRBeanCollectionDataSource jbsrc = new JRBeanCollectionDataSource(PaySummaryFactory.getPaySummary());
repsrv.generateReport(false, "/orgpayroll/reports/jasper/payrollsummary.jasper", true, params, jbsrc);
}
else
SysUtils.messageBox("No employees in payroll on "+date_formatter.format(tbpaydate.getDate())+"!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error" + e.getMessage());
}
}
When I try to run this function to get the payroll and employee information of the employee, it says Hibernate could not initialize proxy - no session. I can't find which one is causing the error. It works when I only process one employee of the same date, but when I process two employees on the same date, the error occurs.

Splitting String based on this six characters 0102**

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

create a zip file. and manage the output stream

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;
}

How to add names of class and function automatically to my log

I'm using android.util.Log
class Foo
{
private void boo()
{
// This is the basic log of android.
Log.i("tag", "Start");
}
}
I want the log should be printed [Foo::boo] Start.
Can I get the class and function name in Java? Then how do I wrap the code?
here
UPDATED
String tag = "[";
tag += this.getClass().toString();
tag += " :: ";
tag += Thread.currentThread().getStackTrace()[1].getMethodName().toString();
tag += "]";
Log.i(tag, "Message");
this.getClass().toString() will return class name as String
UPDATE
if function is static then use following code
String tag = "[";
tag += Thread.currentThread().getStackTrace()[1].getClassName().toString();
tag += " :: ";
tag += Thread.currentThread().getStackTrace()[1].getMethodName().toString();
tag += "]";
Log.i(tag, "Message");
Get The Current Class Name and Function Name :
Log.i(getFunctionName(), "Start");
private String getFunctionName()
{
StackTraceElement[] sts = Thread.currentThread().getStackTrace();
if(sts == null)
{
return null;
}
for(StackTraceElement st : sts)
{
if(st.isNativeMethod())
{
continue;
}
if(st.getClassName().equals(Thread.class.getName()))
{
continue;
}
if(st.getClassName().equals(this.getClass().getName()))
{
continue;
}
return mClassName + "[ " + Thread.currentThread().getName() + ": "
+ " " + st.getMethodName() + " ]";
}
return null;
}
You can use these methods of java.lang.Class class
getClass().getname() - to get the name of the class
getClass().getMethods() - to get the methods declared in that class.

Categories