Java Codemodel - Annotate a method or class - java

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

Related

Inspiring from GENERATED TALEND CLASS and Reuse in JAVA

I would like to get the value of from context in a new [java simple class] by inspiring from the seconde generated [talend class] :
I couldn't get filepath value because TALEND CLASS seems a little bit difficult to me ^^
My new java class
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import sapphire.util.DataSet;
public class LHCM_FX {
public static void main(String[] args) {
// Trying to get filepath here from context as TALEND JAVA GENERATED CLASS DO
String filepath = "C:/Users/Administrator/Desktop/Test/";
System.out.println("xmldataset=" + parseFXFile(filepath+"0.txt").toXML());
}
public static DataSet parseFXFile(String filepath) {
// Something Codes Here
}
TALEND GENERATED CLASS where filepath is declared
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import routines.LHCM_FX_ROUTINE;
import routines.TalendString;
import routines.system.IPersistableRow;
import routines.system.ResumeUtil;
import routines.system.TDieException;
import sapphire.util.DataSet;
public class LHCM_FX {
public final Object obj = new Object();
private Object valueObject = null;
private static final String defaultCharset = Charset.defaultCharset().name();
private static final String utf8Charset = "UTF-8";
private Properties defaultProps = new Properties();
private LHCM_FX.ContextProperties context = new LHCM_FX.ContextProperties();
private final String jobVersion = "0.1";
private final String jobName = "LHCM_FX";
private final String projectName = "CETEMCO";
public Integer errorCode = null;
private String currentComponent = "";
private final Map<String, Long> start_Hash = new HashMap();
private final Map<String, Long> end_Hash = new HashMap();
private final Map<String, Boolean> ok_Hash = new HashMap();
private final Map<String, Object> globalMap = new HashMap();
public final List<String[]> globalBuffer = new ArrayList();
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
private final PrintStream errorMessagePS;
private Exception exception;
public String resuming_logs_dir_path;
public String resuming_checkpoint_path;
public String parent_part_launcher;
private String resumeEntryMethodName;
private boolean globalResumeTicket;
public boolean watch;
public Integer portStats;
public int portTraces;
public String clientHost;
public String defaultClientHost;
public String contextStr;
public String pid;
public String rootPid;
public String fatherPid;
public String fatherNode;
public long startTime;
public boolean isChildJob;
private boolean execStat;
private ThreadLocal threadLocal;
private Properties context_param;
public Map<String, Object> parentContextMap;
public String status;
ResumeUtil resumeUtil;
public LHCM_FX() {
this.errorMessagePS = new PrintStream(new BufferedOutputStream(this.baos));
this.exception = null;
this.resuming_logs_dir_path = null;
this.resuming_checkpoint_path = null;
this.parent_part_launcher = null;
this.resumeEntryMethodName = null;
this.globalResumeTicket = false;
this.watch = false;
this.portStats = null;
this.portTraces = 4334;
this.defaultClientHost = "localhost";
this.contextStr = "Default";
this.pid = "0";
this.rootPid = null;
this.fatherPid = null;
this.fatherNode = null;
this.startTime = 0L;
this.isChildJob = false;
this.execStat = true;
this.threadLocal = new ThreadLocal();
Map threadRunResultMap = new HashMap();
threadRunResultMap.put("errorCode", (Object)null);
threadRunResultMap.put("status", "");
this.threadLocal.set(threadRunResultMap);
this.context_param = new Properties();
this.parentContextMap = new HashMap();
this.status = "";
this.resumeUtil = null;
}
public Object getValueObject() {
return this.valueObject;
}
public void setValueObject(Object valueObject) {
this.valueObject = valueObject;
}
public LHCM_FX.ContextProperties getContext() {
return this.context;
}
public String getExceptionStackTrace() {
if ("failure".equals(this.getStatus())) {
this.errorMessagePS.flush();
return this.baos.toString();
} else {
return null;
}
}
public Exception getException() {
return "failure".equals(this.getStatus()) ? this.exception : null;
}
public void tJavaFlex_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tJavaFlex_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tLogRow_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tLogRow_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tLabVantageLIMSCIPostData_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tJavaFlex_1_onSubJobError(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.resumeUtil.addLog("SYSTEM_LOG", "NODE:" + errorComponent, "", String.valueOf(Thread.currentThread().getId()), "FATAL", "", exception.getMessage(), ResumeUtil.getExceptionStackTrace(exception), "");
}
public void tJavaFlex_1Process(Map<String, Object> globalMap) throws LHCM_FX.TalendException {
globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", 0);
boolean execStat = this.execStat;
String iterateId = "";
String currentComponent = "";
try {
String currentMethodName = (new Exception()).getStackTrace()[0].getMethodName();
boolean resumeIt = currentMethodName.equals(this.resumeEntryMethodName);
if (this.resumeEntryMethodName == null || resumeIt || this.globalResumeTicket) {
this.globalResumeTicket = true;
LHCM_FX.row1Struct row1 = new LHCM_FX.row1Struct();
this.ok_Hash.put("tLabVantageLIMSCIPostData_1", false);
this.start_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
currentComponent = "tLabVantageLIMSCIPostData_1";
int tos_count_tLabVantageLIMSCIPostData_1 = 0;
DataSet dsData_tLabVantageLIMSCIPostData_1 = new DataSet();
dsData_tLabVantageLIMSCIPostData_1.addColumn("sdcid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("keyid1", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("paramlistid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("variantid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("paramtype", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("instrumentfield", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("value", 0);
this.ok_Hash.put("tLogRow_1", false);
this.start_Hash.put("tLogRow_1", System.currentTimeMillis());
currentComponent = "tLogRow_1";
int tos_count_tLogRow_1 = 0;
this.ok_Hash.put("tJavaFlex_1", false);
this.start_Hash.put("tJavaFlex_1", System.currentTimeMillis());
currentComponent = "tJavaFlex_1";
int tos_count_tJavaFlex_1 = 0;
DataSet ds = LHCM_FX_ROUTINE.parseFXFile(this.context.filepath);
int i_tLabVantageLIMSCIPostData_1;
String keyid1;
String instrumentfield;
for(int i = 0; i < ds.getRowCount(); ++i) {
currentComponent = "tJavaFlex_1";
row1.sdcid = ds.getValue(i, "sdcid", "");
row1.keyid1 = ds.getValue(i, "keyid1", "");
row1.paramlistid = ds.getValue(i, "paramlistid", "");
row1.variantid = ds.getValue(i, "variantid", "");
row1.paramtype = ds.getValue(i, "paramtype", "");
row1.instrumentfield = ds.getValue(i, "instrumentfield", "");
row1.value = ds.getValue(i, "value", "");
++tos_count_tJavaFlex_1;
currentComponent = "tLogRow_1";
++tos_count_tLogRow_1;
currentComponent = "tLabVantageLIMSCIPostData_1";
i_tLabVantageLIMSCIPostData_1 = dsData_tLabVantageLIMSCIPostData_1.addRow();
keyid1 = "";
instrumentfield = "";
keyid1 = "sdcid";
instrumentfield = row1.sdcid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "keyid1";
instrumentfield = row1.keyid1;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "paramlistid";
instrumentfield = row1.paramlistid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "variantid";
instrumentfield = row1.variantid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "paramtype";
instrumentfield = row1.paramtype;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "instrumentfield";
instrumentfield = row1.instrumentfield;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "value";
instrumentfield = row1.value;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
++tos_count_tLabVantageLIMSCIPostData_1;
currentComponent = "tJavaFlex_1";
}
this.ok_Hash.put("tJavaFlex_1", true);
this.end_Hash.put("tJavaFlex_1", System.currentTimeMillis());
currentComponent = "tLogRow_1";
this.ok_Hash.put("tLogRow_1", true);
this.end_Hash.put("tLogRow_1", System.currentTimeMillis());
currentComponent = "tLabVantageLIMSCIPostData_1";
String sWarningMessages_tLabVantageLIMSCIPostData_1 = "";
if ("LIMS CI".equals("LIMS CI") && (!dsData_tLabVantageLIMSCIPostData_1.isValidColumn("sdcid") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("keyid1") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("instrumentfield") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("value"))) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + "Error : In 'LIMS CI' case, the columns sdcid, keyid1, instrumentfield and value are mandatory. Please change the component schema.";
}
if ("LIMS CI".equals("Protocol Provider") && (!dsData_tLabVantageLIMSCIPostData_1.isValidColumn("instrumentfield") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("value"))) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + "Error : In 'Protocol Provider' case, the columns instrumentfield and value are mandatory. Please change the component schema.";
}
if (sWarningMessages_tLabVantageLIMSCIPostData_1.equals("")) {
for(i_tLabVantageLIMSCIPostData_1 = 0; i_tLabVantageLIMSCIPostData_1 < dsData_tLabVantageLIMSCIPostData_1.getRowCount(); ++i_tLabVantageLIMSCIPostData_1) {
keyid1 = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, "keyid1", "null");
instrumentfield = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, "instrumentfield", "null");
if ((!"LIMS CI".equals("LIMS CI") || !keyid1.equals("null")) && !instrumentfield.equals("null")) {
for(int j_tLabVantageLIMSCIPostData_1 = 0; j_tLabVantageLIMSCIPostData_1 < dsData_tLabVantageLIMSCIPostData_1.getColumnCount(); ++j_tLabVantageLIMSCIPostData_1) {
String columnid = dsData_tLabVantageLIMSCIPostData_1.getColumnId(j_tLabVantageLIMSCIPostData_1);
String value = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, columnid, "nullvalue");
String message = "";
if ("LIMS CI".equals("LIMS CI") && (columnid.equals("sdcid") || columnid.equals("keyid1") || columnid.equals("instrumentfield")) && (value == null || value.equals("") || value.equals("nullvalue"))) {
message = "Error : Invalid value : The column '" + columnid + "' can not be empty or null.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
}
if ("LIMS CI".equals("Protocol Provider")) {
if (!columnid.equals("instrumentfield") && !columnid.equals("value")) {
message = "Error : Invalid column '" + columnid + "'. In 'Protocol Provider' case, only 'instrumentfield' and 'value' columns are accepted.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
} else if (columnid.equals("instrumentfield") && (value == null || value.equals("") || value.equals("nullvalue"))) {
message = "Error : Invalid value : The column '" + columnid + "' can not be empty or null.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
}
}
}
} else {
dsData_tLabVantageLIMSCIPostData_1.deleteRow(i_tLabVantageLIMSCIPostData_1);
--i_tLabVantageLIMSCIPostData_1;
}
}
}
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.equals("")) {
System.out.println("Invalid data ! You must solve the following problems : ");
System.out.println(sWarningMessages_tLabVantageLIMSCIPostData_1);
}
System.out.println("xmldataset=" + dsData_tLabVantageLIMSCIPostData_1.toXML());
globalMap.put("tLabVantageLIMSCIPostData_1_NB_LINE", dsData_tLabVantageLIMSCIPostData_1.getRowCount());
this.ok_Hash.put("tLabVantageLIMSCIPostData_1", true);
this.end_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
}
} catch (Exception var22) {
throw new LHCM_FX.TalendException(var22, currentComponent, globalMap, (LHCM_FX.TalendException)null);
} catch (Error var23) {
throw new Error(var23);
}
globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", 1);
}
public static void main(String[] args) {
LHCM_FX LHCM_FXClass = new LHCM_FX();
int exitCode = LHCM_FXClass.runJobInTOS(args);
System.exit(exitCode);
}
public String[][] runJob(String[] args) {
int exitCode = this.runJobInTOS(args);
String[][] bufferValue = new String[][]{{Integer.toString(exitCode)}};
return bufferValue;
}
public int runJobInTOS(String[] args) {
String lastStr = "";
boolean hasContextArg = false;
String[] var7 = args;
int var6 = args.length;
for(int var5 = 0; var5 < var6; ++var5) {
String arg = var7[var5];
if (arg.toLowerCase().contains("--context=")) {
hasContextArg = true;
} else if (arg.equalsIgnoreCase("--context_param")) {
lastStr = arg;
} else if (lastStr.equals("")) {
this.evalParam(arg);
} else {
this.evalParam(lastStr + " " + arg);
lastStr = "";
}
}
if (this.clientHost == null) {
this.clientHost = this.defaultClientHost;
}
if (this.pid == null || "0".equals(this.pid)) {
this.pid = TalendString.getAsciiRandomString(6);
}
if (this.rootPid == null) {
this.rootPid = this.pid;
}
if (this.fatherPid == null) {
this.fatherPid = this.pid;
} else {
this.isChildJob = true;
}
try {
InputStream inContext = LHCM_FX.class.getClassLoader().getResourceAsStream("cetemco/lhcm_fx_0_1/contexts/" + this.contextStr + ".properties");
if (inContext != null) {
this.defaultProps.load(inContext);
inContext.close();
this.context = new LHCM_FX.ContextProperties(this.defaultProps);
} else if (hasContextArg) {
System.err.println("Could not find the context " + this.contextStr);
}
if (!this.context_param.isEmpty()) {
this.context.putAll(this.context_param);
}
this.context.filepath = this.context.getProperty("filepath");
} catch (IOException var12) {
System.err.println("Could not load context " + this.contextStr);
var12.printStackTrace();
}
if (this.parentContextMap != null && !this.parentContextMap.isEmpty() && this.parentContextMap.containsKey("filepath")) {
this.context.filepath = (String)this.parentContextMap.get("filepath");
}
this.resumeEntryMethodName = ResumeUtil.getResumeEntryMethodName(this.resuming_checkpoint_path);
this.resumeUtil = new ResumeUtil(this.resuming_logs_dir_path, this.isChildJob, this.rootPid);
this.resumeUtil.initCommonInfo(this.pid, this.rootPid, this.fatherPid, "CETEMCO", "LHCM_FX", this.contextStr, "0.1");
this.resumeUtil.addLog("JOB_STARTED", "JOB:LHCM_FX", this.parent_part_launcher, String.valueOf(Thread.currentThread().getId()), "", "", "", "", ResumeUtil.convertToJsonText(this.context));
long startUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long endUsedMemory = 0L;
long end = 0L;
this.startTime = System.currentTimeMillis();
this.globalResumeTicket = true;
this.globalResumeTicket = false;
try {
this.errorCode = null;
this.tJavaFlex_1Process(this.globalMap);
this.status = "end";
} catch (LHCM_FX.TalendException var11) {
this.status = "failure";
var11.printStackTrace();
this.globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", -1);
}
this.globalResumeTicket = true;
end = System.currentTimeMillis();
if (this.watch) {
System.out.println(end - this.startTime + " milliseconds");
}
endUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
int returnCode = false;
int returnCode;
if (this.errorCode == null) {
returnCode = this.status != null && this.status.equals("failure") ? 1 : 0;
} else {
returnCode = this.errorCode;
}
this.resumeUtil.addLog("JOB_ENDED", "JOB:LHCM_FX", this.parent_part_launcher, String.valueOf(Thread.currentThread().getId()), "", "" + returnCode, "", "", "");
return returnCode;
}
private void evalParam(String arg) {
if (arg.startsWith("--resuming_logs_dir_path")) {
this.resuming_logs_dir_path = arg.substring(25);
} else if (arg.startsWith("--resuming_checkpoint_path")) {
this.resuming_checkpoint_path = arg.substring(27);
} else if (arg.startsWith("--parent_part_launcher")) {
this.parent_part_launcher = arg.substring(23);
} else if (arg.startsWith("--watch")) {
this.watch = true;
} else {
String keyValue;
if (arg.startsWith("--stat_port=")) {
keyValue = arg.substring(12);
if (keyValue != null && !keyValue.equals("null")) {
this.portStats = Integer.parseInt(keyValue);
}
} else if (arg.startsWith("--trace_port=")) {
this.portTraces = Integer.parseInt(arg.substring(13));
} else if (arg.startsWith("--client_host=")) {
this.clientHost = arg.substring(14);
} else if (arg.startsWith("--context=")) {
this.contextStr = arg.substring(10);
} else if (arg.startsWith("--father_pid=")) {
this.fatherPid = arg.substring(13);
} else if (arg.startsWith("--root_pid=")) {
this.rootPid = arg.substring(11);
} else if (arg.startsWith("--father_node=")) {
this.fatherNode = arg.substring(14);
} else if (arg.startsWith("--pid=")) {
this.pid = arg.substring(6);
} else if (arg.startsWith("--context_param")) {
keyValue = arg.substring(16);
int index = true;
int index;
if (keyValue != null && (index = keyValue.indexOf(61)) > -1) {
this.context_param.put(keyValue.substring(0, index), keyValue.substring(index + 1));
}
}
}
}
public Integer getErrorCode() {
return this.errorCode;
}
public String getStatus() {
return this.status;
}
public class ContextProperties extends Properties {
public String filepath;
public ContextProperties(Properties properties) {
super(properties);
}
public ContextProperties() {
}
public void synchronizeContext() {
if (this.filepath != null) {
this.setProperty("filepath", this.filepath.toString());
}
}
public String getFilepath() {
return this.filepath;
}
}
private class TalendException extends Exception {
private Map<String, Object> globalMap;
private Exception e;
private String currentComponent;
private TalendException(Exception e, String errorComponent, Map<String, Object> globalMap) {
this.globalMap = null;
this.e = null;
this.currentComponent = null;
this.currentComponent = errorComponent;
this.globalMap = globalMap;
this.e = e;
}
public void printStackTrace() {
if (!(this.e instanceof LHCM_FX.TalendException) && !(this.e instanceof TDieException)) {
this.globalMap.put(this.currentComponent + "_ERROR_MESSAGE", this.e.getMessage());
System.err.println("Exception in component " + this.currentComponent);
}
if (!(this.e instanceof TDieException)) {
if (this.e instanceof LHCM_FX.TalendException) {
this.e.printStackTrace();
} else {
this.e.printStackTrace();
this.e.printStackTrace(LHCM_FX.this.errorMessagePS);
LHCM_FX.this.exception = this.e;
}
}
if (!(this.e instanceof LHCM_FX.TalendException)) {
try {
Method[] var4;
int var3 = (var4 = this.getClass().getEnclosingClass().getMethods()).length;
for(int var2 = 0; var2 < var3; ++var2) {
Method m = var4[var2];
if (m.getName().compareTo(this.currentComponent + "_error") == 0) {
m.invoke(LHCM_FX.this, this.e, this.currentComponent, this.globalMap);
break;
}
}
boolean var10000 = this.e instanceof TDieException;
} catch (SecurityException var5) {
this.e.printStackTrace();
} catch (IllegalArgumentException var6) {
this.e.printStackTrace();
} catch (IllegalAccessException var7) {
this.e.printStackTrace();
} catch (InvocationTargetException var8) {
this.e.printStackTrace();
}
}
}
// ............. More More code
}
}
Thank you in advance,
My bad!
I have the parameter filepath inside args of my : MAIN (String[] args)
so filepath = args[4]
Im sorry and thanks anyway :)

How to get all class on android app running

I just wanna get all class from my android project,someone suggest me to use dexfile,so,I try it.but it can not get all class ,for example,my packagename is "org.zj",I just wanna get some class which name start with "org.zj" but it response me "android.support.xxx" or "android.arch.xxx" .this is my code
public static List<Class> getClasses(Activity activity) {
List<Class> classes = new ArrayList<>();
try {
String packageName = activity.getPackageName();
System.out.println(packageName + " 包名");
//String packageCodePath = activity.getPackageCodePath();
classes.addAll(getClasses(packageName));
} catch (Exception e) {
e.printStackTrace();
}
return classes;
}
public static List<Class> getClasses(String packageName) {
List<Class> classes=new ArrayList<>();
List<DexFile> multiDex = getMultiDex();
for (DexFile df : multiDex) {
classes.addAll(getClassByDexFile(df,packageName));
}
return classes;
}
public static ArrayList<DexFile> getMultiDex() {
BaseDexClassLoader dexLoader = (BaseDexClassLoader) ClassUtil.class.getClassLoader();
Field f = ClassUtil.getField("pathList", "dalvik.system.BaseDexClassLoader");
Object pathList = getObjectFromField(f, dexLoader);
Field f2 = ClassUtil.getField("dexElements", "dalvik.system.DexPathList");
Object[] list = (Object[]) getObjectFromField(f2, pathList);
Field f3 = ClassUtil.getField("dexFile", "dalvik.system.DexPathList$Element");
ArrayList<DexFile> res = new ArrayList<>();
for (int i = 0; i < list.length; i++) {
DexFile d = (DexFile) getObjectFromField(f3, list[i]);
res.add(d);
}
return res;
}
public static List<Class> getClassByDexFile(DexFile dexFile, String packageName) {
List<Class> classes = new ArrayList<>();
DexFile df = dexFile;
//String regExp = "^" + packageName + ".\\w+$";
for (Enumeration iter = df.entries(); iter.hasMoreElements(); ) {
String className = (String) iter.nextElement();
System.out.println(className + "");
if (className.contains(packageName)) {
try {
classes.add(Class.forName(className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return classes;
}

how to remove 503 exceptions in java

I have a list of names in the form of a CSV and I am up for google searching those names using java. But the problem that i am facing is that when i initially run the code i am able to search the query but in the middle of the code the code starts to throw 503 exceptions and when i again run the code it starts throwing 503 exceptions from the very beginning.Here is the code that i am using.
public class ExtractInformation
{
static String firstname,middlename,lastname;
public static final int PAGE_NUMBERS = 10;
public static void readCSV()
{
boolean first = true;
try
{
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("E:\\KOLDump\\names.csv"));
String line = null;
String site = null;
while((line=br.readLine())!=null)
{
if(first)
{
first = false;
continue;
}
String[] b = line.split(splitBy);
firstname = b[0];
middlename = b[1];
lastname = b[2];
String name = null;
if(middlename == null || middlename.length() == 0)
{
name = firstname+" "+lastname+" OR "+lastname+" "+firstname.charAt(0);
}
else
{
name = firstname+" "+lastname+" OR "+lastname+" "+firstname.charAt(0)+" OR "+firstname+" "+middlename.charAt(0)+". "+lastname;
}
BufferedReader brs = new BufferedReader(new FileReader("E:\\KOLDump\\site.csv"));
while((site = brs.readLine()) != null)
{
if(first)
{
first = false;
continue;
}
String [] s = site.split(splitBy);
String siteName = s[0];
siteName = (siteName.replace("www.", ""));
siteName = (siteName.replace("http://", ""));
getDataFromGoogle(name.trim(), siteName.trim());
}
brs.close();
}
//br.close();
}
catch(Exception e)
{
System.out.println("unable to read file...some problem in the csv");
}
}
public static void main(String[] args)
{
readCSV();
}
private static void getDataFromGoogle(String query,String siteName)
{
Set<String> result = new HashSet<String>();
String request = "http://www.google.co.in/search?q="+query+" "+siteName;
try
{
Document doc = Jsoup.connect(request).userAgent("Chrome").timeout(10000).get();
Element query_results = doc.getElementById("ires");
Elements gees = query_results.getElementsByClass("g");
for(Element gee : gees)
{
Element h3 = gee.getElementsByTag("h3").get(0);
String annotation = h3.getElementsByTag("a").get(0).attr("href");
if(annotation.split("q=",2)[1].contains(siteName))
{
System.out.println(annotation.split("q=",2)[1]);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
any suggestions on how to remove this exceptions from the code would really be helpful.
If you wait a little do the 503's go away? If so, then you're probably being rate-limited by Google. https://support.google.com/gsa/answer/2686272?hl=en
You may need to put some kind of delay between requests.

Find the first and follow set of a given grammar in java

I have been given the problem to complete, and the algorithms to find the first and follow, but my problem is I cant quite find a data structure to implement to find these sets.
import java.util.Stack;
public class FirstFollowSet {
private final String[] term_tokens = { "begin", "end", ";", "if", "then", "else", "fi", "i", "=", "+", "-", "*",
"/", "(", ")", "const" };
private final static String[] non_term_tokens = { "Start", "Prog", "Block", "Body", "S", "E", "T", "F" };
private static RuleStack rules;
private Stack<String> firstSet;
private Stack<String> followSet;
private boolean is_terminal(String str) {
boolean test = false;
for (int i = 0; i < term_tokens.length; i++) {
if (str.equals(term_tokens[i]))
test = true;
}
return test;
}
private boolean is_non_term(String str){
for(int i = 0; i < non_term_tokens.length; i++)
{
if(str.equals(non_term_tokens[i]))
{
return true;
}
}
return false;
}
private class Rule{
String def, token;
public Rule()
{
def = "";
token = "";
}
public Rule(String d, String t)
{
def = d;
token = t;
}
public String getDef() {
return def;
}
public String getToken() {
return token;
}
public String toString()
{
String str = "";
str+= token + " " + def + '\n';
return str;
}
}
public class RuleStack{
Stack<Rule> rules;
public RuleStack(String grammar)
{
if(grammar.equals("G1"));
{
rules = new Stack();
Rule rule = new Rule("Prog", "Start");
rules.push(rule);
rule = new Rule("Block #", "Prog");
rules.push(rule);
rule = new Rule("begin Body end", "Block");
rules.push(rule);
rule = new Rule("begin S end", "Body");
rules.push(rule);
rule = new Rule("Body ; S", "Body");
rules.push(rule);
rule = new Rule("S", "Body");
rules.push(rule);
rule = new Rule("if E then S else S fi", "S");
rules.push(rule);
rule = new Rule("if E else S fi", "S");
rules.push(rule);
rule = new Rule("i = E", "S");
rules.push(rule);
rule = new Rule("Block", "S");
rules.push(rule);
rule = new Rule("E + T", "E");
rules.push(rule);
rule = new Rule("E * T", "E");
rules.push(rule);
rule = new Rule("T", "E");
rules.push(rule);
rule = new Rule("T * F", "T");
rules.push(rule);
rule = new Rule("T / F", "T");
rules.push(rule);
rule = new Rule("F", "T");
rules.push(rule);
rule = new Rule("const", "F");
rules.push(rule);
rule = new Rule("( E )", "F");
rules.push(rule);
}
}
}
public FirstFollowSet()
{
rules = new RuleStack("G1");
firstSet = new Stack();
followSet = new Stack();
}
public String FindFirstSet(String str, Stack<String> used)
{
if(used.contains(str))
{
return null;
}
String firstToken = "";
String win = "";
if(str.indexOf(" ") != -1)
firstToken = str.substring(0, str.indexOf(" "));
else
firstToken = str;
if(is_terminal(firstToken))
{
if(!(firstSet.contains(firstToken)))
win = firstToken;
if(win.equals("") != true)
firstSet.push(win);
}
else if(is_non_term(firstToken) && !(used.contains(firstToken)))
{
used.push(firstToken);
if(firstToken.equals("lambda"))
{
if(!(firstSet.contains(firstToken)))
win = firstToken;
}
else
{
RuleStack rules = new RuleStack("G1");
while(rules.rules.isEmpty() != true)
{
Rule winner = rules.rules.pop();
if(winner.token.equals(firstToken))
{
String test = FindFirstSet(winner.def, used);
if(!(test.equals("lambda")))
{
if(!(firstSet.contains(test)))
win = test;
}
}
}
}
}
return win;
}
public String findFollowSet(String str)
{
if(str.equals("S"))
{
followSet.push("$");
}
for(int i = 0; i < non_term_tokens.length; i++)
{
if(str.contains(non_term_tokens[i]))
{
int index = str.indexOf(non_term_tokens[i]);
Stack<String> used = new Stack();
FirstFollowSet test = new FirstFollowSet();
if(index > 0 && index < str.length()-1)
{
test.FindFirstSet(str, used);
while(test.firstSet.isEmpty() != true)
{
String token = firstSet.pop();
if(!(token.equals("lambda")))
test.followSet.push(token);
}
}
else if(index > 0 && index == str.length()-1)
{
}
}
}
}
public static void main(String[] args) {
FirstFollowSet test = new FirstFollowSet();
Stack<String> used = new Stack();
test.FindFirstSet("S", used);
while(test.firstSet.isEmpty() != true)
{
String str = test.firstSet.pop();
System.out.println(str);
}
}
}
This is the code I have so far, and the find first set works just fine, but the findfollowset method I'm not quite sure how to implement. The only idea I can seem to come up with is making a stack for each non-terminal symbol, apply the algorithm, and add each terminal symbol returned to the set it belongs to. This method just feel like its more work then necessary.
If anyone has ever solved this problem, or has seen a way to solve this problem I would just like to know what sort of data structure was used and how it the algorithm was implemented for said structure.
Thank you for taking the time to read this, and i appreciate any feedback given.
package modelo;
import java.util.ArrayList;
/**
*
* #author celeste
*/
public class Axioma {
public char getSimbolo() {
return simbolo;
}
public void setSimbolo(char simbolo) {
this.simbolo = simbolo;
}
public ArrayList<Character> getPrimeros() {
return primeros;
}
public void setPrimeros(ArrayList<Character> primeros) {
this.primeros = primeros;
}
public ArrayList<Character> getSiguientes() {
return siguientes;
}
public void setSiguientes(ArrayList<Character> siguientes) {
this.siguientes = siguientes;
}
public ArrayList<Character> getPredictivos() {
return predictivos;
}
public void setPredictivos(ArrayList<Character> predictivos) {
this.predictivos = predictivos;
}
public ArrayList<Character> getRegla() {
return regla;
}
public void setRegla(ArrayList<Character> regla) {
this.regla = regla;
}
private ArrayList<Character> primeros = new ArrayList<>();
private ArrayList<Character> siguientes = new ArrayList<>();
private ArrayList<Character> predictivos = new ArrayList<>();
private ArrayList<Character> regla = new ArrayList<>();
private char simbolo;
}

Searching Twitter with OAuth

Okay so I get an access token for Twitter each time I run my program...(It's tedious at the moment but I will find out how to make it a persistent store)... How do I go about using this access token so that when I search, I won't get a
"Rate limit exceeded. Clients may not make more than 150 requests per hour."
error?
It happens when I'm searching for the following: "https://api.twitter.com/1/users/show.json?screen_name=[screenName]"
Which is coded as :
BufferedReader ff = new BufferedReader( new InputStreamReader(ffUser.openConnection().getInputStream()));
In my code below:
public class UDC {
private static String term1;
private static String term2;
public static String PIN;
private static final String twitterSearch = "http://search.twitter.com/search.json?q=%23";
private static String rppPage = "&rpp=500&page=1";
private static final String ffGet = "https://api.twitter.com/1/users/show.json?screen_name=";
private static final String CONSUMER_KEY = "K7el7Fqu7UtcJv3A3ssOQ";
private static final String CONSUMER_SECRET = "w7ZX27ys58mafLYeivuA2POVe0gjhTIIUH26f2IM";
private static String entities = "&include_entities=true";
static Object[][] tableData = new Object[500][6];
static SearchResultC s = new SearchResultC();
static StringBuffer buff = new StringBuffer();
static StringBuffer buff1 = new StringBuffer();
public static void main (String args[]) throws Exception{
verifyURL v = new verifyURL();
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null; // = loadAccessToken(Integer.parseInt(args[0]));
//Twitter twitter = factory.getInstance);
//twitter.setOAuthConsumerKey(COMSUMER_KEY, COMSUMER_SECRET);
//twitter.setOAuthAccessToken(accessToken);
v.valURLText.setText(requestToken.getAuthorizationURL());
v.vFrame.setVisible(true);
int p = 0;
do {
//nothing
} while (v.vFrame.isVisible());
try {
if (PIN.length() > 0) {
accessToken = twitter.getOAuthAccessToken(requestToken, PIN);
} else {
accessToken = twitter.getOAuthAccessToken();
}
} catch (TwitterException te) {
if(401 == te.getStatusCode()) {
showErrorPane("Unable to get access code", "Error");
p = 1;
} else {
te.printStackTrace();
}
}
//storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
if (p == 0) {
initComponents();
UDTFrame.setVisible(true);
} else {
System.exit(0);
}
}
#SuppressWarnings({ "static-access"})
private static void searchButtonMouseClicked(String t1, String t2) throws IOException {
if(t1.equals("") || t2.equals("") || t1.equals(t2))
{
showErrorPane("Invalid Search Terms", "Search Error");
}
else
{
s.getInitComponents();
clicked(t1, 0);
clicked(t2, 3);
s.SRTFrame.setVisible(true);
s.sTerm1Field.setText(t1);
s.sTerm2Field.setText(t2);
}
}
#SuppressWarnings("static-access")
public static void clicked(String term, int t){
UDTFrame.setVisible(false);
float follower;
float friends;
float ffRatio;
float DUA;
int statuses;
int day;
int year;
String month;
try {
URL searchURL1 = new URL (twitterSearch + term + rppPage);
//String searchURL = new String (twitterSearch + term + rppPage);
BufferedReader br = new BufferedReader( new InputStreamReader(searchURL1.openConnection().getInputStream()));
//OAuthRequest request = new OAuthRequest(Verb.POST, searchURL);
int c;
while ((c=br.read()) != -1) {
buff.append((char)c);
}
br.close();
/*******************************************************************************************/
/*******************************************************************************************/
/******************************** follower/friend ratio ************************************/
/*******************************************************************************************/
/*******************************************************************************************/
JSONObject js = new JSONObject(buff.toString());
JSONArray tweets = js.getJSONArray("results");
JSONObject tweet = new JSONObject();
for(int i=0; i < tweets.length(); i++) {
tweet = tweets.getJSONObject(i);
//System.out.println(tweet);
//user[i] = tweet.getString("from_user_name");
//System.out.println(tweet.getString("from_user_name"));
//System.out.println(user[i]);
String userName = tweet.getString("from_user");
//URL ffUser = new URL(ffGet + user[i] + entities);
URL ffUser = new URL(ffGet + userName + entities);
String ffUser1 = new String(ffGet + userName + entities);
BufferedReader ff = new BufferedReader( new InputStreamReader(ffUser.openConnection().getInputStream()));
OAuthRequest request = new OAuthRequest(Verb.POST, ffUser1);
int d, e = 0;
while((d = ff.read()) != -1) {
buff1.append((char)d);
e++;
}
ff.close();
JSONObject js1 = new JSONObject(buff1.toString());
//System.out.println(js1);
//JSONArray userData = new JSONArray(buff1.toString());
//JSONObject userData1;
//for(int j = 0; j < js1.length(); i++){
//userData1 = userData.getJSONObject(j);
follower = js1.getInt("followers_count");
friends = js1.getInt("friends_count");
ffRatio = friends/follower;
String createdDate = js1.getString("created_at");
statuses = js1.getInt("statuses_count");
String nameData = js1.getString("name");
String gen = gender(nameData);
//}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm completely new to this OAuth and Access Tokens and all so any help will be much appreciated.
With
OAuthRequest request = new OAuthRequest(Verb.POST, ffUser1);
you are doing an unauthenticated request using the Scribe library (you never instantiated an OAuthService object which would have to be used to sign this request). So when you do this too often Twitter denies these requests.
So your problem here does indeed come from mixing Twitter4J and Scribe.

Categories

Resources