How to Grab records from an object - java

I am having a very difficult time on figuring out how to get records from an object that i have passed in the path to the file.
import java.util.ArrayList;
import edu.trident.cpt237.recordreaper.CabRecordReaper;
public class CabOrginazer implements CabInfo
{
private final String FARE = "";
private final String GAS = "";
private final String SERVICE = "";
private final String MILES = "";
private final double VALUE = 0.0;
CabRecordReaper reaper = new CabRecordReaper("C:/CabRecords/September.txt" );
public void cabOrginazer()
{
}
#Override
public Records getType() {
// TODO Auto-generated method stub
return null;
}
#Override
public String getDate() {
// TODO Auto-generated method stub
return null;
}
#Override
public String CabId() {
// TODO Auto-generated method stub
return null;
}
#Override
public double getValue() {
// TODO Auto-generated method stub
return 0;
}
#Override
public double getPerGallonCost() {
// TODO Auto-generated method stub
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
I have try'd using a Scanner but does not work so i took it out. I can't do any of my other methods until i can grab what is in side of that reaper. The only methods inside of the CabRecordReaper is hasMoreRecord() which determines if there is more lines in the file.

I'm not quite understanding your question but I think you are having difficulties with reading from a .txt file?
try (BufferedReader reader = Files.newBufferedReader(Paths.get("path here")) {
String line = null;
while ((line = reader.readLine()) != null) {
// Add your code here.
System.out.println(true);
}
} catch (IOException e) {
e.printStackTrace();
}

Related

Storm bolt executes more than its parent

I have a Topology which contains a KafkaSpout and 2 bolts.
BoltParseJsonInput and its execute method:
public void execute(Tuple input) {
// TODO Auto-generated method stub
String data = input.getString(4);
js = new JSONObject(data);
String userId = js.getString("userId");
String timestamp = js.getString("timestamp");
counter++;
System.out.println(counter);
collector.emit(input, new Values(userId, timestamp));
collector.ack(input);
}
BoltInsertRedis and its execute method
public void execute(Tuple input) {
// TODO Auto-generated method stub
String userId = input.getStringByField("userId");
int timestamp = 0;
try {
timestamp = convertTimestampToEpoch(input.getStringByField("timestamp"));
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String timestep = this.prefix + timestamp/10;
String curTimestamp = jedis.hget(timestep, userId);
if(curTimestamp == null || Integer.parseInt(curTimestamp) < timestamp) {
jedis.hset(timestep, userId, Integer.toString(timestamp));
}
collector.ack(input);
}
BoltInsertRedis get the input from BoltParseJsonInput
builder.setBolt("ParseJsonInput-Bolt", new BoltParseJsonInput()).shuffleGrouping("Kafka-Spout");
builder.setBolt("BoltRedisUserLastActive-Bolt", new BoltRedisUserLastActive()).shuffleGrouping("ParseJsonInput-Bolt");
But when I submit this topology into Storm, BoltInsertRedis execute more than BoltParseJsonInput
Can you explain to me what is the problem here?
I found that my ParseJsonBolt had made an exception at message 25700 and it keeps replaying execution at that point. When I made a try catch, it works well

axis2 invokeNonBlocking NullPointerException

it is throw NullPointerException when i use RPCServiceClient and asynchronous call.But it is normal using RPCServiceClient.invokeBlocking.
my axis2 version is 1.6.4.
this is my code:
public void sendMsg(String xmldata, AxisCallback callback) throws AxisFault {
String webServiceURL = "http://171.8.212.68:8191/axis2/services/UserService";
String sendflag = "true";
if ("true".equals(sendflag)) {
RPCServiceClient serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
EndpointReference targetEPR = new EndpointReference(webServiceURL);
options.setTo(targetEPR);
Object[] opAddEntryArgs = new Object[]{xmldata};
QName opAddEntry = new QName("http://downstream.sysinterface.topsms.topnet.com", "sendMsg");
if (callback == null) {
callback = new AxisCallback() {
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("***********onComplete");
}
public void onError(Exception exception) {
// TODO Auto-generated method stub
exception.printStackTrace();
System.out.println("***********onError:"+exception.getMessage()+":"+ Arrays.toString(exception.getStackTrace()));
System.out.println(getStackTrace(exception));
}
public void onFault(MessageContext context) {
// TODO Auto-generated method stub
System.out.println("***********onFault");
}
public void onMessage(MessageContext context) {
// TODO Auto-generated method stub
System.out.println("***********onMessage");
}
};
}
serviceClient.invokeNonBlocking(opAddEntry, opAddEntryArgs, callback);
serviceClient.cleanupTransport();
serviceClient.cleanup();
}
}
Exception is below:
java.lang.NullPointerException
at org.apache.axis2.context.AbstractContext.needPropertyDifferences(AbstractContext.java:239)
at org.apache.axis2.context.AbstractContext.setProperty(AbstractContext.java:202)
at org.apache.axis2.transport.http.AbstractHTTPSender.getHttpClient(AbstractHTTPSender.java:568)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:157)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:396)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:223)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient$NonBlockingInvocationWorker.run(OutInAxisOperation.java:446)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:767)

Mismatch of return datatype

i am facing a problem regrading specifying the return data type. I have the FOComp class which implements callabale, the call() method of the 'FOComp' returns data type List<ArrayList<Mat>> as shown in the code of 'FOComp' class below.
and the method 'getResults()' returns data of type ArrayList<Mat> as shown in the code below. and currently, at run time, when I execute the code, I receive the folowing error:
Multiple markers at this line
The return type is incompatible with Callable<ArrayList<Mat>>.call()
The return type is incompatible with Callable<List<Mat>>.call()
kindly please let me know how to fix it.
'FOComp' class:
static class FOComp implements Callable<List<Mat>> {//should return list contains 4 mats(0,45,90,135)
private ArrayList<Mat> gaussianMatList = null;
private List<ArrayList<Mat>> results_4OrientAngles_List = null;
public FOComp(ArrayList<Mat> gaussianMatList) {
// TODO Auto-generated constructor stub
this.gaussianMatList = gaussianMatList;
this.results_4OrientAngles_List = new ArrayList<ArrayList<Mat>>();
}
public List<ArrayList<Mat>> call() throws Exception {
// TODO Auto-generated method stub
try {
featOrient = new FeatOrientation(this.gaussianMatList);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
featOrient.start();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.results_4OrientAngles_List.add(featOrient.getResults());
return results_4OrientAngles_List;
}
}
'getResults':
public ArrayList<Mat> getResults() {
if (this.crossAddOrientMapsList != null) {
if (!this.crossAddOrientMapsList.isEmpty()) {
if (this.crossAddOrientMapsList.size() == 4) {
double[] theta = new double[4];
theta[0] = 0;
theta[1] = 45;
theta[2] = 90;
theta[3] = 135;
for (int i = 0; i < this.crossAddOrientMapsList.size(); i++) {
MatFactory.writeMat(FilePathUtils.newOutputPath("FinalCrossAdd_" + theta[i]+"_degs"), this.crossAddOrientMapsList.get(i));
//ImageUtils.showMat(this.crossAddOrientMapsList.get(i), "OrientMap_" + theta[i] + " degs");
}
return this.crossAddOrientMapsList;
} else {
Log.WTF(TAG, "getResults", "crossAddOrientMapsList != 4 !!");
return null;
}
} else {
Log.E(TAG, "getResults", "crossAddOrientMapsList is empty.");
return null;
}
} else {
Log.E(TAG, "getResults", "crossAddOrientMapsList is null");
return null;
}
}
class FOComp implements Callable<List<Mat>>
and
public List<ArrayList<Mat>> call()
aren't really compatible... Your call() method should be
#Override public List<Mat> call()
Also, it is good practice to avoid implementation classes in method signatures, use the interfaces instead (in this case, use List rather than ArrayList). That will also fix your problem with one of the "multiple markers" :-)
Cheers,
You class declaration says that you are going to return a List of Mat (FOComp implements Callable<List<Mat>>), but your call method signature says you are going to return a List of ArrayList of Mat (List<ArrayList<Mat>>).
You will need to make them consistent.

Apache FTPClient and Apache FTPServer (JAVA)

Hello everyone my question is that I've created an FTP Server and FTPClient using Apache all in eclipse and everything seems to be working fine except the part when i try to upload a jar file which is for another code i wrote in java but it keeps corrupting and I've literally tried everything that i could find but it wouldn't work. So anybody who can help me or direct me to help would be greatly appreciated.
Thank You. I've attached both my Apache FTPServer code and FTPCLient again Thank You in advance.
serverFactory = new FtpServerFactory();
factory = new ListenerFactory();
factory.setPort(3232);
factory.setIdleTimeout(3000);
serverFactory.addListener("default", factory.createListener());
//serverFactory.setUserManager(addUser("jjj"));
userManagerFactory = new PropertiesUserManagerFactory();
//userManagerFactory.setFile(new File("C:/Users/Jean-Jacques/myusers.properties"));
userManagerFactory.setPasswordEncryptor(new PasswordEncryptor ()
{
public String encrypt(String password){
return password;
}
public boolean matches(String passwordTocheck, String storedpassword){
return passwordTocheck.equals(storedpassword);
}
});
serverFactory.setUserManager(addUser("jjj","hello"));
m = new HashMap<String, Ftplet>();
m.put("miaFtplet", new Ftplet()
{
#Override
public FtpletResult afterCommand(FtpSession session, FtpRequest request,
FtpReply reply) throws FtpException, IOException {
// TODO Auto-generated method stub
return FtpletResult.DEFAULT;
}
#Override
public FtpletResult beforeCommand(FtpSession session, FtpRequest request)
throws FtpException, IOException {
// TODO Auto-generated method stub
return FtpletResult.DEFAULT;
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void init(FtpletContext ftpletContext) throws FtpException {
// TODO Auto-generated method stub
}
#Override
public FtpletResult onConnect(FtpSession session) throws FtpException,
IOException {
// TODO Auto-generated method stub
return FtpletResult.DEFAULT;
}
#Override
public FtpletResult onDisconnect(FtpSession session)
throws FtpException, IOException {
// TODO Auto-generated method stub
return FtpletResult.DEFAULT;
}
});
server = serverFactory.createServer();
try{
server.start();
}catch(FtpException ex){
System.out.println("sorrty bro");
}
}
public UserManager addUser(String person, String pass) {
// TODO Auto-generated method stub
user = new BaseUser();
user.setName(person);
user.setPassword(pass);
//user.setHomeDirectory("C:/Users/Jean-Jacques/New Folder"); //by taking this out you can create any directory you want
userManagerFactory.setFile(new File("C:/Users/Jean-Jacques/myusers.properties"));
authorities = new ArrayList<Authority>();
authorities.add(new WritePermission());
user.setAuthorities(authorities);
um = userManagerFactory.createUserManager();
try{
um.save(user);
} catch(FtpException e){
}
return um;
}
here is the FTPCLient
private static void showServerReply(FTPClient ftpClient){
String[] replies = ftpClient.getReplyStrings();
if(replies != null && replies.length > 0){
for (String aReply : replies) {
System.out.println("Server: " + aReply);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String server = "localhost";
int port = 3232;
String user = "jjj";
String pass = "hello";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.enterLocalPassiveMode();
ftpClient.login(user, pass);
if(ftpClient.setFileType(FTP.BINARY_FILE_TYPE)){
System.out.print("bbbbbb");
}
ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
showServerReply(ftpClient);
System.out.println("binary");
int replyCode = ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. server reply code: " + replyCode);
return;
}
boolean gone = ftpClient.changeWorkingDirectory("/upload"); // this removes directory from root
if(gone){
System.out.println("gone");
} else{
}
File dod = new File("C:\\Users\\Jean-Jacques\\New Folder\\BattleShip.jar");
String file = "BattleShip.jar";
//try{
input = new FileInputStream(dod);
System.out.println("its uploading");
OutputStream output = ftpClient.storeFileStream(file);
byte[] bytein = new byte[8192];
int read =0;
while((read = input.read(bytein)) != -1){
output.write(bytein, 0, read);
}
input.close();
output.close();
boolean yo = ftpClient.completePendingCommand();
if(yo){
System.out.println("yo");
}
} catch (IOException ex) {
System.out.println("Oops! ");
ex.printStackTrace();
}
finally{
System.out.println("finally");
try {
if(ftpClient.isConnected()){
ftpClient.logout();
ftpClient.disconnect();
System.out.println("connected");}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Checking if a message contains a string

I have have a class that check id a phrase is contained in a message, I tried to do it with Matcher and Pattern and with String.contains(), but the results returned are odd.
Here is the class:
public class MotsClesFilter implements EmailFilter {
final String NAME = "Filtrage par mots cles";
/*private Pattern chaineSpam;
private Matcher chaineCourriel;*/
private int nbOccMotSpam;
private byte confidenceLevel;
#Override
public String getFilterName() {
return this.NAME;
}
#Override
public byte checkSpam(MimeMessage message) {
analyze(message);
if(this.nbOccMotSpam==0)
this.confidenceLevel = 1;
else if (this.nbOccMotSpam>0 && this.nbOccMotSpam<2)
this.confidenceLevel = CANT_SAY;
else if (this.nbOccMotSpam>1 && this.nbOccMotSpam<3)
this.confidenceLevel = 50;
else if (this.nbOccMotSpam>3 && this.nbOccMotSpam<4)
this.confidenceLevel = 65;
else if (this.nbOccMotSpam>4 && this.nbOccMotSpam<5)
this.confidenceLevel = 85;
else this.confidenceLevel = 90;
return (getConfidenceLevel());
}
public void analyze(MimeMessage message){
try {
List<String> listeChaines = new ArrayList<String>();
BufferedReader bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File("SpamWords.txt"))));
while(bis.ready()){
String ligne = bis.readLine();
listeChaines.add(ligne);
}
String mail = ((String.valueOf(message.getContent())));
//System.out.println(mail);
for (int j =0; j<listeChaines.size();j++){
//System.out.println(listeChaines.get(j));
Pattern chaineSpam = Pattern.compile(listeChaines.get(j),Pattern.CASE_INSENSITIVE);
Matcher chaineCourriel = chaineSpam.matcher(mail);
if (chaineCourriel.matches())
this.nbOccMotSpam++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public byte getConfidenceLevel() {
// TODO Auto-generated method stub
return this.confidenceLevel;
}
#Override
public boolean enabled() {
// TODO Auto-generated method stub
return true;
}
}
The results returned by checkSpam are always 1 if use matches and 90 if I use find, it also returns 90 when I use mail.contains(listeChaines.get(j)).
That means that the message doesn't match any of the strings in the file, but that there are at least 5 strings in the file that can be found inside the message.
matches() checks if the whole string matches the pattern. Not if some substring matches it.

Categories

Resources