PayPal roundtrip sandbox testing - paypal

I am looking for a way for the PayPal sandbox for a round trip test:
create a payment and redirect the user to PayPal so he can log in and approve
user follow the redirect and log in and approve the payment
verify payment on shop side
The steps 1. and 3. are not the problem. But how can I approve the payment automatically in the sand box. IMHO this is a scenario which every developer should need for automatic regression testing but I could not find any solution.
I use Java JUnit for regression tests.
I have tried with WebClient, but PayPal nags about cookies and JavaScript. So I got no success with that.

With the following code I could log in into PayPal developer page. Maybe for someone else this is useful.
package paypaltest;
import java.io.IOException;
public class htmlUnitTest extends TestCase {
#Test
public void test() {
final WebClient wc = new WebClient(BrowserVersion.FIREFOX_10);
wc.getCookieManager().setCookiesEnabled(true);
wc.setJavaScriptEnabled(false);
wc.setWebConnection(new TestHttpWebConnection(wc));
try {
final HtmlPage page = wc.getPage("https://developer.paypal.com/");
System.out.println(page.asXml());
final List<HtmlAnchor> anchors = page.getAnchors();
HtmlAnchor loginAnchor = null;
for (final HtmlAnchor htmlAnchor : anchors) {
if (htmlAnchor.getHrefAttribute().startsWith("https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize?client_id")) {
loginAnchor = htmlAnchor;
break;
}
}
if (loginAnchor != null) {
System.out.println("### login anchor");
System.out.println(loginAnchor.asXml());
System.out.println("### login to: " + loginAnchor.getHrefAttribute());
final HtmlPage loginPage = wc.getPage(loginAnchor.getHrefAttribute());
System.out.println("### login page");
System.out.println(loginPage.asXml());
final HtmlForm loginForm = loginPage.getForms().get(0);
final HtmlInput email = loginForm.getInputByName("email");
final HtmlInput password = loginForm.getInputByName("password");
final HtmlInput login = loginForm.getInputByValue("Log In");
email.setValueAttribute("my#email.com");
password.setValueAttribute("password");
final HtmlPage loggedInPage = login.click();
System.out.println("### logged in page");
System.out.println(loggedInPage.asXml());
}
final HtmlPage pageLoggedIn = wc.getPage("https://developer.paypal.com/");
System.out.println("### page logged in ");
System.out.println(pageLoggedIn.asXml());
} catch (final FailingHttpStatusCodeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static final class EasySSLSocketFactory implements SchemeLayeredSocketFactory {
// ** Log object for this class. *//*
private static final Log LOG = LogFactory.getLog(EasySSLSocketFactory.class);
private SSLContext sslcontext = null;
public Socket createSocket(final HttpParams params) throws IOException {
final SSLSocket sock = (SSLSocket) getSSLContext().getSocketFactory().createSocket();
return sock;
}
public Socket createLayeredSocket(final Socket socket, final String target, final int port, final HttpParams params) throws IOException,
UnknownHostException {
final SSLSocket sslSocket = (SSLSocket) getSSLContext().getSocketFactory().createSocket(socket, target, port, true);
// verifyHostName() didn't blowup - good!
return sslSocket;
}
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
if (remoteAddress == null)
throw new IllegalArgumentException("Remote address may not be null");
if (params == null)
throw new IllegalArgumentException("HTTP parameters may not be null");
final Socket sock = socket != null ? socket : getSSLContext().getSocketFactory().createSocket();
if (localAddress != null) {
sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
sock.bind(localAddress);
}
final int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
final int soTimeout = HttpConnectionParams.getSoTimeout(params);
try {
sock.setSoTimeout(soTimeout);
sock.connect(remoteAddress, connTimeout);
} catch (final SocketTimeoutException ex) {
throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
}
String hostname;
if (remoteAddress instanceof HttpInetSocketAddress) {
hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName();
} else {
hostname = remoteAddress.getHostName();
}
SSLSocket sslsock;
// Setup SSL layering if necessary
if (sock instanceof SSLSocket) {
sslsock = (SSLSocket) sock;
} else {
final int port = remoteAddress.getPort();
sslsock = (SSLSocket) getSSLContext().getSocketFactory().createSocket(sock, hostname, port, true);
}
return sslsock;
}
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
if (sock == null)
throw new IllegalArgumentException("Socket may not be null");
// This instanceof check is in line with createSocket() above.
if (!(sock instanceof SSLSocket))
throw new IllegalArgumentException("Socket not created by this factory");
// This check is performed last since it calls the argument object.
if (sock.isClosed())
throw new IllegalArgumentException("Socket is closed");
return true;
}
private static SSLContext createEasySSLContext() {
try {
final SSLContext context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);
return context;
} catch (final Exception e) {
LOG.error(e.getMessage(), e);
throw new HttpClientError(e.toString());
}
}
private SSLContext getSSLContext() {
if (this.sslcontext == null) {
this.sslcontext = createEasySSLContext();
}
return this.sslcontext;
}
}
public static final class TestHttpWebConnection extends HttpWebConnection {
public TestHttpWebConnection(final WebClient webClient) {
super(webClient);
final SchemeRegistry schemeRegistry = getHttpClient().getConnectionManager().getSchemeRegistry();
final SchemeSocketFactory socketFactory = new EasySSLSocketFactory();
schemeRegistry.register(new Scheme("https", 443, socketFactory));
}
}
}

Related

netty SimpleChannelInboundHandler<String> channelRead0 only occasionally invoked

I know that there are several similar questions that have either been answered or still outstanding, however, for the life of me...
Later Edit 2016-08-25 10:05 CST - Actually, I asked the wrong question.
The question is the following: given that I have both a netty server (taken from DiscardServer example) and a netty client - (see above) what must I do to force the DiscardServer to immediately send the client a request?
I have added an OutboundHandler to the server and to the client.
After looking at both the DiscardServer and PingPongServer examples, there is an external event occurring to kick off all the action. In the case of Discard server, it is originally waiting for a telnet connection, then will transmit whatever was in the telnet msg to the client.
In the case of PingPongServer, the SERVER is waiting on the client to initiate action.
What I want is for the Server to immediately start transmitting after connection with the client. None of the examples from netty seem to do this.
If I have missed something, and someone can point it out, much good karma.
My client:
public final class P4Listener {
static final Logger LOG;
static final String HOST;
static final int PORT;
static final Boolean SSL = Boolean.FALSE;
public static Dto DTO;
static {
LOG = LoggerFactory.getLogger(P4Listener.class);
HOST = P4ListenerProperties.getP4ServerAddress();
PORT = Integer.valueOf(P4ListenerProperties.getListenerPort());
DTO = new Dto();
}
public static String getId() { return DTO.getId(); }
public static void main(String[] args) throws Exception {
final SslContext sslCtx;
if (SSL) {
LOG.info("{} creating SslContext", getId());
sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.handler(new P4ListenerInitializer(sslCtx));
// Start the connection attempt.
LOG.debug(" {} starting connection attempt...", getId());
Channel ch = b.connect(HOST, PORT).sync().channel();
// ChannelFuture localWriteFuture = ch.writeAndFlush("ready\n");
// localWriteFuture.sync();
} finally {
group.shutdownGracefully();
}
}
}
public class P4ListenerHandler extends SimpleChannelInboundHandler<String> {
static final Logger LOG = LoggerFactory.getLogger(P4ListenerHandler.class);
static final DateTimeFormatter DTFormatter = DateTimeFormatter.ofPattern("yyyyMMdd-HHMMss.SSS");
static final String EndSOT;
static final String StartSOT;
static final String EOL = "\n";
static final ClassPathXmlApplicationContext AppContext;
static {
EndSOT = P4ListenerProperties.getEndSOT();
StartSOT = P4ListenerProperties.getStartSOT();
AppContext = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
}
private final RequestValidator rv = new RequestValidator();
private JAXBContext jaxbContext = null;
private Unmarshaller jaxbUnmarshaller = null;
private boolean initialized = false;
private Dto dto;
public P4ListenerHandler() {
dto = new Dto();
}
public Dto getDto() { return dto; }
public String getId() { return getDto().getId(); }
Message convertXmlToMessage(String xml) {
if (xml == null)
throw new IllegalArgumentException("xml message is null!");
try {
jaxbContext = JAXBContext.newInstance(p4.model.xml.request.Message.class, p4.model.xml.request.Header.class,
p4.model.xml.request.Claims.class, p4.model.xml.request.Insurance.class,
p4.model.xml.request.Body.class, p4.model.xml.request.Prescriber.class,
p4.model.xml.request.PriorAuthorization.class,
p4.model.xml.request.PriorAuthorizationSupportingDocumentation.class);
jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader strReader = new StringReader(xml);
Message m = (Message) jaxbUnmarshaller.unmarshal(strReader);
return m;
} catch (JAXBException jaxbe) {
String error = StacktraceUtil.getCustomStackTrace(jaxbe);
LOG.error(error);
throw new P4XMLUnmarshalException("Problems when attempting to unmarshal transmission string: \n" + xml,
jaxbe);
}
}
#Override
public void channelActive(ChannelHandlerContext ctx) {
LOG.debug("{} let server know we are ready", getId());
ctx.writeAndFlush("Ready...\n");
}
/**
* Important - this method will be renamed to
* <code><b>messageReceived(ChannelHandlerContext, I)</b></code> in netty 5.0
*
* #param ctx
* #param msg
*/
#Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
ChannelFuture lastWriteFuture = null;
LOG.debug("{} -- received message: {}", getId(), msg);
Channel channel = ctx.channel();
Message m = null;
try {
if (msg instanceof String && msg.length() > 0) {
m = convertXmlToMessage(msg);
m.setMessageStr(msg);
dto.setRequestMsg(m);
LOG.info("{}: received TIMESTAMP: {}", dto.getId(), LocalDateTime.now().format(DTFormatter));
LOG.debug("{}: received from server: {}", dto.getId(), msg);
/*
* theoretically we have a complete P4(XML) request
*/
final List<RequestFieldError> errorList = rv.validateMessage(m);
if (!errorList.isEmpty()) {
for (RequestFieldError fe : errorList) {
lastWriteFuture = channel.writeAndFlush(fe.toString().concat(EOL));
}
}
/*
* Create DBHandler with message, messageStr, clientIp to get
* dbResponse
*/
InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
InetAddress inetaddress = socketAddress.getAddress();
String clientIp = inetaddress.getHostAddress();
/*
* I know - bad form to ask the ApplicationContext for the
* bean... BUT ...lack of time turns angels into demons
*/
final P4DbRequestHandler dbHandler = (P4DbRequestHandler) AppContext.getBean("dbRequestHandler");
// must set the requestDTO for the dbHandler!
dbHandler.setClientIp(clientIp);
dbHandler.setRequestDTO(dto);
//
// build database request and receive response (string)
String dbResponse = dbHandler.submitDbRequest();
/*
* create ResponseHandler and get back response string
*/
P4ResponseHandler responseHandler = new P4ResponseHandler(dto, dbHandler);
String responseStr = responseHandler.decodeDbServiceResponse(dbResponse);
/*
* write response string to output and repeat exercise
*/
LOG.debug("{} -- response to be written back to server:\n {}", dto.getId(), responseStr);
lastWriteFuture = channel.writeAndFlush(responseStr.concat(EOL));
//
LOG.info("{}: response sent TIMESTAMP: {}", dto.getId(), LocalDateTime.now().format(DTFormatter));
} else {
throw new P4EventException(dto.getId() + " -- Message received is not a String");
}
processWriteFutures(lastWriteFuture);
} catch (Throwable t) {
String tError = StacktraceUtil.getCustomStackTrace(t);
LOG.error(tError);
} finally {
if (lastWriteFuture != null) {
lastWriteFuture.sync();
}
}
}
private void processWriteFutures(ChannelFuture writeFuture) throws InterruptedException {
// Wait until all messages are flushed before closing the channel.
if (writeFuture != null) {
writeFuture.sync();
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
/**
* Creates a newly configured {#link ChannelPipeline} for a new channel.
*/
public class P4ListenerInitializer extends ChannelInitializer<SocketChannel> {
private static final StringDecoder DECODER = new StringDecoder();
private static final StringEncoder ENCODER = new StringEncoder();
private final SslContext sslCtx;
public P4ListenerInitializer(SslContext sslCtx) {
this.sslCtx = sslCtx;
}
#Override
public void initChannel(SocketChannel ch) {
P4ListenerHandler lh = null;
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
P4Listener.LOG.info("{} -- constructing SslContext new handler ", P4Listener.getId());
pipeline.addLast(sslCtx.newHandler(ch.alloc(), P4Listener.HOST, P4Listener.PORT));
} else {
P4Listener.LOG.info("{} -- SslContext null; bypassing adding sslCtx.newHandler(ch.alloc(), P4Listener.HOST, P4Listener.PORT) ", P4Listener.getId());
}
// Add the text line codec combination first,
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(DECODER);
P4Listener.LOG.debug("{} -- added Decoder ", P4Listener.getId());
pipeline.addLast(ENCODER);
P4Listener.LOG.debug("{} -- added Encoder ", P4Listener.getId());
// and then business logic.
pipeline.addLast(lh = new P4ListenerHandler());
P4Listener.LOG.debug("{} -- added P4ListenerHandler: {} ", P4Listener.getId(), lh.getClass().getSimpleName());
}
}
#Sharable
public class P4ListenerOutboundHandler extends ChannelOutboundHandlerAdapter {
static final Logger LOG = LoggerFactory.getLogger(P4ListenerOutboundHandler.class);
private Dto outBoundDTO = new Dto();
public String getId() {return this.outBoundDTO.getId(); }
#Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
try {
ChannelFuture lastWrite = ctx.write(Unpooled.copiedBuffer((String) msg, CharsetUtil.UTF_8));
try {
if (lastWrite != null) {
lastWrite.sync();
promise.setSuccess();
}
} catch (InterruptedException e) {
promise.setFailure(e);
e.printStackTrace();
}
} finally {
ReferenceCountUtil.release(msg);
}
}
}
output from client
Just override channelActive(...) on the handler of the server and trigger a write there.

Background Service displays a timeout exception after some time in Android 6

This is a service running in the background, no Activity, began operating normally, but After about four hours, there will be a ConnectTimeoutException.
Connect to xxx.xxx.xxx.xxx time out.
This problem occurs in Android 6, I did not find this issue Android 4. When this problem occurs, I have to restart this phone, after which it connects properly for some time. When this problem occurs, other network applications on the phone runs properly.
public class mService extends Service{
Intent intent;
private Handler objHandlerCheckNetwork = new Handler();
private boolean mReflectFlg = false;
private static final int NOTIFICATION_ID = 101;
private static final Class<?>[] mSetForegroundSignature = new Class[] { boolean.class };
private static final Class<?>[] mStartForegroundSignature = new Class[] { int.class , Notification.class };
private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };
private NotificationManager mNM;
private Method mSetForeground;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mSetForegroundArgs = new Object[1];
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];
private Runnable mHttpTestRunnable = new Runnable() {
#Override
public void run() {
if (httpTest()){
Log.e(GlobalData.getClassMethodName(),"true");
}else{
Log.e(GlobalData.getClassMethodName(),"false");
}
}
};
private Runnable mTasksCheckNetwork = new Runnable()
{
public void run()
{
Thread httpTestThread = new Thread(mHttpTestRunnable);;
httpTestThread.start();
objHandlerCheckNetwork.postDelayed(mTasksCheckNetwork, 1000*30);
}
};
#SuppressLint("NewApi")
#Override
public void onCreate() {
super.onCreate();
mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE );
try {
mStartForeground = mService.class.getMethod("startForeground" , mStartForegroundSignature);
mStopForeground = mService.class.getMethod("stopForeground" , mStopForegroundSignature);
} catch (NoSuchMethodException e) {
mStartForeground = mStopForeground = null;
}
try {
mSetForeground = getClass().getMethod( "setForeground", mSetForegroundSignature);
} catch (NoSuchMethodException e) {
throw new IllegalStateException( "OS doesn't have Service.startForeground OR Service.setForeground!");
}
Intent intent = new Intent(this,UploadTableDataService.class );
intent.putExtra( "ficationId", NOTIFICATION_ID);
Notification.Builder builder = new Notification.Builder(this);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.gps);
builder.setContentTitle( "test" );
builder.setContentText( "test111" );
Notification notification = builder.getNotification();
startForegroundCompat( NOTIFICATION_ID, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
//startService( new Intent( this, WifiService. class));
//startService( new Intent( this, VoiceService. class));
this.intent = intent;
Log.e(GlobalData.getClassMethodName(),"mService start!");
objHandlerCheckNetwork.postDelayed(mTasksCheckNetwork, 1000);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
try{
objHandlerCheckNetwork.removeCallbacks(mTasksCheckNetwork);
}catch (Exception e) {
Log.d("DEBUG->", "onDestroy error - removeUpdates: ");
}
//stopForegroundCompat( NOTIFICATION_ID);
}
void invokeMethod(Method method, Object[] args) {
try {
method.invoke( this, args);
} catch (InvocationTargetException e) {
// Should not happen.
Log. w("ApiDemos" , "Unable to invoke method" , e);
} catch (IllegalAccessException e) {
// Should not happen.
Log. w("ApiDemos" , "Unable to invoke method" , e);
}
}
/**
* This is a wrapper around the new startForeground method, using the older
* APIs if it is not available.
*/
void startForegroundCompat( int id, Notification notification) {
if ( mReflectFlg) {
// If we have the new startForeground API, then use it.
if ( mStartForeground != null) {
mStartForegroundArgs[0] = Integer. valueOf(id);
mStartForegroundArgs[1] = notification;
invokeMethod( mStartForeground, mStartForegroundArgs);
return;
}
// Fall back on the old API.
mSetForegroundArgs[0] = Boolean. TRUE;
invokeMethod( mSetForeground, mSetForegroundArgs);
mNM.notify(id, notification);
} else {
if (Build.VERSION. SDK_INT >= 5) {
startForeground(id, notification);
} else {
// Fall back on the old API.
mSetForegroundArgs[0] = Boolean. TRUE;
invokeMethod( mSetForeground, mSetForegroundArgs);
mNM.notify(id, notification);
}
}
}
/**
* This is a wrapper around the new stopForeground method, using the older
* APIs if it is not available.
*/
void stopForegroundCompat( int id) {
if ( mReflectFlg) {
// If we have the new stopForeground API, then use it.
if ( mStopForeground != null) {
mStopForegroundArgs[0] = Boolean. TRUE;
invokeMethod( mStopForeground, mStopForegroundArgs);
return;
}
mNM.cancel(id);
mSetForegroundArgs[0] = Boolean. FALSE;
invokeMethod( mSetForeground, mSetForegroundArgs);
} else {
if (Build.VERSION. SDK_INT >= 5) {
stopForeground( true);
} else {
// Fall back on the old API. Note to cancel BEFORE changing the
// foreground state, since we could be killed at that point.
mNM.cancel(id);
mSetForegroundArgs[0] = Boolean. FALSE;
invokeMethod( mSetForeground, mSetForegroundArgs);
}
}
}
public static Boolean httpTest() {
HttpClient client= new DefaultHttpClient();;
try {
StringBuilder sb = new StringBuilder();
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 1000*5);
HttpConnectionParams.setSoTimeout(httpParams, 1000*10);
HttpResponse response = client.execute(new HttpGet("http://www.itnanny.com/default.htm"));
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
}
Log.e(GlobalData.getClassMethodName(),"result:"+sb.toString());
if (sb.toString().indexOf("ok") > -1){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
client.getConnectionManager().shutdown();;
}
return false;
}
}

Javafx Task for Bluetooth data reciever

I am creating javafx application where I have this case that I need to listen for data sent over Bluetooth.
I have one fxml window on which I need to initialize Bluetooth and start listening from data.
Following is my Code for fxml controller:
//all imports
public class NewBarcodeInvoicePaneController implements Initializable{
private BluetoothController bc;
public BluetoothController getBc() {
return bc;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
try {
bc = new BluetoothController();
new Thread(bc).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
And BluetoothController is task where I initialize bluettoth and listen to the data
public class BluetoothController extends Task<Void> {
#Override
protected Void call() throws Exception {
LocalDevice local = null;
StreamConnectionNotifier notifier;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice();
try {
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
}
UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
try {
System.err.println("THIS IS HAPENING");
connection = notifier.acceptAndOpen();
System.err.println("HAPENING???????????????????????????");
InputStream inputStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String lineRead = bReader.readLine();
connection.close();
inputStream.close();
notifier.close();
local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
JSONParser parser = new JSONParser();
Object obj = parser.parse(lineRead);
JSONArray array = (JSONArray) obj;
array.stream().map((o) -> (String) o).forEach((stringObj) -> {
System.out.println(stringObj);
});
System.out.println("AFTER DATA RECIEVED");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
}
It Works fine if I send data over bluetooth and blocking call to notifier.acceptAndOpen() is unblocked.
My problem is when we do not pass any data and I just want to close the window I opened..
It still have blocking call open with extra thread by the task.
I tried to cancel BluetoothController task in Main controller where I open this window like following
private void openNewBarcodeInvoicePane(ActionEvent ae) {
//following are custom classes to open windows from fxml and getting controller back for further manipulation
PostoryModalWindow modalWindow = new PostoryModalWindow();
modalWindow.openNewModalPaneWithParent("New Invoice", "fxml/newbarcodeinvoicepane.fxml", ae);
//getting controller object
NewBarcodeInvoicePaneController controller = (NewBarcodeInvoicePaneController) modalWindow.getDswFromController();
controller.getWindowStage().showAndWait();
BluetoothController bc = controller.getBc();
if(bc != null){
System.err.println("CANCELLING");
bc.cancel(true);
}
}
But it doesn't throw InterrupttedExeption (In which I might have Choice to close Bluetooth thread) and after research I found that waiting on Socket doesn't work on interrupt.
Any help on this?
Thanks
Got Solution After Some Research.
I just added new task to call notifier.acceptAndOpen();
And added method to close Bluetooth notifier.
public class BluetoothController extends Task<Void> {
private final ObservableList<Item> items = FXCollections.observableArrayList();
public ObservableList<Item> getItems() {
return items;
}
StreamConnectionNotifier notifier;
#Override
protected Void call() throws Exception {
try {
BluetoothConnectionTask bct = new BluetoothConnectionTask(items);
new Thread(bct).start();
Thread.sleep(2000);
notifier = bct.getNotifier();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public void cancelandExit() {
try {
if (notifier != null) {
notifier.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Here is new task for blocking call
public class BluetoothConnectionTask extends Task<Void>{
private StreamConnectionNotifier notifier;
private StreamConnection connection;
private ObservableList<Item> items = FXCollections.observableArrayList();
public StreamConnection getConnection() {
return connection;
}
public StreamConnectionNotifier getNotifier() {
return notifier;
}
public BluetoothConnectionTask(ObservableList<Item> is){
items = is;
}
#Override
protected Void call() throws Exception {
try {
LocalDevice local = LocalDevice.getLocalDevice();
try {
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
}
UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
connection = notifier.acceptAndOpen();
InputStream inputStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String lineRead = bReader.readLine();
connection.close();
inputStream.close();
notifier.close();
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
JSONParser parser = new JSONParser();
Object obj = parser.parse(lineRead);
JSONArray array = (JSONArray) obj;
ItemDAO idao = new ItemDAO();
array.stream().map((o) -> (String) o).forEach((stringObj) -> {
String barcode = (String) stringObj;
Item i = idao.getItemByBarCode(barcode);
System.err.println("Adding Item "+i.getName());
items.add(i);
});
System.out.println("AFTER DATA RECIEVED");
return null;
}
}
Now for cancelling closing my bluetooth thread I am calling cancelandExit() after window is closed.

Use apache httpclient as backend for jersey client base on PoolingHttpClientConnectionManager

i try to use apache httpclient as backend for jersey client to handle cookie automatically and here is my code
class ClientHelper {
public static HttpClientConnectionManager customConnectionManager() throws Exception {
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
System.out.println("========checkClientTrusted=========");
}
#Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
System.out.println("========checkServerTrusted==========");
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}}, new SecureRandom());
SSLConnectionSocketFactory
sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionSocketFactory)
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager phcc = new PoolingHttpClientConnectionManager(registry);
return phcc;
}
public static Client createClient() {
HttpClient apacheClient = null;
try {
apacheClient =
HttpClientBuilder.create().setConnectionManager(customConnectionManager()).build();
} catch (Exception e) {
e.printStackTrace();
}
Client client = new Client(new ApacheHttpClient4Handler(apacheClient,
new BasicCookieStore(),
true));
return client;
}
}
I try to use the apache httpclient as the backend of jersey client (in order to handle the cookie)
Then, I create a simple class to test client,
import com.sun.jersey.api.client.Client;
....
public class ApiTest {
private static Client client;
public String getAuth(String username, String passwd) {
Map<String, String> formParams = new HashMap<String, String>();
formParams.put("username", String.valueOf(username));
formParams.put("passwd", String.valueOf(passwd));
try {
String basePath = "https://xyzhost/login";
if (client == null) {
client = ClientHelper.createClient();
client.addFilter(new LoggingFilter(System.out));
}
WebResource webResource = client.resource(basePath);
ClientResponse response = webResource.type("application/x-www-form-urlencoded").accept("application/json")
.post(ClientResponse.class, processFormParams(formParams));
if (response != null) {
String authRes = response.getEntity(String.class);
response.close();
return authRes;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public String getSummary(){
try {
String basePath = "https://xyzhost/summary";
if (client == null) {
client = ClientHelper.createClient();
}
WebResource webResource = client
.resource(basePath);
ClientResponse response = webResource.type("application/x-www-form-urlencoded").accept("application/json")
.post(ClientResponse.class, processFormParams(formParams));
if (response != null) {
String serviceRes = response.getEntity(String.class);
response.close();
return serviceRes;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) throws ApiException {
String username = "testuser";
String passwd = "testpasswd";
AuthApi apiTest = new ApiTest();
String auth =apiTest.getAuth(username, passwd);
String reslut1 = apiTest.getSummary();
String result2 = apiTest.getSummary();
String result3 = apiTest.getSummary();
String result4 = apiTest.getSummary();
}
}
So, I use the same client to hit the service under the same host.
I can success get the response for "auth" and "result1" but the client stuck in "result2" in the following part
ClientResponse response = webResource.type("application/x-www-form-urlencoded").accept("application/json")
.post(ClientResponse.class, processFormParams(formParams));
I try to modify the following part:
PoolingHttpClientConnectionManager phcc= new PoolingHttpClientConnectionManager(registry);
phcc.setDefaultMaxPerRoute(10);
then, ApiTest works, won't stuck. I guess there is some issue about the connection, since by default, the max per route for poolingHttpClientConnectionManager is 2, so my ApiTest will stuck in the 3rd request. I think the connection has been release since I have consume the response entity ,
if (response != null) {
String serviceRes = response.getEntity(String.class);
response.close();
return serviceRes;
}
but it seems not work at all, the connection seems not released.
anyone can help ? Appreciate!
I get one solution: switch the version of jersey-client from 1.17 to 1.18 , then problem solved!
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18</version>
<scope>compile</scope>
</dependency>

Socket closed after a while

I have my socket closed or reset by peer after a while,I think garbage collection problem through its reader or writer.
Asynctask for handling responses:
#Override
protected Void doInBackground(Void... params) {
//Log.e("NEW LISTENER THREAD NAME", name);
//initializations
try{
clientSocket = new Socket();
//clientSocket.setTcpNoDelay(true);
clientSocket.connect(new InetSocketAddress(serverURL, dataServerPort));
requestSender = new PrintWriter(new PrintStream(clientSocket.getOutputStream(), true,"UTF-8"));
Sender.Init();
}catch(Exception e){
e.printStackTrace();
}
gsonObj = new GsonBuilder().create();//This the object that handels every comming response
finish = false;
try{
listener = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}catch (IOException e) {
Log.e("FROM CREATING LISTENER", "FROM CREATING LISTENER ========> ");
e.printStackTrace();
}
LOGGED_IN = StaticArea.getLoggedIn(cnt);
if(LOGGED_IN){
USER = StaticArea.getUserName(cnt);
Sender.ResumeUser();
/*********DELEGATING CONNECTING TO SERVER TO BE USED IN SERVICE*************/
Message connectionMsg = new Message();
connectionMsg.obj = Boolean.valueOf(true);
serviceHandler.handleMessage(connectionMsg);
/*********END DELEGATING CONNECTING TO SERVER*************/
}else{
/*********DELEGATING CONNECTING TO SERVER TO BE USED IN SERVICE*************/
Message connectionMsg = new Message();
connectionMsg.obj = Boolean.valueOf(false);
serviceHandler.handleMessage(connectionMsg);
/*********END DELEGATING CONNECTING TO SERVER*************/
}
GoOnline();
while(!finish){
try{
answerS = listener.readLine();
if(answerS != null )//to avoid any null response
if(answerS.contains(Response.MYRESPONSE){
if(MyService.theHandler != null){
Message msg = new Message();
msg.obj = answerS;
MyService.theHandler.sendMessage(msg);
The Sender class is class that has a static methods and uses my sockets output:
public class Sender {
private static Gson gsonObj;
public static void Init() {
gsonObj = new GsonBuilder().create();
}
public static void SendTestRequest(){
try{
Request req = new Request();
req.setR_TYPE(Request.TEST);
String reqString = gsonObj.toJson(req);
requestSender.println(reqString);
requestSender.flush();
}catch(Exception e){
}
}//end method