Matching a String in a text file, and return back the meaning of the word in the client part (Scala) - scala

I would like to solve a problem where the client will send a word to the server, and server will run through the text file and return the meaning of the word that is typed by the user. My problem is when a matching word is typed, i will return the match word meaning, at the same time return back other "Word not found" (which is my control statement). So i would like to just return the meaning of the word only if the word is matched and found
Heres my code:
Server part
Future {
//store local socket references for processing
val client = socket
try {
// Get a communication stream associated with the socket
val is = new BufferedReader(new InputStreamReader(client.getInputStream))
// Get a communication stream associated with the socket
val os = new PrintStream(client.getOutputStream)
val inFile = new File(filename)
val readFile = new Scanner(inFile)
var input : String = null;
while (true) {
// Read from input stream
var line: String = is.readLine() // read the word from client
println("The client send " + line)
while (readFile.hasNext()) {
input = readFile.nextLine()
println("From the file " + input)
if (input.contains(line)) {
os.println(input)
os.flush()
}
else{
os.println("Word not found")
}
}
}
} catch {
case e: Exception => e.printStackTrace
} finally {
// Close the connection, but not the server socket
client.close()
}
}
Client Part
val is = new BufferedReader(new InputStreamReader(client.get.getInputStream))
val os = new PrintStream(client.get.getOutputStream) // write to server a strin
println("Please Input Ur word ")
val user = readLine
os.println(user)
while (true) {
var line: String = is.readLine() //receive string from server
println(line)
}
My text file is formatted this way:
super-very good or pleasant; excellent.

Use the following approach:
var found = false;
while (readFile.hasNext() && !found) {
input = readFile.nextLine()
println("From the file " + input)
if (input.contains(line)) {
os.println(input)
os.flush()
found = true;
}
}
if(!found) {
os.println("Word not found")
os.flush()
}
There are much more beautiful ways to do this, but as you seem to be a beginner, this is the simplest solution possible.
If you are interested in a functional approach, I will gladly help.
Hope this helps.

Related

data exchange using socket between Julia and Groovy

Recently I'm trying to use a socket to exchange data between a solver in Julia as a server and a client in Groovy. Im new to the socket concept and both the language. The thing is that it seems that once julia server done 'readLine()', the socket close and the 'write()' cannot proceed. I cannot send messages to the Groovy client nor exchange data.
Server code(Julia):
using Sockets
server = listen(2000)
while true
conn = accept(server)
println("connection accepted")
#async begin
try
line = readlines(conn)
println(line)
str = "server"
write(conn,str)
println("write done")
sleep(2)
catch err
print("connection ended with error $err")
sleep(2)
end
end
end
Client code(Groovy):
class groovy_client {
static void main(String[] args) {
while (true) {
try {
dataTransfer()
println 'dataTransfer success'
}catch (e) {
println(e)
sleep(2000)
}
}
}
private static void dataTransfer() {
Socket s = new Socket('localhost', 2000)
println 'connect to the server'
s.withStreams { input, output ->
// BufferedReader reader = new BufferedReader(new InputStreamReader(input))
// str = reader.readLine()
// println(str)
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output))
writer.write('Hi server')
writer.flush()
input.withReader{reader ->
str = reader.readLine()
println 'haha'
println(str)
// def reader = input.newReader()
// def buffer = reader.readLine()
// println "server: $buffer"
sleep(2000)
}
println 'disconnect'
}
}
}
And I also have a doubt about how the socket works. Do server and client send and receive messages at the same time? Like server tells the client to add 1 to int_a while client send int_a back to the sender. Does int_a remain the original value or with 1 added and sent to the server?

Sending the error in case of GRPC with full duplex ReadStream and WriteStream

Can someone help me understand how I can send the error in case of full duplex with ReadStream and WriteStream.
This is the sample proto file.
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.pace.vertx.grpc.generated";
package com.pace.vertx.grpc.generated;
service ArrangementService {
rpc GetArrangementDetails (stream ArrangementRequest) returns (stream ArrangementAllDetails) {}
}
message ArrangementRequest {
string arrangementId = 1;
}
message ArrangementAllDetails {
string arrangementDetails = 1;
}
This is the code I have so far.
BindableService vertxArrangementServiceGrpc = new VertxArrangementServiceGrpc.ArrangementServiceVertxImplBase() {
#Override
public void getArrangementDetails(ReadStream<ArrangementRequest> request, WriteStream<ArrangementAllDetails> response) {
Pump.pump((ReadStream)request, response).start();
request.handler(arrangementRequest -> {
couchbaseDAO.getReactiveCollection()
.get(arrangementRequest.getArrangementId())
.map(getResult -> getResult
.contentAsObject()
.removeKey("key_tx")
.removeKey("version"))
.subscribe(
jsonObject -> response.end(ArrangementAllDetails.newBuilder().setArrangementDetails(jsonObject.toString()).build()),
error -> ?????
);
});
}
}
.withCompression("gzip");
How can I send the error back in the error subscription block ?
This answer to "Pattern for rich error handling in gRPC" question might be helpful.

Reading Emails based on recipient email id in Jmeter using groovy

I have a Jmeter script which follows the following steps
1. registers user
2. Reads email using Mail Reader Sampler which has following script
StringBuilder aggregateResult = new StringBuilder()
prev.getSubResults().each {
aggregateResult.append(it.getResponseDataAsString())
it.getSubResults().each {
aggregateResult.append(it.getResponseDataAsString())
it.getSubResults().each {
aggregateResult.append(it.getResponseDataAsString())
}
}
}
prev.setResponseData(aggregateResult.toString().getBytes())
Then extracts a particular link based on regexp.
As of now, it reads either the latest email or all the unread emails in the server.
Can someone please help me to modify the above script to read the message based on the user email created at step 1? Emails are created like test+1#gmail.com, test+2#gmail.com and so on.
Unfortunately it is not something you can do with Mail Reader Sampler, if you need to get mail(s) only for this or that sender email address you can use JavaMail API which provides filtering using i.e. FromStringTerm class from JSR223 Sampler
Example code:
import javax.mail.Multipart
Properties properties = new Properties()
properties.put('mail.imap.host', 'your mail server host') // i.e. imap.gmail.com
properties.put('mail.imap.port', your mail server port) // i.e. 993
properties.setProperty('mail.imap.socketFactory.class', 'javax.net.ssl.SSLSocketFactory')
properties.setProperty('mail.imap.socketFactory.fallback', 'false')
properties.setProperty('mail.imap.socketFactory.port', 'your_mail_server_port') // i.e. 993
def session = javax.mail.Session.getDefaultInstance(properties)
def store = session.getStore('imap')
store.connect('your username (usually email address)', 'your_password')
def inbox = store.getFolder('INBOX')
inbox.open(javax.mail.Folder.READ_ONLY)
def onlyFromGivenUser = inbox.search(new javax.mail.search.FromStringTerm('your_sender_address')) // i.e. test+1#gmail.com
onlyFromGivenUser.each { message ->
if (message.getContent() instanceof Multipart) {
StringBuilder content = new StringBuilder()
def multipart = (Multipart) message.getContent()
multipart.eachWithIndex { Multipart entry, int i ->
def part = entry.getBodyPart(i)
if (part.isMimeType('text/plain')) {
content.append(part.getContent().toString())
}
}
SampleResult.setResponseData(content.toString(), 'UTF-8')
} else {
SampleResult.setResponseData(message.getContent().toString(), 'UTF-8')
}
}
More information:
Apache Groovy - Why and How You Should Use It
Filter emails by domain using javamail
Not sure if you ever managed, I stepped away from javax.mail.Multipart and have implemented the below code in a JSR223 sampler inside a While Controller, this worked for me.
import javax.mail.Message
import javax.mail.search.RecipientStringTerm
Properties properties = new Properties();
properties.put('mail.imap.host', 'your mail server host') // i.e. imap.gmail.com
properties.put('mail.imap.port', your mail server port) // i.e. 993
properties.setProperty('mail.imap.socketFactory.class', 'javax.net.ssl.SSLSocketFactory')
properties.setProperty('mail.imap.socketFactory.fallback', 'false')
properties.setProperty('mail.imap.socketFactory.port', 'your_mail_server_port') // i.e. 993
def session = javax.mail.Session.getDefaultInstance(properties)
def store = session.getStore('imap')
store.connect('your username (usually email address)', 'your_password')
def inbox = store.getFolder('INBOX');
inbox.open(javax.mail.Folder.READ_ONLY);
def onlyToGivenUser = inbox.search(new RecipientStringTerm(Message.RecipientType.TO,'your_recipient_address')); // i.e. test+1#gmail.com
try {
onlyToGivenUser.each { message ->
ByteArrayOutputStream emailRaw = new ByteArrayOutputStream();
message.writeTo(emailRaw);
SampleResult.setResponseData(emailRaw.toString(), 'UTF-8');
}
} catch (Exception ex) {
log.warn("Something went wrong", ex);
OUT.println("Something went wrong", ex);
throw ex;
}
You probably need additional conditions and not only use the recipients address, in my case the recipient is unique for each iteration

Creating a Chat With Server Socket Channel

I'm creating a chat with ServerSocketChannel and maintain communication between Clients - Server.
The server receives a message from the client and broadcasts to every client.
I tried to send a message to the server and everything was fine, but when I try to send a message to the client from the server the message doesn't get there. It only delivers when I close the socket. (It's like it was buffered)
Here's my code for the server:
static public void main( String args[] ) throws Exception {
// Parse port from command line
int port = Integer.parseInt( args[0] );
try {
// Instead of creating a ServerSocket, create a ServerSocketChannel
ServerSocketChannel ssc = ServerSocketChannel.open();
// Set it to non-blocking, so we can use select
ssc.configureBlocking( false );
// Get the Socket connected to this channel, and bind it to the
// listening port
ServerSocket ss = ssc.socket();
InetSocketAddress isa = new InetSocketAddress( port );
ss.bind( isa );
// Create a new Selector for selecting
Selector selector = Selector.open();
// Register the ServerSocketChannel, so we can listen for incoming
// connections
ssc.register( selector, SelectionKey.OP_ACCEPT );
System.out.println( "Listening on port "+port );
while (true) {
// See if we've had any activity -- either an incoming connection,
// or incoming data on an existing connection
int num = selector.select();
// If we don't have any activity, loop around and wait again
if (num == 0) {
continue;
}
// Get the keys corresponding to the activity that has been
// detected, and process them one by one
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> it = keys.iterator();
while (it.hasNext()) {
// Get a key representing one of bits of I/O activity
SelectionKey key = it.next();
// What kind of activity is it?
if ((key.readyOps() & SelectionKey.OP_ACCEPT) ==
SelectionKey.OP_ACCEPT) {
// It's an incoming connection. Register this socket with
// the Selector so we can listen for input on it
Socket s = ss.accept();
clientList.add(new Client(s));
System.out.println( "Got connection from "+s );
// Make sure to make it non-blocking, so we can use a selector
// on it.
SocketChannel sc = s.getChannel();
sc.configureBlocking( false );
// Register it with the selector, for reading
sc.register( selector, SelectionKey.OP_READ );
} else if ((key.readyOps() & SelectionKey.OP_READ) ==
SelectionKey.OP_READ) {
SocketChannel sc = null;
try {
// It's incoming data on a connection -- process it
sc = (SocketChannel)key.channel();
boolean ok = processInput( sc );
/* HERE, TRYING TO SEND A TEST MESSAGE BACK */
ByteBuffer bf = ByteBuffer.allocate(48);
bf.clear();
bf.put("testmessage".getBytes());
sc.write(bf);
// If the connection is dead, remove it from the selector
// and close it
if (!ok) {
key.cancel();
Socket s = null;
try {
s = sc.socket();
System.out.println( "Closing connection to "+s );
s.close();
} catch( IOException ie ) {
System.err.println( "Error closing socket "+s+": "+ie );
}
}
} catch( IOException ie ) {
// On exception, remove this channel from the selector
key.cancel();
try {
sc.close();
} catch( IOException ie2 ) { System.out.println( ie2 ); }
System.out.println( "Closed "+sc );
ie.printStackTrace();
}
}
}
// We remove the selected keys, because we've dealt with them.
keys.clear();
}
} catch( IOException ie ) {
System.err.println( ie );
}
}
On the server, please note the lines:
ByteBuffer bf = ByteBuffer.allocate(48);
bf.clear();
bf.put("testmessage".getBytes());
sc.write(bf);
This is where I try to answer back.
Client receives the messages in a method:
// Main method for incoming
public void run() throws IOException {
while(true) {
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String answer = br.readLine();
printMessage(answer);
}
}
Regards,
Pedro
Several problems here.
You're reading lines but you're not writing lines. Add a line terminator when sending.
You need to close the channel immediately you get -1 from read(). You almost certainly can't send on it after that.
You don't need to cancel the key or close the socket of the channel. Closing the channel does all that.
Your client read loop needs to break when you get null from readLine().

Error emailing outgoing sms

Is there anyway to listen for an outbound sms without having to import javax.wireless.messaging?
I'm trying to write an app that listens for an sms sent from the device then emails the message of the sms, but I get the error:
reference to Message is ambiguous, both class
javax.wireless.messaging.Message in javax.wireless.messaging and class
net.rim.blackberry.api.mail.Message in net.rim.blackberry.api.mail
match
I need to import net.rim.blackberry.api.mail.Message in order to sent an email.
Is there a way to get around this as it seems that the two packages are clashing.
My code:
public void notifyIncomingMessage(MessageConnection messageconnection) {}
public void notifyOutgoingMessage(javax.wireless.messaging.Message message) {
try {
String address = message.getAddress();
String msg = null;
if ( message instanceof TextMessage ) {
TextMessage tm = (TextMessage)message;
msg = tm.getPayloadText();
} else if (message instanceof BinaryMessage) {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) message).getPayloadData();
msg = new String(data, "UTF-8");
Store store = Session.getDefaultInstance().getStore();
Folder[] folders = store.list(Folder.SENT);
Folder sentfolder = folders[0];
Message in = new Message(sentfolder);
Address recipients[] = new Address[1];
recipients[0]= new Address("me#us.com", "user");
in.addRecipients(Message.RecipientType.TO, recipients);
in.setSubject("Outgoing sms");
in.setContent("You have just sent an sms to: " + address + "\n" + "Message: " + msg);
in.setPriority(Message.Priority.HIGH);
Transport.send(in);
in.setFlag(Message.Flag.OPENED, true);
Folder folder = in.getFolder();
folder.deleteMessage(in);
}
} catch (IOException me) {
System.out.println(me);
}
}
}
You never should need to import anything in Java. Importing a package is just a shortcut, so that you don't have to fully type out the whole package name. If you have a class named Message that you want to use, and it exists in two packages (both of which you need), then I wouldn't import either of them.
Simply, always refer to each of them by their fully-qualified name:
net.rim.blackberry.api.mail.Message
and
javax.wireless.messaging.Message
It's just a little more typing.