I am getting an exception for the following code. I am not able to understand what is UUID. Can anyone help to resolve this error? I have posted the code as well as error I am getting.
package wiki.nokia.example;
import java.io.IOException;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.L2CAPConnection;
import javax.bluetooth.L2CAPConnectionNotifier;
import javax.bluetooth.LocalDevice;
import javax.microedition.io.Connector;
public class BluetoothServer implements Runnable {
private boolean listening = true;
private LocalDevice local_device;
private BtoothChat midlet;
private String deviceName;
private L2CAPConnection con;
/** Creates a new instance of BluetoothServer */
public BluetoothServer(BtoothChat midlet) {
this.midlet = midlet;
Thread t = new Thread(this);
t.start();
}
public void run(){
System.out.println("Starting server - please wait...");
try {
local_device = LocalDevice.getLocalDevice();
DiscoveryAgent disc_agent = local_device.getDiscoveryAgent();
local_device.setDiscoverable(DiscoveryAgent.LIAC);
String service_UUID = "9";
deviceName = local_device.getFriendlyName();
String url = "btl2cap://localhost:" + service_UUID + ";name=" + deviceName;
L2CAPConnectionNotifier notifier = (L2CAPConnectionNotifier)Connector.open(url);
con = notifier.acceptAndOpen();
while (listening) {
if (con.ready()){
byte[] b = new byte[1000];
con.receive(b);
String s = new String(b, 0, b.length);
System.out.println("Recieved from client: " + s.trim());
midlet.setAlert(s.trim());
send("Hello client, my name is: " + getName());
listening=false;
}
}
} catch(BluetoothStateException e){System.out.println(e);} catch(IOException f){System.out.println(f);}
}
private void send(String s){
byte[] b = s.getBytes();
try {
con.send(b);
} catch(IOException e){
System.out.println(e);
}
}
private String getName(){
return deviceName;
}
}
ERROR IS:
Starting server - please wait...
Uncaught exception: java.lang.NumberFormatException
at java.lang.Long.parseLong(Long.java:401)
at javax.bluetooth.UUID.<init>(), bci=166
at com.sun.jsr082.bluetooth.btl2cap.L2CAPNotifierImpl.createServiceRecord(), bci=26
at com.sun.jsr082.bluetooth.btl2cap.L2CAPNotifierImpl.<init>(), bci=122
at com.sun.jsr082.bluetooth.btl2cap.Protocol.serverConnection(), bci=16
at com.sun.jsr082.bluetooth.BluetoothProtocol.openPrimImpl(), bci=24
at com.sun.jsr082.bluetooth.BluetoothProtocol.openPrim(), bci=14
at com.sun.midp.io.j2me.btl2cap.Protocol.openPrim(), bci=7
at javax.microedition.io.Connector.openPrim(), bci=327
at javax.microedition.io.Connector.open(), bci=3
at javax.microedition.io.Connector.open(), bci=3
at javax.microedition.io.Connector.open(), bci=2
at wiki.nokia.example.BluetoothServer.run(BluetoothServer.java:48)
at java.lang.Thread.run(), bci=11
You can find a definition of an UUID here. The problem is that the UUID you are using isn't appropriate. A value of '9' won't do.
Related
I am trying to modify this app. But for the first time I have to solve the permission problem which is not happening to me. I have pasted the code and the logcat. Please tell me a solution.
getDeviceId: The user 10214 does not meet the requirements to access
device identifiers
Splah
package com.xitij.spintoearn.Activity;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.facebook.ads.AudienceNetworkAds;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;
import com.xitij.spintoearn.Models.Settings;
import com.xitij.spintoearn.Models.User;
import com.xitij.spintoearn.R;
import com.xitij.spintoearn.Util.Constant;
import com.xitij.spintoearn.Util.Ex;
import com.xitij.spintoearn.Util.Method;
import com.xitij.spintoearn.Util.RestAPI;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import cz.msebera.android.httpclient.Header;
public class Splash extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 2000;
private Constant constant;
private String GetDeviceID(){
TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String deviceID = null;
int readIMEI= ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE);
if(deviceID == null) {
if (readIMEI == PackageManager.PERMISSION_GRANTED) {
deviceID = tm.getDeviceId().toString();
}
}
return deviceID;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AudienceNetworkAds.initialize(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
Constant.DeviceID = GetDeviceID();
login(Constant.DeviceID);
//Toast.makeText(Splash.this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
finish();
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setDeniedMessage("If you reject permission,you can not use this service\n\nPlease turn on permissions at [Setting] > [Permission]")
.setPermissions(Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_NETWORK_STATE,Manifest.permission.RECORD_AUDIO)
.check();
constant = new Constant(Splash.this);
Constant.DeviceID = GetDeviceID();
Ex.getIPaddress();
if(Ex.isConnectionEnable(this) && Ex.checkAndRequestPermissions(this,this)){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//login(Constant.DeviceID);
}
},SPLASH_TIME_OUT);
}
}
public void login(final String deviceid) {
String login = RestAPI.API_Device_Login + "&deviceid=" + deviceid;
AsyncHttpClient client = new AsyncHttpClient();
client.get(login, null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Response", new String(responseBody));
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
JSONArray jsonArray = jsonObject.getJSONArray(Constant.AppSid);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String success = object.getString("success");
if (success.equals("1")) {
String user_id = object.getString("user_id");
String name = object.getString("name");
String sendEmail = object.getString("email");
String userPhone = object.getString("phone");
String userCode = object.getString("user_code");
constant.sharedEditor.putBoolean(constant.isLogin, true);
constant.sharedEditor.putString(constant.profileId, user_id);
constant.sharedEditor.putString(constant.userName, name);
constant.sharedEditor.putString(constant.userEmail, sendEmail);
constant.sharedEditor.putString(constant.userPhone, userPhone);
constant.sharedEditor.putString(constant.userCode, userCode);
constant.sharedEditor.commit();
LoadSettings();
Constant.user =new User("00",name,sendEmail,"000",userPhone,userCode);
Method.UserLoginLogs(user_id,"Login",Constant.DeviceID);
Intent intent=new Intent(getBaseContext(),MainActivity.class);
startActivity(intent);
finish();
} else {
Intent inst = new Intent(Splash.this, Login.class);
inst.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(inst);
finish();
// Ex.okAlertBox(getResources().getString(R.string.login_failed_message));
//Toast.makeText(Login.this, getResources().getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Splash.this);
alertDialogBuilder.setTitle("Server Maintenance");
alertDialogBuilder.setMessage("System is Undergoing Maintenance. Please try again later.");
alertDialogBuilder.setPositiveButton(getApplication().getResources().getString(R.string.ok_message),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
public void LoadSettings() {
AsyncHttpClient client = new AsyncHttpClient();
client.get(RestAPI.API_Settings, null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Response-ls", new String(responseBody));
String res = new String(responseBody);
try {
JSONObject jsonObject = new JSONObject(res);
JSONArray jsonArray = jsonObject.getJSONArray(Constant.AppSid);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String app_name = object.getString("app_name");
String app_logo = object.getString("app_logo");
String app_version = object.getString("app_version");
String app_author = object.getString("app_author");
String app_contact = object.getString("app_contact");
String app_email = object.getString("app_email");
String app_website = object.getString("app_website");
String app_description = object.getString("app_description");
String app_developed_by = object.getString("app_developed_by");
String app_faq = object.getString("app_faq");
String app_privacy_policy = object.getString("app_privacy_policy");
String publisher_id = object.getString("publisher_id");
boolean interstital_ad = Boolean.parseBoolean(object.getString("interstital_ad"));
String interstital_ad_id = object.getString("interstital_ad_id");
String interstital_ad_click = object.getString("interstital_ad_click");
boolean banner_ad = Boolean.parseBoolean(object.getString("banner_ad"));
String banner_ad_id = object.getString("banner_ad_id");
boolean rewarded_video_ads = Boolean.parseBoolean(object.getString("rewarded_video_ads"));
String rewarded_video_ads_id = object.getString("rewarded_video_ads_id");
String redeem_currency = object.getString("redeem_currency");
String redeem_points = object.getString("redeem_points");
String redeem_money = object.getString("redeem_money");
String minimum_redeem_points = object.getString("minimum_redeem_points");
String payment_method1 = object.getString("payment_method1");
String payment_method2 = object.getString("payment_method2");
String payment_method3 = object.getString("payment_method3");
String payment_method4 = object.getString("payment_method4");
String daily_spin_limit = object.getString("daily_spin_limit");
String ads_frequency_limit= object.getString("ads_frequency_limit");
String video_add_point= object.getString("video_add_point");
String app_refer_reward= object.getString("app_refer_reward");
String registration_reward= object.getString("registration_reward");
String video_ads_limit= object.getString("daily_rewarded_video_ads_limits");
Constant.settings = new Settings(app_name, app_logo, app_version, app_author, app_contact, app_email, app_website, app_description, app_developed_by,
app_faq, app_privacy_policy, publisher_id, interstital_ad_id, interstital_ad_click, banner_ad_id, rewarded_video_ads_id, redeem_currency, redeem_points,
redeem_money, minimum_redeem_points, payment_method1, payment_method2, payment_method3, payment_method4, interstital_ad, banner_ad, rewarded_video_ads,daily_spin_limit,ads_frequency_limit,video_add_point,app_refer_reward,registration_reward,video_ads_limit);
Log.d("Response-ls",ads_frequency_limit );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
}
Constant
package com.xitij.spintoearn.Util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import com.xitij.spintoearn.Models.CoinHistory;
import com.xitij.spintoearn.Models.Settings;
import com.xitij.spintoearn.Models.SpinCounter;
import com.xitij.spintoearn.Models.User;
import com.xitij.spintoearn.Models.UserBalance;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.reward.RewardedVideoAd;
public class Constant {
public static final String AppSid="spin";
public static final int POINT_VIDEO_MIN=1;
public static final int POINT_VIDEO_MAX=100;
public static final int RATE_POINT=1000;
public static final int DAILY_CHECK=100;
public static String Total_Point;
//Enter milliseconds
public static final int Waitsecond=8000;
public static String PublicIP;
public static String DeviceID;
public static final String ReferPoint = "10";
public static final String VIDEO_AD_ID="ca-app-pub-3940256099942544/8691691433";
public static final String INSTE_AD_ID="ca-app-pub-3940256099942544/1033173712";
public static final String AD_ID= "#";
public static int AD_COUNT = 0;
public static int VIDEO_AD_COUNT= 0;
public static InterstitialAd mInterstitial;
public static RewardedVideoAd mRewardedVideoAd;
public static User user;
public static UserBalance userBalance;
public static CoinHistory coinHistory;
public static Settings settings;
public static SpinCounter spinCounter;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor sharedEditor;
private Activity activity;
private final String loginPerfm = "login";
public String isLogin = "isLogin";
private String deviceId = "deviceId";
public String profileId = "profileId";
public String userEmail = "userEmail";
public String userPassword = "userPassword";
public String userName = "userName";
public String userPhone = "userPhone";
public String userCode = "userCode";
public String Spin_Count = "Spin_Count";
#SuppressLint("CommitPrefEdits")
public Constant(Activity activity) {
this.activity = activity;
sharedPreferences = activity.getSharedPreferences(loginPerfm, 0); // 0 - for private mode
sharedEditor = sharedPreferences.edit();
}
}
logcat
2021-03-08 08:05:02.525 14296-14296/? E/itij.spintoear: Unknown bits set in runtime_flags: 0x8000
2021-03-08 08:05:04.622 14296-14296/com.xitij.spintoearn E/fdsan: attempted to close file descriptor 74, expected to be unowned, actually owned by FILE* 0x76c3b37018
2021-03-08 08:05:04.758 14296-14296/com.xitij.spintoearn E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xitij.spintoearn, PID: 14296
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xitij.spintoearn/com.xitij.spintoearn.Activity.Splash}: java.lang.SecurityException: getDeviceId: The user 10214 does not meet the requirements to access device identifiers.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3547)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2080)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7581)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.SecurityException: getDeviceId: The user 10214 does not meet the requirements to access device identifiers.
at android.os.Parcel.createException(Parcel.java:2071)
at android.os.Parcel.readException(Parcel.java:2039)
at android.os.Parcel.readException(Parcel.java:1987)
at com.android.internal.telephony.ITelephony$Stub$Proxy.getDeviceId(ITelephony.java:10389)
at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:1620)
at com.xitij.spintoearn.Activity.Splash.GetDeviceID(Splash.java:53)
at com.xitij.spintoearn.Activity.Splash.onCreate(Splash.java:99)
at android.app.Activity.performCreate(Activity.java:7805)
at android.app.Activity.performCreate(Activity.java:7794)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1306)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3378)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3547)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2080)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7581)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
I'm using this Java code to send messages in JSF page:
import com.web.utils.SendEmail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.mail.MessagingException;
import javax.servlet.http.Part;
#Named
#ViewScoped
public class Contacts implements Serializable
{
private static final long serialVersionUID = 1L;
private Part file;
private String name;
private String senderEmail;
private String telephone;
private String comment;
private String result;
public Contacts()
{
}
public void sendEmail() throws IOException, MessagingException
{
String[] to =
{
"test#gmail.com"
}; // list of recipient email addresses
String subject = name + " " + senderEmail + " " + telephone;
SendEmail mail = new SendEmail();
result = mail.intiSendEmail(to, subject, comment, file);
}
public void upload()
{
if (file != null)
{
try (InputStream inputStream = file.getInputStream(); FileOutputStream outputStream = new FileOutputStream("D:" + File.separator + "files" + File.separator + file.getSubmittedFileName()))
{
int bytesRead = 0;
final byte[] chunck = new byte[1024];
while ((bytesRead = inputStream.read(chunck)) != -1)
{
outputStream.write(chunck, 0, bytesRead);
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload successfully ended!"));
}
catch (IOException e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload failed!"));
}
}
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSenderEmail()
{
return senderEmail;
}
public void setSenderEmail(String senderEmail)
{
this.senderEmail = senderEmail;
}
public String getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public String getComment()
{
return comment;
}
public void setComment(String comment)
{
this.comment = comment;
}
public String getResult()
{
return result;
}
public void setResult(String result)
{
this.result = result;
}
public Part getFile()
{
return file;
}
public void setFile(Part file)
{
this.file = file;
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.servlet.http.Part;
public class SendEmail implements Serializable
{
private String USER_NAME = "test";
private String PASSWORD = "test!";
public String intiSendEmail(String[] to, String subject, String body, Part file) throws IOException, MessagingException
{
String status;
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", USER_NAME);
props.put("mail.smtp.password", PASSWORD);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try
{
message.setFrom(new InternetAddress(USER_NAME));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++)
{
toAddress[i] = new InternetAddress(to[i]);
}
for (int i = 0; i < toAddress.length; i++)
{
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
/**
* If file is not attached skip setting content
*/
if (file != null)
{
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
ByteArrayDataSource ds = new ByteArrayDataSource(file.getInputStream(), file.getContentType());
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
}
Transport transport = session.getTransport("smtp");
transport.connect(host, USER_NAME, PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae)
{
ae.printStackTrace();
return status = "Cannot send Message!";
}
catch (MessagingException me)
{
me.printStackTrace();
return status = "Cannot send Message!";
}
return status = "Message is send!";
}
/**
* For testing
*/
public void upload()
{
Part file = null;
if (file != null)
{
try (InputStream inputStream = file.getInputStream(); FileOutputStream outputStream = new FileOutputStream("D:" + File.separator + "files" + File.separator + file.getSubmittedFileName()))
{
int bytesRead = 0;
final byte[] chunck = new byte[1024];
while ((bytesRead = inputStream.read(chunck)) != -1)
{
outputStream.write(chunck, 0, bytesRead);
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload successfully ended!"));
}
catch (IOException e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload failed!"));
}
}
}
}
I added thread pool in order to speedup page performance. But I as you can see the code execution is not properly handled when package is redeployed. What it the proper way to stop Thread pool in JSF?
I'm going to write a programm that can save a name and a birthday-date. After closing the programm the data shouldn't be lost. If you open the programm, you are able to add an additional user to the according users. Unfortunately I'm always get a stackoverflow - exception and i didn't found the mistake.
<pre> package geburtstagstool;
import java.io.*;
public class GeburtstagsTool
{
public static void main (String[]args) throws Exception
{
Eintrag eintrag = new Eintrag ("Miller","000000");
}
}
class Eintrag implements Serializable
{
Eintrag [] eintrag = new Eintrag [50];
public String name;
public String gebDatum;
int i=0;
public Eintrag (String name, String gebDatum)
{
eintrag[i] = new Eintrag (name,gebDatum);
++i;
}
public void testSchreiben () throws Exception
{
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("eintrag.dat"));
oos.writeObject(eintrag);
oos.close();
}
public static Eintrag testLesen() throws IOException, ClassNotFoundException
{
ObjectInputStream ois = new ObjectInputStream (new FileInputStream ("eintrag.dat"));
Eintrag eint = (Eintrag) ois.readObject();
ois.close();
return eint;
}
}
<code>
Thanks for your help.
Here is a fully working solution. This should get you started. Good luck.
GeburtstagsTool class:
public class GeburtstagsTool {
List<Eintrag> eintragList;
public static void main (String[] args) throws IOException, ClassNotFoundException
{
GeburtstagsTool geburtstagsTool = new GeburtstagsTool();
geburtstagsTool.loadEintrag();
System.out.println("What's already in the list: \n" + geburtstagsTool.eintragList);
Eintrag eintrag = new Eintrag("Peyton Manning", "03/24/1976");
geburtstagsTool.eintragList.add(eintrag);
geburtstagsTool.writeEintrag();
}
public void loadEintrag() {}
{
ObjectInputStream ois = null;
try
{
ois = new ObjectInputStream(new FileInputStream("eintrag.dat"));
eintragList = (List<Eintrag>) ois.readObject();
}
catch (IOException e)
{
System.out.println("File doesn't exist");
eintragList = new ArrayList<>();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public void writeEintrag() throws IOException
{
ObjectOutputStream oos = null;
try
{
oos = new ObjectOutputStream(new FileOutputStream("eintrag.dat"));
}
catch (IOException e)
{
e.printStackTrace();
}
oos.writeObject(eintragList);
oos.close();
}
Eintrag class:
public class Eintrag implements Serializable{
String name;
String gebDatum;
public Eintrag(String name, String gebDatum) {
this.name = name;
this.gebDatum = gebDatum;
}
#Override
public String toString()
{
return "Eintrag{" +
"name='" + name + '\'' +
", gebDatum='" + gebDatum + '\'' +
'}';
}
Your problem is here
public Eintrag (String name, String gebDatum)
{
eintrag[i] = new Eintrag (name,gebDatum);
++i;
}
It's an endless loop. It's a recursive call without ending.
You call the constructor that call's it self.. so it does that until the whole stack is full.. and then You get the SF exception :)
I want to the following code to convert the thread to newFixedThreadpool()
how do I do it?
//saddddddddddddddddddddddddddddffgfggggggggggggggggggggggggfdhfdhfdhdhdfhjhljgjhgdadsadsafds
class client :
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.lang.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
String fileName = null;
try {
fileName = args[0];
} catch (Exception e) {
System.out.println("Enter the name of the file :");
Scanner scanner = new Scanner(System.in);
String file_name = scanner.nextLine();
File file = new File(file_name);
Socket socket = new Socket("localhost", 3332);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file.getName());
FileInputStream fis = new FileInputStream(file);
byte [] buffer = new byte[Server.BUFFER_SIZE];
Integer bytesRead = 0;
while ((bytesRead = fis.read(buffer)) > 0) {
oos.writeObject(bytesRead);
oos.writeObject(Arrays.copyOf(buffer, buffer.length));
}
oos.close();
ois.close();
System.exit(0);
}
}
}
class server:
import java.io.FileOutputStream;
import java.io.*;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
public static final int PORT = 3332;
public static final int BUFFER_SIZE = 100;
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
saveFile(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveFile(Socket socket) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
FileOutputStream fos = null;
byte [] buffer = new byte[BUFFER_SIZE];
Object o = ois.readObject();
if (o instanceof String) {
fos = new FileOutputStream(new File("/home/reza/Desktop/reza"));
} else {
throwException("Something is wrong");
}
Integer bytesRead = 0;
do {
o = ois.readObject();
if (!(o instanceof Integer)) {
throwException("Something is wrong");
}
bytesRead = (Integer)o;
o = ois.readObject();
if (!(o instanceof byte[])) {
throwException("Something is wrong");
}
buffer = (byte[])o;
fos.write(buffer, 0, bytesRead);
} while (bytesRead == BUFFER_SIZE);
System.out.println("File transfer success");
fos.close();
ois.close();
oos.close();
}
public static void throwException(String message) throws Exception {
throw new Exception(message);
}
public static void main(String[] args) {
new Server().start();
}
}
public class Server extends Thread {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
new ServerWorker(s).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ServerWorker extends Thread {
private Socket _socket;
public ServerWorker(Socket socket) {
this._socket = socket;
}
public void run() {
saveFile(this._socket);
// Thread should terminate when run returns.
}
private void saveFile(Socket socket) throws Exception {
...
}
}
I want to communicate to a server from J2me app using UDP.However, when I am running the app, I am getting a bad length exception.My codes and output are given below.
client code
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import java.io.IOException;
public class DatagramTest extends MIDlet
implements CommandListener, Runnable
{
private static final int BUF_SIZE = 1024;
private static Command exit = new Command("Exit", Command.EXIT, 1);
private static DatagramTest instance;
private Display display;
private TextBox dgramText;
private DatagramConnection conn;
private Datagram dgram;
private String address = "datagram://myip:9876";
public DatagramTest()
{
super();
instance = this;
}
public DatagramTest(String service)
{
this();
address = service;
}
/**
Returns the single instance of this class. Calling
this method before constructing an object will return
a null pointer.
#return an instance of this class.
*/
public static DatagramTest getInstance()
{
return instance;
}
public void startApp()
{
display = Display.getDisplay(this);
dgramText = new TextBox("Datagram contents",
null,
2048,
TextField.ANY);
dgramText.setCommandListener(this);
display.setCurrent(dgramText);
System.out.println("Starting run....");
run();
System.out.println("Stopping run....");
}
public void run()
{
System.out.println("In run....");
try
{
int maxLength;
conn = (DatagramConnection)Connector.open(address);
maxLength = conn.getMaximumLength();
dgram = conn.newDatagram(1024);
dgram.reset();
conn.send(dgram);
conn.receive(dgram);
byte[] data = dgram.getData();
// Extract the response string.
String str = new String(data);
System.out.println(str);
dgram.reset();
System.out.println("Exit run....");
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
quit();
}
return;
}
public void pauseApp()
{
}
void quit()
{
destroyApp(true);
notifyDestroyed();
}
public void destroyApp(boolean destroy)
{
try
{
conn.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
public void display()
{
Display.getDisplay(this).setCurrent(dgramText);
}
public void commandAction(Command c, Displayable d)
{
if (c == exit)
{
quit();
}
}
}
Server code
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
Output at clientside
Starting run.... In run.... Bad
datagram length java.io.IOException:
Bad datagram length
at com.sun.midp.io.j2me.datagram.Protocol.receive(Protocol.java:367)
at hello.DatagramTest.run(DatagramTest.java:89)
at hello.DatagramTest.startApp(DatagramTest.java:69)
at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:43)
at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:374)
at com.sun.midp.main.Main.runLocalClass(Main.java:466)
at com.sun.midp.main.Main.main(Main.java:120)
Stopping run....
Why I am getting this bad length exception and how do I sort it out?
One thing you need to try is to send and receive datagrams in a separate thread.
The documentation for DatagramConnection.receive() says: "This method blocks until a datagram is received"
You are calling it from inside MIDlet.startApp().
Blocking the application management system thread that calls startApp() is bad practice.