weblogic 12c response.flushBuffer() issue - ntlm

I have a ntlm filter in a web application deployed on weblogic 12c used to retrieve the logged user client name in order to authenticate it automatically.
My filter class is below.
The problem is that in weblogic response.flushBuffer() does nothing.
The status page from browser is 401.
This code works well with Jetty Http Server.
Any idea on how to resolve this?
Thanks!
package com.asf.ntlm.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jcifs.ntlmssp.Type3Message;
public class AsfNtlmFilter implements javax.servlet.Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
System.out.println("Ntlm filter!!!");
String username = null;
// first, get the user agent
String useragent = request.getHeader("user-agent");
// if you're using IE, you can continue
// Always do the ntlm check (for IE POST back)
try {
String auth = request.getHeader("Authorization");
if (auth == null) {
response.setHeader("WWW-Authenticate", "NTLM");
response.setStatus(response.SC_UNAUTHORIZED);
response.setContentLength(0);
response.flushBuffer();
return;
}
if (auth.startsWith("NTLM ")) {
byte[] msg = new sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5));
int off = 0, length, offset;
if (msg[8] == 1) {
byte z = 0;
byte[] msg1 = { (byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M', (byte) 'S', (byte) 'S', (byte) 'P',
z, (byte) 2, z, z, z, z, z, z, z, (byte) 40, z, z, z, (byte) 1, (byte) 130, z, z, z,
(byte) 2, (byte) 2, (byte) 2, z, z, z, z, z, z, z, z, z, z, z, z };
response.setHeader("WWW-Authenticate", "NTLM " + new sun.misc.BASE64Encoder().encodeBuffer(msg1));
response.setStatus(response.SC_UNAUTHORIZED);
response.setContentLength(0);
response.flushBuffer();
return;
} else if (msg[8] == 3) {
// Did Authentication Succeed? All this is always
// printed.
Type3Message type3 = new Type3Message(msg);
System.out.println("osUser: " + type3.getUser());
System.out.println("osRemoteHost: + " + type3.getWorkstation());
System.out.println("osDomain: " + type3.getDomain());
}
}
} catch (Exception e) {
System.out.println(e);
}
// System.out.println("Suc);
try {
chain.doFilter(req, res);
} catch (IOException e) {
System.out.println(e);
} catch (ServletException e) {
System.out.println(e);
}
}
#Override
public void destroy() {
filterConfig = null;
}
}

It was a problem with Weblogic.
I reinstall it and now works well.

Related

Issues with runaway thread

I'm pretty new to android studio. I noticed that my program had a very severe performance hiccup and I believe it is slowing down after I run the app every time. I think I have a runaway thread and I will attach pictures at the end of my post. I could really use some help. The first picture shows an example of the thread and then the second picture shows the thread after 5 minutes or so of waiting. I attached two codes. CameraSurfaceView runs the code while FaceDetectionThread creates the thread.
package com.example.phliip_vision;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import com.example.phliip_vision.Point;
import com.example.phliip_vision.MeasurementStepMessage;
import com.example.phliip_vision.MessageHUB;
import com.example.phliip_vision.Util;
public class CameraSurfaceView extends SurfaceView implements Callback,
Camera.PreviewCallback {
public static final int CALIBRATION_DISTANCE_A4_MM = 294;
public static final int CALIBRATION_MEASUREMENTS = 10;
public static final int AVERAGE_THREASHHOLD = 5;
private static final String TAG = "CameraSurfaceView";
/**
* Measured distance at calibration point
*/
private float _distanceAtCalibrationPoint = -1;
private float _currentAvgEyeDistance = -1;
// private int _facesFoundInMeasurement = -1;
/**
* in cm
*/
private float _currentDistanceToFace = -1;
private final SurfaceHolder mHolder;
private Camera mCamera;
private Face _foundFace = null;
private int _threashold = CALIBRATION_MEASUREMENTS;
private FaceDetectionThread _currentFaceDetectionThread;
private List<Point> _points;
protected final Paint _middlePointColor = new Paint();
protected final Paint _eyeColor = new Paint();
private Size _previewSize;
// private boolean _measurementStartet = false;
private boolean _calibrated = false;
private boolean _calibrating = false;
private int _calibrationsLeft = -1;
public CameraSurfaceView(final Context context, final AttributeSet attrs) {
super(context, attrs);
_middlePointColor.setARGB(100, 200, 0, 0);
_middlePointColor.setStyle(Paint.Style.FILL);
_middlePointColor.setStrokeWidth(2);
_eyeColor.setColor(Color.GREEN);
mHolder = getHolder();
mHolder.addCallback(this);
}
public void setCamera(final Camera camera) {
mCamera = camera;
if (mCamera != null) {
requestLayout();
Log.d(TAG, "mCamera RANNNNNNN!!!!");
Camera.Parameters params = mCamera.getParameters();
camera.setDisplayOrientation(90);
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
Log.d(TAG, "FOCUS_MODE_AUTO RANNNNNNN!!!!");
// set the focus mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
// set Camera parameters
mCamera.setParameters(params);
}
}
}
/**
* Variables for the onDraw method, in order to prevent variable allocation
* to slow down the sometimes heavily called onDraw method
*/
private final PointF _middlePoint = new PointF();
private final Rect _trackingRectangle = new Rect();
private final static int RECTANGLE_SIZE = 20;
private boolean _showEyes = false;
private boolean _showTracking = true;
#SuppressLint("DrawAllocation")
#Override
protected void onDraw(final Canvas canvas) {
// super.onDraw(canvas);
if (_foundFace != null) {
_foundFace.getMidPoint(_middlePoint);
Log.d(TAG, "_middlePoint RANNNNNNN!!!!");
Log.i("Camera", _middlePoint.x + " : " + _middlePoint.y);
// portrait mode!
float heightRatio = getHeight() / (float) _previewSize.width;
float widthRatio = getWidth() / (float) _previewSize.height;
Log.i("Drawcall", _middlePoint.x + " : " + _middlePoint.y);
int realX = (int) (_middlePoint.x * widthRatio);
int realY = (int) (_middlePoint.y * heightRatio);
Log.i("Drawcall", "Real :" + realX + " : " + realY);
int halfEyeDist = (int) (widthRatio * _foundFace.eyesDistance() / 2);
if (_showTracking) {
// Middle point
Log.d(TAG, "_showTracking RANNNNNNN!!!!");
_trackingRectangle.left = realX - RECTANGLE_SIZE;
_trackingRectangle.top = realY - RECTANGLE_SIZE;
_trackingRectangle.right = realX + RECTANGLE_SIZE;
_trackingRectangle.bottom = realY + RECTANGLE_SIZE;
canvas.drawRect(_trackingRectangle, _middlePointColor);
}
if (_showEyes) {
// Left eye
Log.d(TAG, "_showEyes RANNNNNNN!!!!");
_trackingRectangle.left = realX - halfEyeDist - RECTANGLE_SIZE;
_trackingRectangle.top = realY - RECTANGLE_SIZE;
_trackingRectangle.right = realX - halfEyeDist + RECTANGLE_SIZE;
_trackingRectangle.bottom = realY + RECTANGLE_SIZE;
canvas.drawRect(_trackingRectangle, _eyeColor);
// Right eye
_trackingRectangle.left = realX + halfEyeDist - RECTANGLE_SIZE;
_trackingRectangle.top = realY - RECTANGLE_SIZE;
_trackingRectangle.right = realX + halfEyeDist + RECTANGLE_SIZE;
_trackingRectangle.bottom = realY + RECTANGLE_SIZE;
canvas.drawRect(_trackingRectangle, _eyeColor);
}
}
}
public void reset() {
Log.d(TAG, "reset RANNNNNNN!!!!");
_distanceAtCalibrationPoint = -1;
_currentAvgEyeDistance = -1;
_calibrated = false;
_calibrating = false;
_calibrationsLeft = -1;
}
/**
* Sets this current EYE distance to be the distance of a peace of a4 paper
* e.g. 29,7cm
*/
public void calibrate() {
Log.d(TAG, "calibrate RANNNNNNN!!!!");
if (!_calibrating || !_calibrated) {
_points = new ArrayList<>();
_calibrating = true;
_calibrationsLeft = CALIBRATION_MEASUREMENTS;
_threashold = CALIBRATION_MEASUREMENTS;
}
}
private void doneCalibrating() {
Log.d(TAG, "doneCalibrating RANNNNNNN!!!!");
_calibrated = true;
_calibrating = false;
_currentFaceDetectionThread = null;
// _measurementStartet = false;
_threashold = AVERAGE_THREASHHOLD;
_distanceAtCalibrationPoint = _currentAvgEyeDistance;
MessageHUB.get().sendMessage(MessageHUB.DONE_CALIBRATION, null);
}
public boolean isCalibrated() {
Log.d(TAG, "isCalibrated RANNNNNNN!!!!");
return _calibrated || _calibrating;
}
public void showMiddleEye(final boolean on) {
Log.d(TAG, "showMiddleEye RANNNNNNN!!!!");
_showTracking = on;
}
public void showEyePoints(final boolean on) {
Log.d(TAG, "showEyePoints RANNNNNNN!!!!");
_showEyes = on;
}
private void updateMeasurement(final FaceDetector.Face currentFace) {
if (currentFace == null) {
Log.d(TAG, "updateMeasurement RANNNNNNN!!!!");
// _facesFoundInMeasurement--;
return;
}
_foundFace = _currentFaceDetectionThread.getCurrentFace();
_points.add(new Point(_foundFace.eyesDistance(),
CALIBRATION_DISTANCE_A4_MM
* (_distanceAtCalibrationPoint / _foundFace
.eyesDistance())));
while (_points.size() > _threashold) {
_points.remove(0);
Log.d(TAG, "Removing points RANNNNNNN!!!!");
}
float sum = 0;
for (Point p : _points) {
sum += p.getEyeDistance();
Log.d(TAG, "adding points RANNNNNNN!!!!");
}
_currentAvgEyeDistance = sum / _points.size();
_currentDistanceToFace = CALIBRATION_DISTANCE_A4_MM
* (_distanceAtCalibrationPoint / _currentAvgEyeDistance);
_currentDistanceToFace = Util.MM_TO_CM(_currentDistanceToFace);
MeasurementStepMessage message = new MeasurementStepMessage();
message.setConfidence(currentFace.confidence());
message.setCurrentAvgEyeDistance(_currentAvgEyeDistance);
message.setDistToFace(_currentDistanceToFace);
message.setEyesDistance(currentFace.eyesDistance());
message.setMeasurementsLeft(_calibrationsLeft);
message.setProcessTimeForLastFrame(_processTimeForLastFrame);
MessageHUB.get().sendMessage(MessageHUB.MEASUREMENT_STEP, message);
}
private long _lastFrameStart = System.currentTimeMillis();
private float _processTimeForLastFrame = -1;
#Override
public void onPreviewFrame(final byte[] data, final Camera camera) {
Log.d(TAG, "onPreviewFrame RANNNNNNN!!!!" + _calibrationsLeft);
if (_calibrationsLeft == -1)
return;
if (_calibrationsLeft > 0) {
// Doing calibration !
Log.d(TAG, "_calibrationLeft RANNNNNNN!!!!" + _calibrationsLeft);
if (_currentFaceDetectionThread != null
&& _currentFaceDetectionThread.isAlive()) {
Log.d(TAG, "_currentFaceDectectionThread RANNNNNNN!!!!" + _currentFaceDetectionThread);
// Drop Frame
return;
}
// No face detection started or already finished
_processTimeForLastFrame = System.currentTimeMillis()
- _lastFrameStart;
_lastFrameStart = System.currentTimeMillis();
if (_currentFaceDetectionThread != null) {
Log.d(TAG, "_calibrationLeft-- RANNNNNNN!!!!");
_calibrationsLeft--;
updateMeasurement(_currentFaceDetectionThread.getCurrentFace());
if (_calibrationsLeft == 0) {
Log.d(TAG, "Calibrating done RANNNNNNN!!!!");
doneCalibrating();
invalidate();
return;
}
}
_currentFaceDetectionThread = new FaceDetectionThread(data,
_previewSize);
_currentFaceDetectionThread.start();
invalidate();
} else {
// Simple Measurement
if (_currentFaceDetectionThread != null
&& _currentFaceDetectionThread.isAlive()) {
Log.d(TAG, "Dropping frames RANNNNNNN!!!!");
// Drop Frame
return;
}
// No face detection started or already finished
_processTimeForLastFrame = System.currentTimeMillis()
- _lastFrameStart;
_lastFrameStart = System.currentTimeMillis();
if (_currentFaceDetectionThread != null)
updateMeasurement(_currentFaceDetectionThread.getCurrentFace());
Log.d(TAG, "Updating measurements RANNNNNNN!!!!");
_currentFaceDetectionThread = new FaceDetectionThread(data,
_previewSize);
_currentFaceDetectionThread.start();
Log.d(TAG, "invalidate RANNNNNNN!!!!");
invalidate();
}
}
/*
* SURFACE METHODS, TO CREATE AND RELEASE SURFACE THE CORRECT WAY.
*
* #see
* android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder
* )
*/
#Override
public void surfaceCreated(final SurfaceHolder holder) {
synchronized (this) {
// This allows us to make our own drawBitmap
this.setWillNotDraw(false);
}
}
#Override
public void surfaceDestroyed(final SurfaceHolder holder) {
mCamera.release();
mCamera = null;
}
#Override
public void surfaceChanged(final SurfaceHolder holder, final int format,
final int width, final int height) {
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
Parameters parameters = mCamera.getParameters();
_previewSize = parameters.getPreviewSize();
// mCamera.setDisplayOrientation(90);
// mCamera.setParameters(parameters);
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
mCamera.setPreviewCallback(this);
} catch (Exception e) {
Log.d("This", "Error starting camera preview: " + e.getMessage());
}
}
}
Here is the other code.
package com.example.phliip_vision;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera.Size;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.util.Log;
public class FaceDetectionThread extends Thread {
public static final String FACEDETECTIONTHREAD_TAG = "FaceDetectionThread_Tag";
private static final String TAG = "FaceDetectionThread";
private Face _currentFace;
private final byte[] _data;
private final Size _previewSize;
private Bitmap _currentFrame;
public FaceDetectionThread(final byte[] data, final Size previewSize) {
Log.d(TAG, "What are we waiting on in FaceDetectionThread????");
_data = data;
_previewSize = previewSize;
}
public Face getCurrentFace() {
Log.d(TAG, "What are we waiting on in Current faces????");
return _currentFace;
}
public Bitmap getCurrentFrame() {
return _currentFrame;
}
/**
* bla bla bla
*/
#Override
public void run() {
long t = System.currentTimeMillis();
YuvImage yuvimage = new YuvImage(_data, ImageFormat.NV21,
_previewSize.width, _previewSize.height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!yuvimage.compressToJpeg(new Rect(0, 0, _previewSize.width,
_previewSize.height), 100, baos)) {
Log.e("Camera", "compressToJpeg failed");
}
Log.i("Timing", "Compression finished: "
+ (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inPreferredConfig = Bitmap.Config.RGB_565;
_currentFrame = BitmapFactory.decodeStream(new ByteArrayInputStream(
baos.toByteArray()), null, bfo);
Log.i("Timing", "Decode Finished: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
// Rotate the so it siuts our portrait mode
Matrix matrix = new Matrix();
matrix.postRotate(90);
matrix.preScale(-1, 1);
// We rotate the same Bitmap
_currentFrame = Bitmap.createBitmap(_currentFrame, 0, 0,
_previewSize.width, _previewSize.height, matrix, false);
Log.i("Timing",
"Rotate, Create finished: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
if (_currentFrame == null) {
Log.e(FACEDETECTIONTHREAD_TAG, "Could not decode Image");
return;
}
FaceDetector d = new FaceDetector(_currentFrame.getWidth(),
_currentFrame.getHeight(), 1);
Face[] faces = new Face[1];
d.findFaces(_currentFrame, faces);
Log.i("Timing",
"FaceDetection finished: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
_currentFace = faces[0];
Log.d(FACEDETECTIONTHREAD_TAG, "Found: " + faces[0] + " Faces");
}
}
enter image description here
enter image description here

AudioRecord buffer values

Hi I am building an app that will use incoming audio from the MIC and compare it with a stored sound file. At the moment I am trying to get to grips with what the data from the AudioRecord function looks like when saved to a array of bytes. My problem is that the values that are returned are all zero. I don't know if I am maybe not using/setting up the AudioRecord function properly. Here is my code:
import android.app.Activity;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SnoreAlarmActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button start, stop;
TextView display;
Boolean rec = false;
AudioRecord snore;
byte[] arrayOfByte = new byte[16 * 1024 / 8];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.bStart);
stop = (Button) findViewById(R.id.bStop);
display = (TextView) findViewById(R.id.tAnswer);
start.setOnClickListener(this);
stop.setOnClickListener(this);
int i = AudioRecord.getMinBufferSize(44100, 16, 2);
snore = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100, 16, 2, i);// From
// MIC,Sample
// Rate
// of
// 44100,
// Channel_IN_MONO,16Bit
// Encoding,buffer
// size
// i
new Record().start();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.bStart:
rec = true;
break;
case R.id.bStop:
rec = false;
snore.stop();
snore.release();
for (int i = 0; i < 100; i++) {
int x = (int) arrayOfByte[i];
Log.w("Tag", "" + x);
}
break;
}
}
class Record extends Thread {
Record() {
}
#Override
public void run() {
// TODO Auto-generated method stub
while (rec) {
snore.startRecording();
snore.read(arrayOfByte, 0, (16 * 1024 / 8));
}
}
}
}
So my question is, why am I getting zero's?
*Also I know I should store the data in a short because of 16Bit encoding, will do that later, just trying to understand the values returned from the AudioRecord function at the moment.
Recording through MIC give me headache :)
Hope this will help because I lost whole day playing with it.
Here are steps which must be satisfied for MIC to work
Maniefst.xml MUST contains:
< uses-permission android:name="android.permission.RECORD_AUDIO" />
AudioRecord buffer should be set with AudioRecord.getMinBufferSize (you did it right)
If MIC wasn't released, you WON'T be able to bind to MIC again!
Restarting your phone will reset MIC.
Here is short example how I did it.
private android.media.AudioRecord aRecorder = null;
private Boolean breakLoop = false;
private byte[] buffer;
public Boolean StartRecording()
int freq = 22050;
try
{
prepareWaveFile(MyRandomAccessFile); //open file and writes WAV header
int bufferSize = android.media.AudioRecord.getMinBufferSize(freq, android.media.AudioFormat.CHANNEL_IN_MONO, android.media.AudioFormat.ENCODING_PCM_16BIT);
buffer = new byte[bufferSize];
if(bufferSize == AudioRecord.ERROR_BAD_VALUE){
Log.e(LOG_TAG, "Min buff size error");
return false;
}
aRecorder = new android.media.AudioRecord(MediaRecorder.AudioSource.MIC, freq, android.media.AudioFormat.CHANNEL_IN_MONO, android.media.AudioFormat.ENCODING_PCM_16BIT, bufferSize);
aRecorder.startRecording();
breakLoop = false;
int TotalSize=0; //koliko je snimljeno podataka
while (TotalSize < freq * 2 * 1 * 30) { //SampleRate * BytesPerSample * NumberOfChannels * seconds
int bufferReadResult = aRecorder.read(buffer, 0, bufferSize);
TotalSize+=bufferReadResult; // filesize failsafe
if (breakLoop) break; //if other thread stops recording
if (bufferReadResult>0) MyRandomAccessFile.write(buffer, 0, bufferReadResult); //write into some file ...
}
aRecorder.stop();
aRecorder.release(); //this is mandatory !
updateWaveFile(MyRandomAccessFile); //updates wave header
MyRandomAccessFile.close();
return true;
} catch (Exception e)
{
Log.e(LOG_TAG, "StartRecording: LOOP " + e);
try
{
aRecorder.stop();
} catch(Exception ex) {}
try
{
aRecorder.release();
} catch(Exception ex) {}
try
{
randomAccessWriter.close();
} catch(Exception ex) {}
return false;
}
are you on the Emulator? I heard that the Mic doesn't work on that.

java.lang.nullpointerexception in j2me

I am writing an application for read the mifare card,but when I pass the APDU the error occur that on emulator "java.lang.nullpointerexception".I have successfully detect the ISO14443_CARD after that I pass the APDU like
if (tp.hasTargetType(TargetType.ISO14443_CARD)){
form.append("Target is ISO14443_CARD\n");
try {
static byte[] APDU_AUTH1 = { (byte) 0xff, (byte) 0x86, (byte) 0x00, (byte) 0x00, (byte) 0x05,(byte)0x01,(byte)0x00,(byte)0xfc,(byte)0x60,(byte)0x00};
static byte[] STATUS_BYTE = {(byte)0x90,(byte)0x00};
if(STATUS_BYTE == iso14443.exchangeData(APDU_LOAD_KEY))
{
String value1 = new String("Hai!");
textfield1.setString(value1);
form.append(textfield1);
}
else
{
String value1 = new String("Hello!");
textfield1.setString(value1);
form.append(textfield1);
}
}
catch (Exception ex) {
form.append(ex.toString());
}
}
Either of iso14443 or textfield1 objects is likely null.
With the way you debug things (quite smart BTW, my congratulations), you could log the checks about as follows:
form.append("\n\n iso14443 is null: [" + (iso14443 == null)
+ "],\n textfield1 is null: [" + (textfield1 == null) + "]");

Commands sometimes don't work

There is a Canvas which has two Commands. The problem is that when the canvas is first opened then the commands work , but when I open it for the second time then the command doesn't work! Here is the code:
package view;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.StringItem;
public class DetailPhotoClient extends Canvas implements CommandListener {
private Command delete, back;
private GaleriePhotos backForm;
private FileConnection fcFile;
private Image sourceImage;
private InputStream is;
private boolean ok,oom, io;
public DetailPhotoClient(GaleriePhotos prevForm, String absolutePathphotoName)
{
super();
back = new Command("Retour", Command.SCREEN, 1);
addCommand(back);
delete = new Command("Supprimer", Command.SCREEN, 2);
addCommand(delete);
setCommandListener(this);
backForm = prevForm;
ok = true;
oom = false;
io = false;
try {
fcFile = (FileConnection) Connector.open(absolutePathphotoName, Connector.READ);
is = fcFile.openInputStream();
sourceImage = Image.createImage(is);
is.close();
fcFile.close();
} catch (IOException ex) {
handleException();
} catch (OutOfMemoryError oome) {
handleOOM();
}
}
private void handleException() {
ok = false;
io = true;
repaint();
}
private void handleOOM() {
ok = false;
oom = true;
repaint();
}
protected void paint(Graphics g) {
StringItem chp;
int chpW;
int x, y = getHeight()/2;
g.fillRect(0, 0, getWidth(), getHeight());
if (ok)
g.drawImage(sourceImage, 0, 0, Graphics.TOP | Graphics.LEFT);
if (io)
{
chp = new StringItem(null,"Erreur média et/ou d'entrée-sortie !");
chpW = chp.getPreferredWidth();
x = ( getWidth() - chpW ) / 2 ;
g.setColor(16711422);
if (x<0)
g.drawString("Erreur média et/ou d'entrée-sortie !", 0, y, Graphics.TOP | Graphics.LEFT);
else
g.drawString("Erreur média et/ou d'entrée-sortie !", x, y, Graphics.TOP | Graphics.LEFT);
}
if (oom)
{
chp = new StringItem(null,"Mémoire insuffisante !");
chpW = chp.getPreferredWidth();
x = ( getWidth() - chpW ) / 2 ;
g.setColor(16711422);
if (x<0)
g.drawString("Mémoire insuffisante !", 0, y, Graphics.TOP | Graphics.LEFT);
else
g.drawString("Mémoire insuffisante !", x, y, Graphics.TOP | Graphics.LEFT);
}
}
public void commandAction(Command c, Displayable d) {
if (c == back)
backForm.showBack();
else
{
backForm.showBack();
backForm.deletePhoto();
}
}
}
So why doesn't the Command work sometimes? Tested the app with an Alcatel OT-806D phone
Well your code is widely exposed to threats related to CommandListener to start with. Look, any piece of code "outside" your class can make your commands irresponsive:
void makeItDeaf(DetailPhotoClient detailPhotoClient) {
detailPhotoClient.setCommandListener(null);
// voila! your commands will be still visible but
// wouldn't respond anymore
}
To make sure that you don't accidentally break the command listener like above, "hide" it about as follows:
//...
public class DetailPhotoClient extends Canvas { // no "implements" here
private Command delete, back;
private GaleriePhotos backForm;
private FileConnection fcFile;
private Image sourceImage;
private InputStream is;
private boolean ok,oom, io;
public DetailPhotoClient(GaleriePhotos prevForm,
String absolutePathphotoName)
{
super();
back = new Command("Retour", Command.SCREEN, 1);
addCommand(back);
delete = new Command("Supprimer", Command.SCREEN, 2);
addCommand(delete);
backForm = prevForm;
setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (backForm == null) {
System.out.println("backForm is null: ignore command");
return;
}
if (c == back) {
System.out.println("back command");
backForm.showBack();
} else {
System.out.println("delete command");
backForm.showBack();
backForm.deletePhoto();
}
}
});
ok = true;
oom = false;
//...
}
//...
}

java-me bluetooth file send

i am having two cell phones and i want to exchange file between these two.
Device A invoke java app, it will scan available bluetooth device in range, show them into list and user can select one device and click send.
i have written below code, it is not working.
package hello;
import java.io.*;
import java.util.Vector;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.io.StreamConnection.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.obex.*;
import javax.obex.ResponseCodes;
public class MyMidlet extends MIDlet implements CommandListener, DiscoveryListener
{
public Command cmdSend;
public Command cmdScan;
public TextBox myText;
public List devList;
public Form myForm;
private LocalDevice localDev;
private DiscoveryAgent dAgent;
private ServiceRecord servRecord;
private Vector myVector;
private ClientSession connection = null;
private String url = null;
private Operation op = null;
private boolean cancelInvoked = false;
public MyMidlet()
{
cmdSend = new Command("Send", 2, 0);
cmdScan = new Command("Scan", 5, 0);
}
public void startApp()
{
if(myText == null)
{
myText = new TextBox("Dummy Text", "Hello", 10, 0);
myText.addCommand(cmdScan);
myText.setCommandListener(this);
Display.getDisplay(this).setCurrent(myText);
}
}
public void pauseApp(){}
public void destroyApp(boolean flag) { }
public void commandAction(Command command, Displayable displayable)
{
if(command == cmdScan)
{
if(myForm == null) { myForm = new Form("Scanning"); }
else {
for(int i = 0; i < myForm.size(); i++) myForm.delete(i);
}
myForm.append("Scanning for bluetooth devices..");
Display.getDisplay(this).setCurrent(myForm);
if(devList == null)
{
devList = new List("Devices", 3);
devList.addCommand(cmdSend);
devList.setCommandListener(this);
} else
{
for(int j = 0; j < devList.size(); j++) devList.delete(j);
}
if(myVector == null) myVector = new Vector();
else myVector.removeAllElements();
try
{
if(localDev == null)
{
localDev = LocalDevice.getLocalDevice();
localDev.setDiscoverable(0x9e8b33);
dAgent = localDev.getDiscoveryAgent();
}
dAgent.startInquiry(0x9e8b33, this);
}
catch(BluetoothStateException bluetoothstateexception)
{
myForm.append("Please check your bluetooth is turn-on");
}
}
if(command == cmdSend)
{
myForm.setTitle("Sending");
for(int k = 0; k < myForm.size(); k++) myForm.delete(k);
myForm.append("Sending application..");
Display.getDisplay(this).setCurrent(myForm);
try
{
RemoteDevice remotedevice = (RemoteDevice)myVector.elementAt(devList.getSelectedIndex());
dAgent.searchServices(null, new UUID[] {new UUID(4358L)}, remotedevice, this);
return;
}
catch(BluetoothStateException bluetoothstateexception1)
{
myForm.append("could not open bluetooth: " + bluetoothstateexception1.toString());
}
}
}
public void deviceDiscovered(RemoteDevice remotedevice, DeviceClass deviceclass)
{
try
{
devList.append(remotedevice.getFriendlyName(false), null);
}
catch(IOException _ex)
{
devList.append(remotedevice.getBluetoothAddress(), null);
}
myVector.addElement(remotedevice);
}
public void servicesDiscovered(int i, ServiceRecord aservicerecord[])
{
servRecord = aservicerecord[0];
}
public void serviceSearchCompleted(int i, int j)
{
if(j != 1) myForm.append("service search not completed: " + j);
try
{
byte[] fileContent = "Raxit Sheth -98922 38248".getBytes();
String s=servRecord.getConnectionURL(0, false);
myForm.append("Debug 0");
connection = (ClientSession) Connector.open(s);
myForm.append("Debug1");
HeaderSet headerSet = connection.connect(null);
myForm.append("Debug1.1");
headerSet.setHeader(HeaderSet.NAME, "a.txt");
headerSet.setHeader(HeaderSet.TYPE, "text/plain");
headerSet.setHeader(HeaderSet.LENGTH, new Long(fileContent.length));
myForm.append("Debug1.2");
//op = connection.put(headerSet); throwing java.lang.IllegalArgument.Exception
op = connection.put(null);
myForm.append("Debug1.2.1");
op.sendHeaders(headerSet);
myForm.append("Debug1.3");
OutputStream out = op.openOutputStream();
myForm.append("Debug2");
//sending data
myForm.append("Debug3");
out.write(fileContent);
myForm.append("Debug4");
//int responseCode = op.getResponseCode();
//myForm.append("resp code="+responseCode);
out.close();
op.close();
connection.close();
myForm.append("Done");
//i was expecting this will send a.txt file with content Raxit Sheth -98922 38248
//to remote device's inbox/gallery/bluetooth folder
}
catch(Exception ex) { myForm.append(ex.toString()); }
}
public void inquiryCompleted(int i)
{
Display.getDisplay(this).setCurrent(devList);
}
}
Your problem is almost certainly the fact that you're starting your bluetooth scanning in the commandAction() method. This is a system lifecycle method, and needs to return quickly. Attempting to perform a blocking operations (such as bluetooth scanning) in this thread could tie up resources which the handset needs to do other things such as the actual scanning!
Refactor so that the scanning is performed in a new thread, then try again.

Resources