While true loop executed only a limited amount of times - while-loop

So i have this telegram bot and i have a while loop in the main string args because i need it to check something for eternity. But after a while or even emediatly the while loop stops.
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import java.time.Duration;
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
boolean running = false;
// Instantiate Telegram Bots API
TelegramBotsApi botsApi = new TelegramBotsApi();
SwtPremiumBot bot = new SwtPremiumBot();
// Register our bot
try {
botsApi.registerBot(bot);
System.out.println("BOT REGISTERED");
running=true;
//storing the filIDS
String[] files=new String[9];
files[0]="AgADBAADa6wxG1gRcVGzXAwfpuZjo0JZJhoABOvVf8G55uyhXeUEAAEC";
files[1]="AgADBAADbKwxG1gRcVGGoZcrmZ786ph7jBoABG7SjlCeIwnjXngDAAEC";
files[2]="AgADBAADbawxG1gRcVFwF6pUv1RskZ1GKRoABMefcdSzWLaxYWIFAAEC";
files[3]="AgADBAADbqwxG1gRcVGB0noIZtEpgypbNBoABL1GJAMM9QxqElABAAEC";
files[4]="AgADBAADcqwxG1gRcVGBiPqbusQgZmBLkRoABE-nBSP6FJZYGnEAAgI";
files[5]="AgADBAADc6wxG1gRcVHwFx4ec9kWnafJKhoABMBQxr6mC9qHXFsFAAEC";
files[6]="AgADBAADdKwxG1gRcVERF469BLWkMB0LkRkABOfM_ioz6u6iG0oAAgI";
files[7]="AgADBAADdawxG1gRcVFa7fItTXuxtu0JjhoABMl076IfG9VFB3oDAAEC";
files[8]="AgADBAADdqwxG1gRcVHEf5OseR1P4aTlkBkABFGmx73rlPOjUksAAgI";
String[] gifs=new String[13];
gifs[0]="CgADBAADYAIAAlgRcVFuikWviGM3ugI";
gifs[1]="CgADBAADYQIAAlgRcVEEWh_ZQxpfNAI";
gifs[2]="CgADBAADYgIAAlgRcVEpmx9MY-rSHwI";
gifs[3]="CgADBAADYwIAAlgRcVF0pJYhUNuCIwI";
gifs[4]="CgADBAADZAIAAlgRcVFvJlndVDLAaAI";
gifs[5]="CgADBAADZQIAAlgRcVFzc-BYUtICfAI";
gifs[6]="CgADBAADZgIAAlgRcVFML1TuOWgTFQI";
gifs[7]="CgADBAADZwIAAlgRcVGDlLtcdA1gGgI";
gifs[8]="CgADBAADaAIAAlgRcVHk0_p_0xy4XQI";
gifs[9]="CgADBAADaQIAAlgRcVH9Y38kRM025QI";
gifs[10]="CgADBAADagIAAlgRcVH7ZXg3Vvju9AI";
gifs[11]="CgADBAADawIAAlgRcVG00SeL2VBKowI";
gifs[12]="CgADBAADbAIAAlgRcVFetih9aTXW8gI";
bot.setFileIds(files);
bot.setGifs(gifs);
} catch (TelegramApiException e) {
e.printStackTrace();
String error = e.toString();
bot.addErrors(error, LocalDateTime.now());
}
LocalDateTime lastCheck = LocalDateTime.now();
while (running){
LocalDateTime now = LocalDateTime.now();
Duration d = Duration.between(lastCheck, now);
long duration = d.toMillis();
if (duration>20000) {
bot.checkCompleteOrders();
bot.checkPublishTime();
lastCheck = LocalDateTime.now();
System.out.println("Orders checked.");
}
}
String error = "WHILE LOOP BROKEN";
bot.addErrors(error, LocalDateTime.now());
}
}
Thanks in advance.

Related

Is it possible to cancel a call to speakTextAsync?

I'm using the javascript SDK of Microsoft Speech Synthesizer and calling speakTextAsync to convert text to speech.
This works perfectly, but sometimes the text is long and I want to be able to cancel in the middle, but I cannot find any way to do this. The documentation doesn't seem to indicate any way to cancel. The name speakTextAsync suggests that it returns a Task that could be cancelled, but in fact the method returns undefined, and I can't find any other way to do this. How can this be done?
Seems there is no way to stop it when it is speaking. But actually,as a workaround, you can just download the audio file and play the file yourself so that you can control everything. try the code below:
import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
import java.nio.file.*;
import java.io.*;
import javax.sound.sampled.*;
public class TextToSpeech {
public static void main(String[] args) {
try {
String speechSubscriptionKey = "key";
String serviceRegion = "location";
String audioTempPath = "d://test.wav"; //temp file location
SpeechConfig config = SpeechConfig.fromSubscription(speechSubscriptionKey, serviceRegion);
AudioConfig streamConfig = AudioConfig.fromWavFileOutput(audioTempPath);
SpeechSynthesizer synth = new SpeechSynthesizer(config, streamConfig);
String filePath = "....//test2.txt"; // .txt file for test with long text
Path path = Paths.get(filePath);
String text = Files.readString(path);
synth.SpeakText(text);
Thread thread = new Thread(new Speaker(audioTempPath));
thread.start();
System.out.println("play audio for 8s...");
Thread.sleep(8000);
System.out.println("stop play audio");
thread.stop();
} catch (Exception ex) {
System.out.println("Unexpected exception: " + ex);
assert (false);
System.exit(1);
}
}
}
class Speaker implements Runnable {
private String path;
public String getText(String path) {
return this.path;
}
public Speaker(String path) {
this.path = path;
}
public void run() {
try {
File file = new File(path);
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;
Clip clip;
stream = AudioSystem.getAudioInputStream(file);
format = stream.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

C3P0, rawConnectionOperation() & java.lang.IllegalArgumentException

I am attempting to use a non-standard method, getServerJobIdentifier(), that is part of the IBM Java Tool Box (jt400.jar) and class com.ibm.as400.access.AS400JDBCConnection with C3P0 & rawConnectionOperation(). I am getting "java.lang.IllegalArgumentException: object is not an instance of declaring class". I have tried numerous options but have not stumbled upon the correct parameters to pass. I am using C3P0 0.9.5.4. Code snippet follows:
// The method I want to call.
// getServerJobIdentifier, public abstract java.lang.String com.ibm.as400.access.AS400JDBCConnection.getServerJobIdentifier()
String driverClassName = "com.ibm.as400.access.AS400JDBCDriver";
String m_DatabaseConnectionString = "jdbc:db2:*local;naming=sql;extended metadata=true";
Connection m_dbConnection;
ComboPooledDataSource m_cpds;
m_cpds = new ComboPooledDataSource();
try {
m_cpds.setDriverClass(driverClassName); //loads the jdbc driver
}
catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
m_cpds.setJdbcUrl(m_DatabaseConnectionString);
m_dbConnection = m_cpds.getConnection();
String qualifiedName = "";
C3P0ProxyConnection castCon = (C3P0ProxyConnection)m_dbConnection;
Method m = AS400JDBCConnection.class.getDeclaredMethod("getServerJobIdentifier");
// This does return what I want. getServerJobIdentified() has no parameters.
System.out.println("method=" + m.toString());
Object[] args = new Object[] {};
System.out.println("calling rawConnectionOperation");
qualifiedName = (String) castCon.rawConnectionOperation(m, C3P0ProxyConnection.RAW_CONNECTION, args);
// never gets here
System.out.println("qualifiedName=" + qualifiedName);
I know I'm that close or I think I am. Thanks!
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import com.mchange.v2.c3p0.*;
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400JDBCConnection;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.db2.jdbc.app.DB2Connection;
// javac -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar C3P0Main.java
// /QIBM/ProdData/OS400/jt400/lib/jt400Native.jar
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar C3P0Main
// or
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:/QIBM/ProdData/OS400/jt400/lib/jt400Native.jar C3P0Main
// c3p0.acquireRetryAttempts=0
// c3p0.acquireRetryDelay=5000
// c3p0.breakAfterAcquireFailure=false
// c3p0.maxConnectionAge=10800
// c3p0.maxIdleTime=3600
// c3p0.maxIdleTimeExcessConnections=600
// c3p0.automaticTestTable=c3p0test
// c3p0.idleConnectionTestPeriod=600
// c3p0.testConnectionOnCheckout=true
// java -cp :./c3p0-0.9.5.4.jar:./mchange-commons-java-0.2.15.jar:./jt400.jar -Dc3p0.acquireRetryAttempts=0 -Dc3p0.acquireRetryDelay=5000 -Dc3p0.breakAfterAcquireFailure=false -Dc3p0.maxConnectionAge=10800 -Dc3p0.maxIdleTime=3600 -Dc3p0.maxIdleTimeExcessConnections=600 -Dc3p0.automaticTestTable=c3p0test -Dc3p0.idleConnectionTestPeriod=600 -Dc3p0.testConnectionOnCheckout=true C3P0Main
public class C3P0Main {
private Connection m_dbConnection;
private ComboPooledDataSource m_cpds;
private String driverClassName = "com.ibm.as400.access.AS400JDBCDriver";
//private String m_DatabaseConnectionString = "jdbc:as400:BNADEV;naming=sql;extended metadata=true;user=beak;password=roatan12";
private String m_DatabaseConnectionString = "jdbc:as400:BNADEV;naming=sql;extended metadata=true";
private String m_databaseServerJobID;
public C3P0Main() throws SQLException
{
m_cpds = new ComboPooledDataSource();
try {
m_cpds.setDriverClass(driverClassName); //loads the jdbc driver
}
catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
m_cpds.setJdbcUrl(m_DatabaseConnectionString);
}
public void run(String[] args) throws Exception
{
m_dbConnection = m_cpds.getConnection();
System.out.println("m_dbConnection=" + m_dbConnection.toString());
String qualifiedName = "";
try {
// To use it, first cast the returned Connection to a C3P0ProxyConnection.
// Then call the method rawConnectionOperation, supplying the java.lang.reflect.Method object
// for the non-standard method you wish to call as an argument. The Method you supply will
// be invoked on the target you provide on the second argument (null for static methods),
// and using the arguments you supply in the third argument to that function. For the target,
// and for any of the method arguments, you can supply the special token
// C3P0ProxyConnection.RAW_CONNECTION, which will be replaced with the
// underlying vendor-specific Connection object before the Method is invoked.
//
// C3P0ProxyConnection castCon = (C3P0ProxyConnection) c3p0DataSource.getConnection();
// Method m = CLOB.class.getMethod("createTemporary", new Class[]{Connection.class, boolean.class, int.class});
// Object[] args = new Object[] {C3P0ProxyConnection.RAW_CONNECTION, Boolean.valueOf( true ), new Integer( 10 )};
// CLOB oracleCLOB = (CLOB) castCon.rawConnectionOperation(m, null, args);
// getServerJobIdentifier, public abstract java.lang.String com.ibm.as400.access.AS400JDBCConnection.getServerJobIdentifier()
System.out.println("Is a wrapper for DB2Connection=" + m_dbConnection.isWrapperFor(com.ibm.db2.jdbc.app.DB2Connection.class));
System.out.println("Is a wrapper for AS400JDBCConnection=" + m_dbConnection.isWrapperFor(AS400JDBCConnection.class));
C3P0ProxyConnection castCon = (C3P0ProxyConnection)m_dbConnection;
System.out.println("C3P0ProxyConnection.RAW_CONNECTION=" + C3P0ProxyConnection.RAW_CONNECTION.getClass().getName());
Method method = AS400JDBCConnection.class.getMethod("getServerJobIdentifier");
System.out.println("method=" + method.toString());
Object[] method_args = new Object[] {};
System.out.println("calling rawConnectionOperation");
try {
qualifiedName = (String) castCon.rawConnectionOperation(method, m_dbConnection, method_args);
System.out.println("qualifiedName=" + qualifiedName);
}
catch (IllegalArgumentException | SQLException | InvocationTargetException | IllegalAccessException e) {
System.out.println(e);
System.out.println("oh well #1.");
}
try {
Object[] method_args = new Object[] {};
qualifiedName = (String) castCon.rawConnectionOperation(method, m_dbConnection, method_args);
System.out.println("qualifiedName=" + qualifiedName);
}
catch (IllegalArgumentException | SQLException | InvocationTargetException | IllegalAccessException e) {
System.out.println(e);
System.out.println("oh well #2.");
}
if (castCon instanceof AS400JDBCConnection) {
System.out.println("YES");
qualifiedName = ((AS400JDBCConnection)C3P0ProxyConnection.RAW_CONNECTION).getServerJobIdentifier();
String jobName = qualifiedName.substring(0, 10).trim();
String jobUser = qualifiedName.substring(10, 20).trim();
String jobNumber = qualifiedName.substring(20).trim();
m_databaseServerJobID = jobNumber + '/' + jobUser + '/' + jobName;
System.out.println("SQL Server Job ID: " + m_databaseServerJobID);
}
else {
System.out.println("m_dbConnection is not an instance of DB2Connection.");
}
}
catch (IllegalArgumentException | SQLException | NoSuchMethodException e) {
System.out.println(e);
System.out.println("oh well.");
}
}
public static void main(java.lang.String args[])
{
try {
C3P0Main app = new C3P0Main();
app.run(args);
}
catch (Exception e) {
e.printStackTrace();
}
}
}

pcap4j+winpcap should I run rpcapd.exe manually?

Hi I have downloaded pcap4j and winpcap and all jar (jna, pcap4j-core-1.8.2, slf4j-api-1.7.25, slf4j-simple-1.7.25) dependency manually. Added to the project and all compile well.
BUT:
when I began to sniff packet.getHeader() and packet.getPayload() returns null!
if I run manually rpcapd.exe then it works...
why?
package sniffer;
import java.io.IOException;
import org.pcap4j.core.BpfProgram.BpfCompileMode;
import org.pcap4j.core.NotOpenException;
import org.pcap4j.core.PacketListener;
import org.pcap4j.core.PcapHandle;
import org.pcap4j.core.PcapNativeException;
import org.pcap4j.core.PcapNetworkInterface;
import org.pcap4j.core.PcapNetworkInterface.PromiscuousMode;
import org.pcap4j.packet.Packet;
import org.pcap4j.util.NifSelector;
public class App {
static PcapNetworkInterface getNetworkDevice() {
PcapNetworkInterface device = null;
try {
device = new NifSelector().selectNetworkInterface();
} catch (IOException e) {
e.printStackTrace();
}
return device;
}
public static void main(String[] args) throws PcapNativeException, NotOpenException {
// The code we had before
PcapNetworkInterface device = getNetworkDevice();
System.out.println("You chose: " + device);
// New code below here
if (device == null) {
System.out.println("No device chosen.");
System.exit(1);
}
// Open the device and get a handle
int snapshotLength = 65536; // in bytes
int readTimeout = 50; // in milliseconds
final PcapHandle handle;
handle = device.openLive(snapshotLength, PromiscuousMode.PROMISCUOUS, readTimeout);
String filter = "tcp port 80";
handle.setFilter(filter, BpfCompileMode.OPTIMIZE);
// Create a listener that defines what to do with the received packets
PacketListener listener = new PacketListener() {
#Override
public void gotPacket(Packet packet) {
// Override the default gotPacket() function and process packet
System.out.println(handle.getTimestamp());
System.out.println(packet);
System.out.println(packet.getHeader());///////////////<<<<<<<<<<<------------
}
};
// Tell the handle to loop using the listener we created
try {
int maxPackets = 50;
handle.loop(maxPackets, listener);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Cleanup when complete
handle.close();
}
}
You need to add a packet factory (e.g. pcap4j-packetfactory-static.jar) to your classpath, or Pcap4J creates UnknownPacket instances, getPayload() and getHeader() of which return null, for all packets.

React-Native can't use jni library correctly

I'm using nanohttpd in my native java code. When I use it normally everything looks good, but when I use jni library methods it does not work.
my app uses nanohttpd to make stream for mediaPlayer.
native methods:
public native String LH();
public native int P();
public native String EngineGS(Context context);
public native byte[] OGB(byte[] inputBuff);
variables :
private MediaPlayer mp;
private HTTPServer encryptServer;
nanohttpd class:
public class HTTPServer extends NanoHTTPD {
public HTTPServer(int port) throws IOException {
super(port);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
#Override
public Response serve(IHTTPSession session) {
Response response = null;
try {
InputStream inputStream = new FileInputStream("/sdcard/Download/" + "encrypted.mp3");
byte[] encryptedInputByteArray = IOUtils.toByteArray(inputStream);
byte[] decryptedByteArray = OGB(encryptedInputByteArray);
inputStream = new ByteArrayInputStream(decryptedByteArray);
int totalLength = inputStream.available();
String requestRange = session.getHeaders().get("range");
if (requestRange == null) {
response = NanoHTTPD.newFixedLengthResponse(Response.Status.OK, "audio/mpeg", inputStream, totalLength);
} else {
Matcher matcher = Pattern.compile("bytes=(\\d+)-(\\d*)").matcher(requestRange);
matcher.find();
long start = 0;
try {
start = Long.parseLong(matcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
inputStream.skip(start);
long restLength = totalLength - start;
response = NanoHTTPD.newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, "audio/mpeg", inputStream, restLength);
String contentRange = String.format("bytes %d-%d/%d", start, totalLength, totalLength);
response.addHeader("Content-Range", contentRange);
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
play method:
#ReactMethod
public void play() {
mp.getCurrentPosition();
try {
if (encryptServer == null) {
encryptServer = new HTTPServer(P());
}
Uri uri = Uri.parse(LH() + ":" + encryptServer.getListeningPort());
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(getReactApplicationContext(), uri);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
I do not know where the problem is.
Errors:
I think the problem comes from here:
No Content Provider: http://localhost:8080

J2ME connect localhost nullpointerexception 0

I am trying to connect localhost and insert data into database through j2me application.but when I am connecting the server it shows there is a nullpointerexception 0 error.
this is midlet code
import java.io.DataOutputStream;
import java.io.InputStream;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.*;
public class Midlet_1 extends MIDlet implements CommandListener {
Display mdDisplay;
Form mForm;
StringItem messageitem;
Command exit, connectCommand;
public Midlet_1() {
mForm = new Form("My Counter midlet");
messageitem = new StringItem(null, "");
exit = new Command("Exit", Command.EXIT, 0);
connectCommand = new Command("Connect", Command.SCREEN, 0);
mForm.append(messageitem);
mForm.addCommand(exit);
mForm.addCommand(connectCommand);
mForm.setCommandListener(this);
}
public void startApp() {
mdDisplay = Display.getDisplay(this);
mdDisplay.setCurrent(mForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exit) {
notifyDestroyed();
} else if (c == connectCommand) {
Form waitform = new Form("Waiting");
mdDisplay.setCurrent(waitform);
Thread t = new Thread() {
public void run() {
connect();
}
};
t.start();
}
}
private void connect() {
try {
HttpConnection hs = null;
InputStream in = null;
String url = "localhost:8080/testweb/src/save";
hs.setRequestProperty("User-Agent", "Profile/MIDP-2.0,Configuration/CLDC-2.0");
hs.setRequestProperty("Content-Language", "en-US");
hs.setRequestMethod(HttpConnection.POST);
DataOutputStream ds = hs.openDataOutputStream();
ds.writeUTF("nam56");
ds.writeUTF("67");
ds.writeUTF("0716522549");
ds.flush();
ds.close();
in = hs.openInputStream();
int connectlength = (int) hs.getLength();
byte[] raw = new byte[connectlength];
int length = in.read(raw);
// int ch;
// StringBuffer sb=new StringBuffer();
// while((ch=in.read())!=-1){
// sb.append((char)ch);
// }
in.close();
hs.close();
String s = new String(raw, 0, length);
messageitem.setText(s);
} catch (Exception e) {
messageitem.setText(e.toString());
System.out.println(e);
}
mdDisplay.setCurrent(mForm);
}
}
and this is servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
DataInputStream in=new DataInputStream(request.getInputStream());
String name=in.readUTF();
String id=in.readUTF();
String contt=in.readUTF();
Connection c=DBcon.setconConnection();
Statement s=c.createStatement();
s.executeUpdate("insert into details values('"+id+"','"+name+"''"+contt+"')");
out.print("successfullllll");
} finally {
out.close();
}
}
please check this out.....
This might work only if you are running an emulator on the same machine as the server. Try to replace locahost by 127.0.0.1.
In your connect() method, I can see that you initialized hs as null then you called setRequestProperty. Try to initialize hs properly before calling its methods.