Parsing from MealMaster files in Java - java

Currently, I'm am trying to parse from MealMaster files, but I am having an issue where Ingredients are being parsed as:
"Inch thick" due to the next line not having a quantity or unit, and carrying on from the previous
Also, I'm finding ingredients that are listed as "ingredient1 or ingredient2" and I'm not sure how to catagorise these in the parser
Here is an example of a file I'm parsing from and my code below
https://pastebin.com/fhkRczya
public void readIngredients() {
try {
Remover remover = new Remover();
ArrayList<Ingredient> ing = new ArrayList<Ingredient>();
while(!( "".equals(line.trim()))) {
parsedIngredients = line + "\n";
if(!line.contains("---") && !line.contains(":")) {
Ingredient currentIng = splitLine();
if(currentIng.getQuantity().length() == 0 && !ing.isEmpty()) {
Ingredient lastIng = ing.get(ing.size()-1);
if (currentIng.getName().toLowerCase().contains("inch") ) {
//System.out.println(currentIng.getName());
lastIng.setOther(lastIng.getOther() + "," + currentIng.getQuantity() + "," +currentIng.getName());
//System.out.println("OTher " + lastIng.getOther());
}else{
String lastIngName = lastIng.getName();
String addName = lastIngName + " " + currentIng.getName();
lastIng.setName(addName);
lastIng = remover.removeTo(unitWords,lastIng);
lastIng = remover.removeCustomWords(lastIng);
}
}else if (currentIng.getName().startsWith("-") || currentIng.getName().startsWith("For") ){
if(ing.size()>0) {
Ingredient lastIng = ing.get(ing.size()-1);
lastIng.setOther(currentIng.getQuantity() + " " + currentIng.getName());
}
}else {
currentIng = remover.removeTo(unitWords,currentIng);
currentIng = remover.removeCustomWords(currentIng);
//currentIng.setName(currentIng.getName().replace(",", ""));
System.out.println(currentIng.getName());
ing.add(currentIng);
}
}
line = reader.readLine();
}
for(int i = 0; i < ing.size();i++) {
removeCommaColon(ing.get(i));
}
for(int i = 0; i<ing.size();i++) {
ingredientsString = ingredientsString + ing.get(i).getName() + "|" + currentRecipe.getTitle() + " \n";
//ingredientsString = ingredientsString + currentRecipe.getTitle() + "\n";
}
currentRecipe.setIngredients(ing);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

How to fix input getting cut off by output

So, I'm trying to create a function (If not pretty) IRC client using no libraries, written in Java. I've gotten almost everything working, the only problem is that I'm currently getting user input using System.in. And if someone else in the channel sends a message while I'm in the middle of typing, it cuts off what I currently have, and I need to guess where I am in the string. I want to know if there's a way to separate user input from the output of the program, so that this doesn't happen. This is the code in question:
new Thread(() -> {
while(connected[0]) {
String output = sc.nextLine();
if(!output.startsWith("~") && !output.startsWith("/")) {
try {
writeToSocket("PRIVMSG " + focused[0] + " " + output);
} catch (IOException e) {
e.printStackTrace();
}
}
if(output.substring(1).toLowerCase().startsWith("quit")) {
String[] split = output.substring(5).split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
if(i == 0) {
sb.append(split[i]);
}
sb.append(" ").append(split[i]);
}
try {
writeToSocket("QUIT " + sb.toString());
connected[0] = false;
} catch (IOException e) {
e.printStackTrace();
}
}else if(output.substring(1).toLowerCase().startsWith("focus")) {
String get = output.substring(7);
if(!channels.contains(get)) {
print("Not connected to channel");
}else {
try {
writeToSocket("PART " + focused[0]);
writeToSocket("JOIN " + get);
} catch (IOException e) {
e.printStackTrace();
}
focused[0] = get;
}
}else if(output.substring(1).toLowerCase().startsWith("join")) {
String get = output.substring(6);
channels.add(get);
}
if(output.startsWith("/") && output.substring(1).toLowerCase().startsWith("msg")) {
String[] split = output.substring(5).split(" ");
String username = split[0];
StringBuilder msg = new StringBuilder();
for(int i = 1; i < split.length; i++) {
if(i == 1) {
msg.append(split[i]);
continue;
}
msg.append(" ").append(split[i]);
}
try {
writeToSocket("PRIVMSG " + username + " " + msg.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();

Java Gui Text files Output

try {
String hour = (String) comboBox.getSelectedItem();
String filename = fileName.getText();
String date = ((JTextField)dateChooser.getDateEditor().getUiComponent()).getText();
String text = txtKeyword.getText();
String newline = "\n";
String directory = Directory.getText();
File path = new File(directory);
File[] faFiles = path.listFiles();
for(File file: faFiles){
**if(file.getName().contains(filename + "-" + date + "[" + hour + "]") == true == true || file.getName().contains(filename + "-" + date) || file.getName().contains(filename)){**
String line = null;
Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
if(line.contains(text)){
jTextArea1.append(line + newline);
btnClear.setEnabled(true);
btnExport.setEnabled(true);
}
}
br.close();
}
}
}
catch(Exception e){
}
Here is my question. I'm trying to use input and loop method to search for a file. The above code works but my problem is lets say I try to find 2 different text files
1. billing-20140527[09].txt has
a)XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)XGMS,2034-05-27 30:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
2. billing-20140527[10].txt has
a)XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)HELO
**I try to find the number 1 in both text files, if lets say I input the text file name is
billing, I can find the number 1 in both text file and output them:**
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b) XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
**However, if I specify the text file name: billing-20140527[09].txt and find the number 1 inside the text file, it will only output:
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.**
Can anyone help me with this? Guide or help?
I would work with the BufferedReader. Because it reads a whole line. And then you can split the line by a delimiter (lets say a space " " ). In your case I would write a split-method which receives a String and search for the regex you want.
private void doSearch(File f2) throws IOException,
fileHandler.FileException {
File[] children = f2.listFiles();
if (children != null && searching)
for (int i = 0; i < children.length; i++) {
if (g.isReady()) {
g.setReady(false);
if (!searching) {
g.setReady(true);
break;
} else if (isDirectory(children[i])) {
g.getActualDirectoryInhalt().setText(children[i].getPath()
.substring(g.root.getText().length()));
counterDirectories++;
doSearch(children[i]);
} else if (advancedSearch && !filterSpecified(children[i])) {
raiseCounterForDirectorySize(children[i]);
continue;
} else if (checkFile(children[i])) {
counterFiles++;
searchThroughFile(children[i], this.regex);
raiseCounterForDirectorySize(children[i]);
} else {
g.getTextAreaUnreachable().setText(
g.getTextAreaUnreachable().getText() + f2
+ "\n");
raiseCounterForDirectorySize(children[i]);
}
} else {
doSearch(children[i]);
}
g.setReady(true);
}
}
And here's the other method:
public static void searchThroughFile(File f2, String regex) throws IOException,
fileHandler.FileException {
try {
InputStream is = new BufferedInputStream(new FileInputStream(f2));
String mimeType = URLConnection.guessContentTypeFromStream(is);
ArrayList<String> linesFromFile = fileHandler.FileReaderer
.readFileIntoStringArrayList(f2);
String line = null;
if (f2.getAbsolutePath().contains(regex)) {
g.getTextAreaAdvanced()
.setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + "\n");
}
if (linesFromFile.size() != 0) {
for (int i = 0; i < linesFromFile.size(); i++) {
line = linesFromFile.get(i);
Pattern MY_Pattern = Pattern.compile(regex);
Matcher m = MY_Pattern.matcher(line);
if (!searching) {
break;
}
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
while (m.find() && searching) {
counterFoundPattern++;
g.getFoundFilesInhalt().setText(counterFoundPattern + "");
if (mimeType != null) {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + mimeType + " " + i+1 + "\n");
} else {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + i+1 + "\n");
}
}
g.setReady(true);
}
}
} catch (IOException e) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTabpane().setForegroundAt(2, Color.RED);
g.getTextAreaException().setText(
g.getTextAreaException().getText() + e + "\n");
g.setReady(true);
} catch (OutOfMemoryError oute) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTextAreaException().setText(
g.getTextAreaException().getText() + "\n"
+ "Fatal Error encured! The File will be skipped!"
+ "\n" + f2.getAbsolutePath());
g.getTabpane().setSelectedIndex(2);
g.setReady(true);
return;
}
}

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

Why does this code not work properly? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This part is supposed to add a train to the TRAININFO table in my database. I have to use mysql.
So there are some constraints I have to see before adding the train.
jTextField1.getText(); TrainNo. should not have more than 6 characters and it should be an integer.
jTextField2.getText(); TrainName. Should not have more than 30 characters.
jTextField10,jTextField12 have Depttime and araivaltime respectively.
It has 5 characters,"hr:mn" So I have to check if 'hr'<=24 and 'mn'<=59.
If the value of jTextField3.getText()==0 (number of ac1 coaches), then the trainfare for ac1 coaches (tfac1) should also be ==0.
Keeping this in mind I have tried to code it. but it doesn't work.
when ever i run this there is an error message .
Please do tell me where I am wrong.
stacktrace:[Ljava.lang.StackTraceElement;#e596c9
okay heres how it should work:
String m="-",t="-",w="-",th="--",f="-",st="--",s="-",runson;
if(jCheckBox1.isSelected()==true)
{
m="m";
}
if(jCheckBox2.isSelected()==true)
{
t="t";
}
if(jCheckBox3.isSelected()==true)
{
w="w";
}
if(jCheckBox4.isSelected()==true)
{
th="th";
}
if(jCheckBox5.isSelected()==true)
{
f="f";
}
if(jCheckBox6.isSelected()==true)
{
st="st";
}
if(jCheckBox7.isSelected()==true)
{
s="s";
}
runson=m+t+w+th+f+st+s;
int h1=Integer.valueOf(jTextField10.getText().substring(0,2));
int mins1=Integer.valueOf(jTextField10.getText().substring(3,5));
int h2=Integer.valueOf(jTextField12.getText().substring(0,2));
int mins2=Integer.valueOf(jTextField12.getText().substring(2,3));
String time1=jTextField10.getText().substring(0,2)+jTextField10.getText().substring
(2,3)+jTextField10.getText().substring(3,5);
String time2=jTextField12.getText().substring(0,2)+jTextField12.getText().substring
(2,3)+jTextField12.getText().substring(3,5);
String tfac1=jTextField13.getText();
String tfac2=jTextField14.getText();
String tfac3=jTextField15.getText();
String tfsl=jTextField16.getText();
if(Integer.valueOf(jTextField3.getText())==0)
{
tfac1="0";
}
if(Integer.valueOf(jTextField4.getText())==0)
{
tfac2="0";
}
if(Integer.valueOf(jTextField5.getText())==0)
{
tfac3="0";
}
if(Integer.valueOf(jTextField6.getText())==0)
{
tfsl="0";
}
try
{
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bvdb","root","enter");
Statement stm=con.createStatement();
int n=jTextField1.getText().trim().length();
int m=jTextField2.getText().trim().length();
if( n<=6 && m<=30 && h1<=24 && h2<=24 && mins1<=59 && mins2<=59 )
//This should check the constraints(1,2,3).if the condition is true the following statement will be executed ..else the catch block should be executed. But this doesn't seem to happen when i run the code. There is always an Exception raised.//
{
String q="INSERT INTO TRAININFO VALUE ("+jTextField1.getText()+",'"+jTextField2.getText()+"','"+jTextField9.getText()+"','"+time1+"','"+jTextField11.getText()+"','"+time2+"','"+runson+"',"+tfac1+","+tfac2+ ","+tfac3+","+tfsl+","+jTextField3.getText()+","+jTextField4.getText()+","+jTextField5.getText()+","+jTextField6.getText()+")";
stm.executeUpdate(q);
System.out.print("ADDED");
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(this,"Enter valid details");
}
s will always be - if !jCheckBox7.isSelected(). Think about it, you have:
if(something) {
...
} else {
s = ...;
}
if(something2) {
...
} else {
s = ...;
}
...
if(somethingN) {
...
} else {
s = "-"; //This will always be executed if !somethingN
}
You might want to have if.. else if instead of if below if.
Also note that it's not a good practice to compare boolean by writing == true. This might lead to problems if you, for example, write = instead of ==. Just write if(isTrue()) instead of if(isTrue() == true).
Basically you need to split your code into many functions. That will make it more readable.
Below is an example of how to structure your code, not a complete working code.
public void InsertTrainInfo() {
String runson = GetRunSon();
Boolean validTime1 = IsTimeValid(jTextField10.getText());
Boolean validTime2 = IsTimeValid(jTextField12.getText());
String time1 = GetTheTime(jTextField10.getText());
String time2 = GetTheTime(jTextField12.getText());
String tfac1 = GetFact(jTextField13.getText());
String tfac2 = GetFact(jTextField14.getText());
String tfac3 = GetFact(jTextField15.getText());
String tfsl = GetFact(jTextField16.getText());
try {
Class.forName("java.sql.DriverManager");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/bvdb", "root", "enter");
Statement stm = con.createStatement();
if (jTextField1.getText().trim().length() <= 6 && jTextField2.getText().trim().length() <= 30 && validTime1 && validTime2) {
String q = "INSERT INTO TRAININFO VALUE (" + jTextField1.getText() + ",'" + jTextField2.getText() + "','" + jTextField9.getText() + "','" + time1 + "','" + jTextField11.getText() + "','" + time2 + "','" + runson + "'," + tfac1 + "," + tfac2 + "," + tfac3 + "," + tfsl + "," + jTextField3.getText() + "," + jTextField4.getText() + "," + jTextField5.getText() + "," + jTextField6.getText() + ")";
stm.executeUpdate(q);
ResetFOrm();
}
} catch (Exception e) {
GetValidDetails();
}
}
Boolean IsTimeValid(String timetext) {
Boolean isOK = false;
try {
int h1 = Integer.valueOf(timetext.substring(0, 2));
int mins1 = Integer.valueOf(timetext.substring(3, 5));
isOK = (h1 <= 24 && mins1 <= 59);
} catch (Exception e) {
isOK = false;
}
return isOK;
}
String GetTheTime(String timetext) {
// do some basic length checks
return timetext.substring(0, 2) + timetext.substring(2, 3) + timetext.substring(3, 5);
}
String GetFact(String facttext) {
String fact = facttext;
if (Integer.valueOf(fact) == 0) {
fact = "0";
}
return fact;
}
void ResetFOrm() {
jTextField1.setEditable(true);
jButton1.setEnabled(true);
jButton2.setEnabled(false);
jButton4.setEnabled(false);
jTextField2.setEditable(false);
jTextField9.setEditable(false);
jTextField10.setEditable(false);
jTextField11.setEditable(false);
jTextField12.setEditable(false);
jTextField13.setEditable(false);
jTextField14.setEditable(false);
jTextField15.setEditable(false);
jTextField16.setEditable(false);
jTextField3.setEditable(false);
jTextField4.setEditable(false);
jTextField5.setEditable(false);
jTextField6.setEditable(false);
jCheckBox1.setEnabled(false);
jCheckBox2.setEnabled(false);
jCheckBox3.setEnabled(false);
jCheckBox4.setEnabled(false);
jCheckBox5.setEnabled(false);
jCheckBox6.setEnabled(false);
jCheckBox7.setEnabled(false);
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jTextField6.setText("");
jTextField7.setText("");
jTextField8.setText("");
jTextField9.setText("");
jTextField10.setText("");
jTextField11.setText("");
jTextField12.setText("");
jTextField13.setText("");
jTextField14.setText("");
jTextField15.setText("");
jTextField16.setText("");
}
void GetValidDetails() {
JOptionPane.showMessageDialog(this, "Enter valid details");
jTextField9.setEditable(true);
jTextField10.setEditable(true);
jTextField11.setEditable(true);
jTextField12.setEditable(true);
jTextField13.setEditable(true);
jTextField14.setEditable(true);
jTextField15.setEditable(true);
jTextField16.setEditable(true);
jTextField2.setEditable(true);
jTextField3.setEditable(true);
jTextField4.setEditable(true);
jTextField5.setEditable(true);
jTextField6.setEditable(true);
jCheckBox1.setEnabled(true);
jCheckBox2.setEnabled(true);
jCheckBox3.setEnabled(true);
jCheckBox4.setEnabled(true);
jCheckBox5.setEnabled(true);
jCheckBox6.setEnabled(true);
jCheckBox7.setEnabled(true);
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jTextField6.setText("");
jTextField7.setText("");
jTextField8.setText("");
jTextField9.setText("");
jTextField10.setText("");
jTextField11.setText("");
jTextField12.setText("");
jTextField13.setText("");
jTextField14.setText("");
jTextField15.setText("");
jTextField16.setText("");
jCheckBox1.setSelected(false);
jCheckBox2.setSelected(false);
jCheckBox3.setSelected(false);
jCheckBox4.setSelected(false);
jCheckBox5.setSelected(false);
jCheckBox6.setSelected(false);
jCheckBox7.setSelected(false);
}
String GetRunSon() {
String m = "-", t = "-", w = "-", th = "--", f = "-", st = "--", s = "-", runson;
if (jCheckBox1.isSelected()) {
m = "m";
}
if (jCheckBox2.isSelected()) {
t = "t";
}
if (jCheckBox3.isSelected()) {
w = "w";
}
if (jCheckBox4.isSelected()) {
th = "th";
}
if (jCheckBox5.isSelected()) {
f = "f";
}
if (jCheckBox6.isSelected()) {
st = "st";
}
if (jCheckBox7.isSelected()) {
s = "s";
}
runson = m + t + w + th + f + st + s;
return runson;
}

Twitter Stream API get 100 status and stop the exceution

I am using twitter4j twitter Streaming API to get the tweets for the specific tag.
I am having number of keywords. I want to search the 100 tweets thats containing that tag
currently what i am doing is i wrote code for getting the tweets for single word
public class StreamAPI {
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("xxxx");
cb.setOAuthConsumerSecret("xxxxx");
cb.setOAuthAccessToken("xxxx");
cb.setOAuthAccessTokenSecret("xxxx");
cb.setUseSSL(true);
cb.setUserStreamRepliesAllEnabled(true);
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
twitterStream.setOAuthAccessToken(accestoken);
StatusListener listener = new StatusListener() {
int countTweets = 0;
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
countTweets++;
System.out.println(countTweets);
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
#Override
public void onStallWarning(StallWarning stallWarning) {
//To change body of implemented methods use File | Settings | File Templates.
}
public void onException(Exception ex) {
ex.printStackTrace();
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = {"ipl"};
fq.track(keywords);
twitterStream.addListener(listener);
twitterStream.filter(fq);
}
}
how would i stop the process after it reaches the count 100 and should return that 100 tweet as list.
Please help me.
see the below code maybe helpfull for you
String token= "Key Word";
Query query = new Query(token);
FileWriter outFile = new FileWriter(token.replaceAll("^#","").concat(".txt"), true);
int numberOfTweets = 1500;
long lastID = Long.MAX_VALUE;
ArrayList<Status> tweets = new ArrayList<Status>();
while (tweets.size () < numberOfTweets) {
if (numberOfTweets - tweets.size() > 100)
query.setCount(100);
else
query.setCount(numberOfTweets - tweets.size());
try {
QueryResult result = twitter.search(query);
tweets.addAll(result.getTweets());
System.out.println("Gathered " + tweets.size() + " tweets");
for (Status t: tweets)
if(t.getId() < lastID) lastID = t.getId(); }
catch (TwitterException te) {
System.out.println("Couldn't connect: " + te); };
query.setMaxId(lastID-1);
}
PrintWriter out1 = new PrintWriter(outFile);
for (int i = 0; i < tweets.size(); i++) {
Status t = (Status) tweets.get(i);
GeoLocation loc = t.getGeoLocation();
String user = t.getUser().getScreenName();
String msg = t.getText();
String time = "";
if (loc!=null) {
Double lat = t.getGeoLocation().getLatitude();
Double lon = t.getGeoLocation().getLongitude();
System.out.println(i + " USER: " + user + " wrote: " + msg + " located at " + lat + ", " + lon);}
else
// System.out.println(i + " USER: " + user + " wrote: " + msg.replaceAll("\n",""));
out1.append(i + " USER: " + user + " wrote: " +msg.replaceAll("\n"," ") );
out1.print("\n");
}
System.out.println("file write succefully");

Categories