I need to tockenize string of a java code to its blocks - java

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class Client {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
socket.connect(new InetSocketAddress(5000));
byte[] message = "Oh Hai!".getBytes();
DatagramPacket packet = new DatagramPacket(message, message.length);
socket.send(packet);
}
}
I have this code as a string and I need to get its methods statements loops for separate arrays
Can any body suggest a solution

You can use the StreamTokenizer to analyze a stream (e.g. StringReader).
Here you are an example:
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
public class Test {
public static void main(String[] args){
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader("public static void main(String[] args){"));
tokenizer.parseNumbers();
tokenizer.wordChars('_', '_');
tokenizer.eolIsSignificant(true);
tokenizer.ordinaryChars(0, ' ');
tokenizer.slashSlashComments(true);
tokenizer.slashStarComments(true);
int token;
try {
while( (token = tokenizer.nextToken()) != StreamTokenizer.TT_EOF) {
if(token == StreamTokenizer.TT_WORD) {
System.out.println(tokenizer.sval);
}
}
} catch (IOException e) {
e.printStackTrace();
// Please handle this exception
}
}
}
This generates the following output:
public
static
void
main
String
args
Please have a look at this for further details:
https://docs.oracle.com/javase/7/docs/api/java/io/StreamTokenizer.html

Related

Why onGuildMemberRoleAdd doesnt work? DiscordBot in Java

The "onGuildMemberRoleAdd" listener just doesn't work ... As if the listener was ignored...
And I don't know why :( can someone help me pls!
I also implemented the listener in the main class.
Listener:
package listener.rollen;
import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class RollenAdd extends ListenerAdapter {
#Override
public void onGuildMemberRoleAdd(GuildMemberRoleAddEvent event) {
System.out.println("test");
}
}
Main
package main;
import listener.*;
import listener.punktesystem.SprachchatConnect;
import listener.punktesystem.SprachchatDisconnect;
import listener.rollen.*;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder;
import net.dv8tion.jda.api.sharding.ShardManager;
import javax.security.auth.login.LoginException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Start {
public static Start INSTANCE;
public ShardManager shardMan;
public static void main(String[] args) {
try {
new Start();
} catch (LoginException e) {
e.printStackTrace();
}
}
public Start() throws LoginException, IllegalArgumentException {
INSTANCE = this;
DefaultShardManagerBuilder builder = DefaultShardManagerBuilder.createDefault("Token");
builder.setActivity(Activity.watching("ZZZZs Zaubertrick"));
builder.setStatus(OnlineStatus.ONLINE);
listeners(builder);
shardMan = builder.build();
shutdown();
}
public void shutdown(){
new Thread(() -> {
String line = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try{
while ((line = reader.readLine()) != null){
if(line.equalsIgnoreCase("exit")){
if(shardMan != null){
shardMan.setStatus(OnlineStatus.OFFLINE);
shardMan.shutdown();
System.out.println("Bot ist offline!");
}
}
}
}catch (IOException e){
e.printStackTrace();
}
}).start();
}
public void listeners(DefaultShardManagerBuilder builder){
builder.addEventListeners(new RollenAdd());
}
}
I think that's all that has to do with it...
At first I thought it was because the Privileged Gateway Intents were not activated in the DiscordDeveloperPortal, but after that it still didn't work

Trouble with recursion and text file

This program takes in input the "hello my name is bob" and spits it out backwards. I really need help making it that the program reads in a text file and spits out the text file backwards. Thanks in advance!
public class Recursion
{
public static void main(String[] args) throws FileNotFoundException {
System.out.println(printBackwards("hello my name is bob"));
}
public static String printBackwards(String s){
if(s.length() <= 1)
return s;
else
return printBackwards(s.substring(1,s.length()))+s.charAt(0);
}
}
Based on the comments for the question, this will read a file called input.txt and save it to a new file called output.txt using your method for reversing a String.
All lines in input.txt are firstly added to a List.
The List is then iterated through backwards from the last element, and with each iteration the reversed String written to output.txt.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
public class Example {
public static void main(String[] args) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
Scanner scanner = new Scanner(new File("input.txt"));
List<String> fileContents = new ArrayList<>();
while (scanner.hasNextLine()) {
fileContents.add(scanner.nextLine());
}
ListIterator<String> it = fileContents.listIterator(fileContents.size());
while (it.hasPrevious()) {
writer.write(printBackwards(it.previous()));
writer.newLine();
}
}
}
public static String printBackwards(String s) {
if (s.length() <= 1) {
return s;
} else {
return printBackwards(s.substring(1, s.length())) + s.charAt(0);
}
}
}
If however you just want to display it to the standard output, you can adjust it to the following:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
public class Example {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("input.txt"));
List<String> fileContents = new ArrayList<>();
while (scanner.hasNextLine()) {
fileContents.add(scanner.nextLine());
}
ListIterator<String> it = fileContents.listIterator(fileContents.size());
while (it.hasPrevious()) {
System.out.println(printBackwards(it.previous()));
}
}
public static String printBackwards(String s) {
if (s.length() <= 1) {
return s;
} else {
return printBackwards(s.substring(1, s.length())) + s.charAt(0);
}
}
}
Or as I said in my comment earlier, you can just read the whole file in one go and reverse it:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Example {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(printBackwards(new Scanner(new File("file.txt")).useDelimiter("\\Z").next()));
}
public static String printBackwards(String s) {
if (s.length() <= 1) {
return s;
} else {
return printBackwards(s.substring(1, s.length())) + s.charAt(0);
}
}
}
Use this code to get the string that you want to reverse from a text file:
try{
String myString;
BufferedReader input = new BufferedReader(new FileReader("Filepath.txt");
while((myString = input.readLine()) != null){}
}
catch(FileNotFoundException ex){
//Error Handler Here
}
catch(IOException ex){
//Error Handler Here
} finally {
try{
if(br != null) br.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
Don't forget to import:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException
This should work as you expect. I assume that in the filename_in.txt you have only one line, otherwise you have to loop (I let you to do this as exercise):
public static void main(String[] args){
Scanner in = null;
PrintWriter writer = null;
try{
in = new Scanner(new FileReader("filename_in.txt"));
writer = new PrintWriter("filename_out.txt");
writer.println(printBackwards(in.nextLine()));
} catch (Exception e) {
e.printStackTrace();
}
finally {
in.close();
writer.close();
}
}

DatagramChannel.receive blocks on VPN

I am learning about DatagramChannel Multicast,
I am trying to do the following ,i noticed that the DatagramChannel#receive method blocks completely when i am on VPN and does not receive anything , but data gets printed few iterations when i disconnect VPN.
1. Sending data to a multicast IP group:
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Date;
public class MultiCastChannelThread extends Thread {
DatagramChannel channel;
ProtocolFamily family = StandardProtocolFamily.INET;
MultiCastChannelThread(String name) throws IOException {
super(name);
configureChannel();
}
public static void main(String[] args) throws IOException {
new MultiCastChannelThread("MultiCastChannel").start();
}
private void configureChannel() throws IOException {
channel = DatagramChannel.open(family).setOption(StandardSocketOptions.SO_REUSEADDR, true).bind(null).setOption(
StandardSocketOptions.IP_MULTICAST_IF, NetworkInterface.getByName("wlan0"));
}
#Override
public void run() {
int i = 0;
while (i++ < 6) {
try {
byte[] buff = new Date().toString().getBytes();
ByteBuffer buffer = ByteBuffer.wrap(buff);
InetAddress group = InetAddress.getByName("224.0.15.15");
int sent = channel.send(buffer, new InetSocketAddress(group, 4466));
System.out.format("Number of bytes sent :%s\n Data sent:%s\t\n", sent, new String(buff));
try {
sleep(5 * 1000);
} catch (InterruptedException e) {
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2. Joining and receiving the data on the group
import static java.lang.Thread.sleep;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class MulticastChannelClient {
NetworkInterface networkInterface;
InetAddress inetAddress;
InetAddress group;
ProtocolFamily family = StandardProtocolFamily.INET;
public MulticastChannelClient() throws UnknownHostException, SocketException {
group = InetAddress.getByName("224.0.15.15");
networkInterface = NetworkInterface.getByName("wlan0");
}
public static void main(String[] args) throws IOException {
new MulticastChannelClient().testMultiCastChannel();
}
private void testMultiCastChannel() throws IOException {
new MultiCastChannelThread("MulticastChannelTest").start();
DatagramChannel channel = DatagramChannel.open(family).setOption(StandardSocketOptions.SO_REUSEADDR, true).bind(
new InetSocketAddress((InetAddress) null, 4466));
channel.join(group, networkInterface);
for (int i = 0; i < 6; i++) {
ByteBuffer received = ByteBuffer.allocate(250);
SocketAddress socketAddress = channel.receive(received);
System.out.println("Received ::: " + i + " " + new String(received.array()));
try {
sleep(2 * 1000);
} catch (InterruptedException e) {
}
}
}
}

How to create a simple Server Client Application Using RUDP in Java?

I was working on a simple application to transfer files between two machines using UDP, but that turned out to be lossy and unreliable, so while searching the Internet I found this project named Simple Reliable UDP here, but they don't have any documentation or any example code. So if there is any who can help me with this code I will be grateful because I'm newbie in Java. I started with writing simple server client app, but I got address already bind exception. To make clear I want to use UDP connections only that's why I'm trying to implement ReliableServerSocket and ReliableSocket.
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.rudp.ReliableServerSocket;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class udpServer implements Runnable{
ReliableServerSocket rss;
///ocket rs;
ReliableSocket rs;
public udpServer() throws IOException {
rss= new ReliableServerSocket(9876);
}
public void run(){
while (true){
try {
rs=(ReliableSocket)rss.accept();
System.out.println("Connection Accepted");
System.out.println(""+rs.getInetAddress());
BufferedReader inReader = new BufferedReader (new InputStreamReader (rs.getInputStream()));
//BufferedWriter outReader = new BufferedWriter (new OutputStreamWriter (rs.getOutputStream()));
String str= ""+inReader.readLine();
if(str.contains("UPLOAD")){
System.out.println("Client wants to upload file");
}else if(str.contains("D1")){
System.out.println("Client wants to download file");
}
} catch (IOException ex) {
Logger.getLogger(udpServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) throws Exception
{
System.out.println("UDP Server Executed");
Thread t= new Thread( new udpServer());
t.start();
}
}
Client Code here
package stackoverflow;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UdpFileClient {
BufferedWriter outReader;
ReliableSocket server;
public UdpFileClient(boolean b1, boolean b2) throws IOException {
if (b1) {
server = new ReliableSocket("127.0.0.1", 9876);
outReader = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
outReader.write("D1");
System.out.println("Download Req Sent From Client");
server.close();
outReader.flush();
outReader.close();
}
if (b2) {
server = new ReliableSocket("127.0.0.1", 9876);
outReader = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
outReader.write("UPLOAD");
System.out.println("Upload Req Sent From Client");
server.close();
outReader.flush();
outReader.close();
}
}
public static void main(String args[]) throws Exception {
System.out.println("UDP CLient Executed");
new UdpFileClient(true, true);
}
}
I already know I can use TCP/IP, but it is kind of requirement for the project to use UDP. If any other way to send files in lossless way using UDP with good speed will also be helpful.
Thanks in advance!!
I tried RUDP and found that i was not printing my output, i know this is a silly mistake.
UDP Client
package UDPClient;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UDPtestc {
ReliableSocket server;
public UDPtestc() throws IOException {
server = new ReliableSocket();
server.connect(new InetSocketAddress("127.0.0.1", 9876));
byte[] buffer = new byte[1024];
int count,progress=0;
InputStream in = server.getInputStream();
while((count=in.read(buffer)) >0){
progress+=count;
System.out.println(""+progress);
}
server.close();
}
public static void main(String[] args) throws IOException {
new UDPtestc();
}
}
UDPserver
package UDPServer;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.rudp.ReliableServerSocket;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UDPtests implements Runnable {
ReliableServerSocket rss;
ReliableSocket rs;
String file;
FileInputStream bin;
public UDPtests() throws IOException {
rss = new ReliableServerSocket(9876);
Thread serverthread = new Thread(this);
serverthread.start();
}
public void run() {
while (true) {
try {
rs = (ReliableSocket)rss.accept();
System.out.println("Connection Accepted");
System.out.println("" + rs.getRemoteSocketAddress());
file = "";
Long size=0L;
file += "10MB.txt";
size+=10*1024*1024;
RandomAccessFile r1= new RandomAccessFile(file,"rw");
r1.setLength(size);
byte[] sendData = new byte[1024];
OutputStream os = rs.getOutputStream();
//FileOutputStream wr = new FileOutputStream(new File(file));
bin= new FileInputStream(file);
int bytesReceived = 0;
int progress = 0;
while ((bytesReceived = bin.read(sendData)) > 0) {
/* Write to the file */
os.write(sendData, 0, bytesReceived);
progress += bytesReceived;
System.out.println(""+progress);
}
} catch (IOException ex) {
Logger.getLogger(udpServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) throws IOException {
new UDPtests();
}
}
Soon i will post other tuts on RUDP if it will be possible.

kryo serializing of class (task object) in apache spark returns null while de-serialization

I am using java spark API to write some test application . I am using a class which doesn't extends serializable interface . So to make the application work I am using kryo serializer to serialize the class . But the problem which I observed while debugging was that during the de-serialization the returned class object becomes null and in turn throws a null pointer exception . It seems to be closure problem where things are going wrong but not sure.Since I am new to this kind of serialization I don't know where to start digging.
Here is the code I am testing :
package org.apache.spark.examples;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
/**
* Spark application to test the Serialization issue in spark
*/
public class Test {
static PrintWriter outputFileWriter;
static FileWriter file;
static JavaSparkContext ssc;
public static void main(String[] args) {
String inputFile = "/home/incubator-spark/examples/src/main/scala/org/apache/spark/examples/InputFile.txt";
String master = "local";
String jobName = "TestSerialization";
String sparkHome = "/home/test/Spark_Installation/spark-0.7.0";
String sparkJar = "/home/test/TestSerializationIssesInSpark/TestSparkSerIssueApp/target/TestSparkSerIssueApp-0.0.1-SNAPSHOT.jar";
SparkConf conf = new SparkConf();
conf.set("spark.closure.serializer","org.apache.spark.serializer.KryoSerializer");
conf.set("spark.kryo.registrator", "org.apache.spark.examples.MyRegistrator");
// create the Spark context
if(master.equals("local")){
ssc = new JavaSparkContext("local", jobName,conf);
//ssc = new JavaSparkContext("local", jobName);
} else {
ssc = new JavaSparkContext(master, jobName, sparkHome, sparkJar);
}
JavaRDD<String> testData = ssc.textFile(inputFile).cache();
final NotSerializableJavaClass notSerializableTestObject= new NotSerializableJavaClass("Hi ");
#SuppressWarnings({ "serial", "unchecked"})
JavaRDD<String> classificationResults = testData.map(
new Function<String, String>() {
#Override
public String call(String inputRecord) throws Exception {
if(!inputRecord.isEmpty()) {
//String[] pointDimensions = inputRecord.split(",");
String result = "";
try {
FileWriter file = new FileWriter("/home/test/TestSerializationIssesInSpark/results/test_result_" + (int) (Math.random() * 100));
PrintWriter outputFile = new PrintWriter(file);
InetAddress ip;
ip = InetAddress.getLocalHost();
outputFile.println("IP of the server: " + ip);
result = notSerializableTestObject.testMethod(inputRecord);
outputFile.println("Result: " + result);
outputFile.flush();
outputFile.close();
file.close();
} catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e1) {
e1.printStackTrace();
}
return result;
} else {
System.out.println("End of elements in the stream.");
String result = "End of elements in the input data";
return result;
}
}
}).cache();
long processedRecords = classificationResults.count();
ssc.stop();
System.out.println("sssssssssss"+processedRecords);
}
}
Here is the KryoRegistrator class
package org.apache.spark.examples;
import org.apache.spark.serializer.KryoRegistrator;
import com.esotericsoftware.kryo.Kryo;
public class MyRegistrator implements KryoRegistrator {
public void registerClasses(Kryo kryo) {
kryo.register(NotSerializableJavaClass.class);
}
}
Here is the class I am serializing :
package org.apache.spark.examples;
public class NotSerializableJavaClass {
public String testVariable;
public NotSerializableJavaClass(String testVariable) {
super();
this.testVariable = testVariable;
}
public String testMethod(String vartoAppend){
return this.testVariable + vartoAppend;
}
}
This is because spark.closure.serializer only supports the Java serializer. See http://spark.apache.org/docs/latest/configuration.html about spark.closure.serializer

Categories

Resources