Раньше писал все в одном классе, добавляя методы в нем. Теперь понадобилось сделать класс чтоб туда можно было передать параметр с любого места, обрабатывать, и возвращать опять куданить. Если это делаю отдельным методом то все работает, если отдельным классом нет. Первый класс - это с отдельным методом где все работает.
Код:
package ru.skyb.scripts.behavior;
import ru.bitel.bgbilling.kernel.event.Event;
import ru.bitel.bgbilling.kernel.script.server.dev.EventScriptBase;
import ru.bitel.bgbilling.modules.bill.server.events.BillCreatedEvent;
import ru.bitel.bgbilling.server.util.Setup;
import ru.bitel.common.sql.ConnectionSet;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Calendar;
import java.util.Locale;
import ru.dinkor.exchange.zoho.SearchUser;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import bitel.billing.server.contract.bean.*;
import bitel.billing.server.contract.bean.Contract;
import bitel.billing.server.contract.bean.ContractManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.math.BigDecimal;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class bill
extends EventScriptBase
{
private String PRODUCTID;
private int currentYear;
private String mounth;
private String comment;
private String format_number;
private String create_dt;
private String product;
//private String xmlDataString;
private String Invoice;
private String OBJECT;
private int created_bill_id;
public String OWNER;
private String OWNER_ID;
@Override
public void onEvent( Event event1, Setup setup2, ConnectionSet connectionSet3 )
throws Exception
{
Calendar c = Calendar.getInstance();//привильное создание календаря
currentYear = c.get(java.util.Calendar.YEAR);
c.add( Calendar.MONTH, -1 );
mounth = c.getDisplayName(Calendar.MONTH, Calendar.LONG, new Locale("ru"));
Connection con = connectionSet3.getConnection();
ContractParameterManager cpm = new ContractParameterManager( con );
//SearchUser su = new SearchUser();
//String owner_id = su.OWNER_ID;
//print("owner_id "+owner_id);
print (mounth);
//print ("currentYear"+currentYear);
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator( '.' );
DecimalFormat df = new DecimalFormat( "########0.00##", dfs );
int cid = event1.getContractId();
OWNER = cpm.getStringParam(cid, 76);
//this.OWNER=OWNER;
searchUser( OWNER );
OBJECT = cpm.getListParamValue(cid, 46);
StringBuilder DateMounth = new StringBuilder();
StringBuilder DateYear = new StringBuilder();
StringBuilder TotalSumm = new StringBuilder();
//StringBuilder SummNds = new StringBuilder();
StringBuilder ProductName = new StringBuilder();
//StringBuilder Quantity = new StringBuilder();
//StringBuilder List = new StringBuilder();
BigDecimal y = new BigDecimal("0.18");
//User user = new UserManager(con).getUsersMap().get(event1.getUserId());
created_bill_id = ((BillCreatedEvent) event1).getBillId();
print (" created_bill_id " + created_bill_id);
int j = 1;
//int user = event1.getUserId();
//int bce = new BillCreatedEvent(user,2,cid,3).getBillId();
//print(" bce.getBillId() "+bce.getBillId() + " user " + user);
String query = " select xml, format_number, create_dt from bill_data_2 "+
" where cid = " + cid + " AND id = " + created_bill_id;
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
String xml = new String( rs.getBytes(1), "windows-1251" );
format_number = rs.getString(2);
create_dt = rs.getString(3);
print (xml);
InputSource input = new InputSource(new StringReader(xml));
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(input);
doc.getDocumentElement().normalize();
ContractManager cm = new ContractManager(con);
Contract contract = cm.getContractById(cid);
comment = contract.getComment();
Element root = doc.getDocumentElement();
//print(root.getNodeName());
System.out.println("========================================================================");
/* NodeList nodeListBill = root.getElementsByTagName("bill");
for (int i = 0; i < nodeListBill.getLength(); i++) {
print("DEBUG: Iteration");
Node node = nodeListBill.item(i);
//print("DEBUG: Node Name :" + node.getNodeName());
if (node.getNodeName().equals("bill"))
{
NamedNodeMap attrs = node.getAttributes();
//print (attrs.getNamedItem("payer").getNodeValue());
AccountName.append( attrs.getNamedItem("payer").getNodeValue() );
//print (attrs.getNamedItem("summ").getNodeValue());
}
}*/
NodeList nodeListBill = root.getElementsByTagName("bill");
for (int i = 0; i < nodeListBill.getLength(); i++) {
print("DEBUG: Iteration");
Node node = nodeListBill.item(i);
//print("DEBUG: Node Name :" + node.getNodeName());
if (node.getNodeName().equals("bill"))
{
NamedNodeMap attrs = node.getAttributes();
//print (attrs.getNamedItem("month").getNodeValue());
DateMounth.append( attrs.getNamedItem("month").getNodeValue() );
DateYear.append( attrs.getNamedItem("yy").getNodeValue() );
TotalSumm.append( attrs.getNamedItem("total_sum").getNodeValue() );
//print (attrs.getNamedItem("summ").getNodeValue());
}
}
String xmlDataString = null;// Собирает строку продуктов включая все услуги
BigDecimal GrandTotal = new BigDecimal("0");// Общий итог по всему счету
BigDecimal Tax = new BigDecimal("0");//
BigDecimal SubTotal = new BigDecimal("0");
NodeList nodeListPos = root.getElementsByTagName("pos");
//NodeList nodeList = root.getChildNodes();
//for (int i = 0; i < nodeList.getLength(); i++) {
for (int i = 0; i < nodeListPos.getLength(); i++) {
//print("DEBUG: Iteration");
Node node = nodeListPos.item(i);
//print("DEBUG: Node Name :" + node.getNodeName());
if (node.getNodeName().equals("pos"))
{
NamedNodeMap attrs = node.getAttributes();
ProductName.append(attrs.getNamedItem("name").getNodeValue());
//String product = ProductName.toString();
//searchRecords( product );
product = attrs.getNamedItem("name").getNodeValue();
searchRecords( product );
//String summ = attrs.getNamedItem("summ").getNodeValue();
//print(Sum);
//Summ.append(Sum);
//String Quantitty = attrs.getNamedItem("quantity").getNodeValue();
//String text = summ.toString(); // example String
BigDecimal quantity = new BigDecimal(attrs.getNamedItem("quantity").getNodeValue());// количество в каждой услуге
BigDecimal summ = new BigDecimal(attrs.getNamedItem("summ").getNodeValue());// сумма по каждой услуге
BigDecimal list = quantity.multiply(summ);
BigDecimal tax = list.multiply(y);
BigDecimal total = quantity.multiply(summ);
GrandTotal = GrandTotal.add(total);
Tax = Tax.add(tax);
SubTotal = SubTotal.add(summ);
BigDecimal NetTotal = tax.add(total);
df.format(tax);
print ("summ " + summ );
//print("SubTotal " + df.format(SubTotal)+"\n"+" summ " + summ);
//print(" PRODUCTID " + PRODUCTID);
//List.append(quantity.multiply(summ).toString());
//SummNds.append(summ.multiply(у).toString());
//print ("Quantity " + attrs.getNamedItem("quantity").getNodeValue() +"\n" +
//print("value " + value.multiply(у));
//print (attrs.getNamedItem("name").getNodeValue());
//print (attrs.getNamedItem("summ").getNodeValue());
//print ("sum " + summ + " Quantity " + quantity + " list " + list + " tax " + tax);
xmlDataString = xmlDataString +
"<product no=\""+j+++"\">"+
"<FL val=\"Product Name\">"+product+"</FL>"+
"<FL val=\"Product Id\">"+PRODUCTID+"</FL>"+
"<FL val=\"Unit Price\">"+df.format(list)+"</FL>"+//Unit Price Цена за штуку
"<FL val=\"Quantity\">"+quantity.toString()+"</FL>"+
"<FL val=\"List Price\">"+df.format(list)+"</FL>"+
"<FL val=\"Tax\">"+df.format(tax)+"</FL>"+
"<FL val=\"Total\">"+df.format(total)+"</FL>"+
"<FL val=\"Net Total\">"+df.format(NetTotal)+"</FL>"+
"</product>";
print ( "<FL val=\"Unit Price\">"+df.format(summ)+"</FL>");
}
}
String AccountId ="";
updateRecords(df, xmlDataString,AccountId, GrandTotal, Tax, SubTotal, DateMounth.toString(), DateYear.toString(), y, TotalSumm.toString(), OWNER_ID );
}
rs.close();
ps.close();
}
public void updateRecords(DecimalFormat df, String xmlDataString, String AccountId, BigDecimal GrandTotal, BigDecimal Tax, BigDecimal SubTotal, String DateMounth, String DateYear, BigDecimal y,
String TotalSumm, String OWNER_ID )
{
BigDecimal GrandTotalNds = GrandTotal.multiply(y);
BigDecimal AllGrandTotal = GrandTotal.add(GrandTotalNds);
//SearchRecords sr = new SearchRecords();
//String owner_id = sr.OWNER_ID;
String authtoken = "218537c";
String scope = "crmapi";
String recordId = AccountId;//AccountId из запроса
String newFormat = "1";
String xmlData = "<Invoice>"+
"<row no=\"1\">"+
"<FL val=\"Subject\">Счёт за услуги Интернет за " + mounth +" "+ DateYear + "г.</FL>"+
"<FL val=\"Account Name\">"+comment+"</FL>"+
"<FL val=\"Invoice Date\">"+create_dt+"</FL>"+
"<FL val=\"Номер счёта\">"+format_number+"</FL>"+
"<FL val=\"Объект\">"+OBJECT+"</FL>"+
"<FL val=\"BGBill_Invoice_ID\">"+created_bill_id+"</FL>"+
"<FL val=\"SMOWNERID\">"+OWNER_ID+"</FL>"+
"<FL val=\"Tax\">"+df.format(Tax)+"</FL>"+
"<FL val=\"Grand Total\">"+AllGrandTotal+"</FL>"+
"<FL val=\"Sub Total\">"+df.format(SubTotal)+"</FL>"+
"<FL val=\"Product Details\">"+
xmlDataString +
"</FL>"+
"</row>"+
"</Invoice>";
//BigDecimal x = GrandTotal.multiply(y);
//BigDecimal grandtotal = new BigDecimal(TotalSumm);
//print ("df.format(Tax)" + df.format(Tax) + "\n" + "AllGrandTotal" + AllGrandTotal + "\n" + "df.format(SubTotal)" + df.format(SubTotal) +"\n"+ "DateMounth " + DateMounth +"\n" + "DateYear "+DateYear);
print ("xmlData " + xmlData);
String targetURL = "https://crm.zoho.com/crm/private/xml/Invoices/insertRecords";
String paramname = "content";
PostMethod post = new PostMethod(targetURL);
post.setParameter("authtoken",authtoken);
post.setParameter("scope",scope);
post.setParameter("newFormat",newFormat);
post.setParameter("id",recordId);
post.setParameter("xmlData",xmlData);
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
HttpClient httpclient = new HttpClient();
//PrintWriter myout = null;
//print ("xmlData + xmlDataString + tags " + xmlData );
try
{
long t1 = System.currentTimeMillis();
httpclient.executeMethod(post);
//------------Get response as a string ----------
String postResp = post.getResponseBodyAsString();
//print ("postResp=======>"+postResp);
//System.out.println("xmlDataString=======>"+ xmlDataString );
//System.out.println("cid=======>"+ cid );
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
//myout.close();
post.releaseConnection();
}
}
public void searchRecords( String product )
{
//try
//{
//"(Product name|=|\"Здесь полное название позиции из счета\")";
//----------------------------Fetch Auth Token ----------------------
String authtoken = "2187c";
String scope = "crmapi";
String selectColumns ="Products(Product Name, PRODUCTID)";
String searchCondition ="(Product Name|=|"+product+")";
String targetURL = "https://crm.zoho.com/crm/private/xml/Products/getSearchRecords";
String paramname = "content";
PostMethod post = new PostMethod(targetURL);
post.setParameter("authtoken",authtoken);
post.setParameter("scope",scope);
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
post.setParameter("selectColumns",selectColumns);
post.setParameter("searchCondition",searchCondition);
HttpClient httpclient = new HttpClient();
// Execute http request
try
{
long t1 = System.currentTimeMillis();
httpclient.executeMethod(post);
//System.out.println("HTTP Response status code: " + result);
//System.out.println(">> Time taken " + (System.currentTimeMillis() - t1));
//------------Get response as a string ----------
String postResp = post.getResponseBodyAsString();
//print("PostMethod=======>"+ searchCondition );
//print("postResp=======>"+postResp);
InputSource input = new InputSource(new StringReader(postResp));
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(input);
doc.getDocumentElement().normalize();
Element root = doc.getDocumentElement();
System.out.println(root.getNodeName());
System.out.println("========================================================================");
NodeList nodeList = root.getElementsByTagName("FL");
for (int i = 0; i < nodeList.getLength(); i++) {
//System.out.println("DEBUG: Iteration");
Node node = nodeList.item(i);
System.out.println(node.getNodeValue());
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) node;
//System.out.println("Parameter is: "
//+ eElement.getAttribute("val"));
//System.out.println("Value is: "
//+ node.getTextContent());
if (eElement.getAttribute("val").equals("PRODUCTID"))
{
String PRODUCTID = node.getTextContent();
this.PRODUCTID = PRODUCTID;
//print("PRODUCTID" + PRODUCTID);
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
post.releaseConnection();
}
}
public void searchUser( String OWNER )
{
//----------------------------Fetch Auth Token ----------------------
String authtoken = "27c";
String scope = "crmapi";
String type = "AllUsers";
String targetURL = "https://crm.zoho.com/crm/private/xml/Users/getUsers";
PostMethod post = new PostMethod(targetURL);
post.setParameter("authtoken",authtoken);
post.setParameter("scope",scope);
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
post.setParameter("type",type);
HttpClient httpclient = new HttpClient();
// Execute http request
try
{
long t1 = System.currentTimeMillis();
httpclient.executeMethod(post);
//System.out.println("HTTP Response status code: " + result);
//System.out.println(">> Time taken " + (System.currentTimeMillis() - t1));
//------------Get response as a string ----------
String postResp = post.getResponseBodyAsString();
//print("PostMethod=======>"+ searchCondition );
print("postResp=======>"+postResp);
InputSource input = new InputSource(new StringReader(postResp));
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(input);
doc.getDocumentElement().normalize();
Element root = doc.getDocumentElement();
print("root.getNodeName() "+root.getNodeName());
System.out.println("========================================================================");
NodeList nodeList = root.getElementsByTagName("user");
for (int i = 0; i < nodeList.getLength(); i++) {
//System.out.println("DEBUG: Iteration");
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE && node.getTextContent().equals(OWNER)) {
Element eElement = (Element) node;
print("eElement.getAttribute(\"id\") " + eElement.getAttribute("id"));
OWNER_ID = eElement.getAttribute("id");
//return OWNER_ID;
[color=#FF0000]this.OWNER_ID = OWNER_ID; [/color]
//System.out.println("Parameter is: "
//+ eElement.getAttribute("val"));
//System.out.println("Value is: "
//+ node.getTextContent());
//print("eElement.getAttribute()" + eElement.getAttribute());
//if (eElement.getAttribute("id").equals("207955000000033001"))
//{
//String PRODUCTID = node.getTextContent();
//this.PRODUCTID = PRODUCTID;
//print("user id" + node.getTextContent());
//}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
post.releaseConnection();
}
}
}
собственно последний метод мне нужно вынести в отдельный класс. Если я выношу в отдельный класс(если ставить его на событие он работает, а если просто класс, то нет)
Код:
package ru.dinkor.exchange.zoho;
import ru.bitel.bgbilling.kernel.event.Event;
import ru.bitel.bgbilling.kernel.script.server.dev.EventScriptBase;
import ru.bitel.bgbilling.server.util.Setup;
import ru.bitel.common.sql.ConnectionSet;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Calendar;
import java.util.Locale;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import bitel.billing.server.contract.bean.*;
import bitel.billing.server.contract.bean.Contract;
import bitel.billing.server.contract.bean.ContractManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.math.BigDecimal;
import ru.skyb.scripts.behavior.bill;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.*;
import java.net.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.PartSource;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.util.URIUtil;
public class SearchUser
{
public String OWNER_ID;
public void searchUser()
{
//TODO Сделать чтоб этот класс вызывался с других мест
bill b = new bill();
String owner = b.OWNER;
String authtoken = "21c";
String scope = "crmapi";
String type = "AllUsers";
String targetURL = "https://crm.zoho.com/crm/private/xml/Users/getUsers";
PostMethod post = new PostMethod(targetURL);
post.setParameter("authtoken",authtoken);
post.setParameter("scope",scope);
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
post.setParameter("type",type);
HttpClient httpclient = new HttpClient();
// Execute http request
try
{
long t1 = System.currentTimeMillis();
httpclient.executeMethod(post);
//------------Get response as a string ----------
String postResp = post.getResponseBodyAsString();
//print("PostMethod=======>"+ searchCondition );
//print("postResp=======>"+postResp);
InputSource input = new InputSource(new StringReader(postResp));
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(input);
doc.getDocumentElement().normalize();
Element root = doc.getDocumentElement();
//print("root.getNodeName() "+root.getNodeName());
System.out.println("========================================================================");
NodeList nodeList = root.getElementsByTagName("user");
for (int i = 0; i < nodeList.getLength(); i++) {
//System.out.println("DEBUG: Iteration");
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE && node.getTextContent().equals(owner)) {
Element eElement = (Element) node;
// print("eElement.getAttribute(\"id\") " + eElement.getAttribute("id"));
OWNER_ID = eElement.getAttribute("id");
//return OWNER_ID;
this.OWNER_ID = OWNER_ID;
System.out.println("OWNER_ID " + OWNER_ID);
//print("OWNER_ID " + OWNER_ID);
//System.out.println("Parameter is: "
//+ eElement.getAttribute("val"));
//System.out.println("Value is: "
//+ node.getTextContent());
//print("eElement.getAttribute()" + eElement.getAttribute());
//if (eElement.getAttribute("id").equals("207955000000033001"))
//{
//String PRODUCTID = node.getTextContent();
//this.PRODUCTID = PRODUCTID;
//print("user id" + node.getTextContent());
//}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
post.releaseConnection();
}
}
}
и вот так я в отдельный класс пытаюсь вынести, потом в том в котором нужно получить OWNER_ID делаю так
импортирую его
Код:
ru.dinkor.exchange.zoho.SearchUser
в методе где генерится событие пишу
Код:
public void onEvent( Event event1, Setup setup2, ConnectionSet connectionSet3 )
throws Exception
{
SearchUser su = new SearchUser();
String owner_id = su.OWNER_ID;
делаю принт и оно выводит null. Но помимо этого,
Код:
System.out.println("OWNER_ID " + OWNER_ID);
тоже не выводится, тоесть я так понимаю у меня даже класс не вызывается

как поправить?
_________________
Код:
Клиент: вер. 6.2.714 / 25.05.2015 17:27:15
os: Linux; java: Java HotSpot(TM) 64-Bit Server VM, v.1.8.0_45
Сервер: вер. 6.2.881 / 22.05.2015 17:56:55
os: Linux; java: Java HotSpot(TM) 64-Bit Server VM, v.1.8.0_45
Помощь по администрированию bgbilling в jabber конференции или Группа в telegramСтиль программирования - пьяный мастерстер
Разработка мобильных приложений