Example usage for java.util Timer schedule

List of usage examples for java.util Timer schedule

Introduction

In this page you can find the example usage for java.util Timer schedule.

Prototype

public void schedule(TimerTask task, Date time) 

Source Link

Document

Schedules the specified task for execution at the specified time.

Usage

From source file:sjizl.com.ChatActivityFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LayoutInflater factory = LayoutInflater.from(getActivity());
    View myView = factory.inflate(R.layout.activity_chat_fragment, null);

    if (CommonUtilities.isInternetAvailable(getActivity().getApplicationContext())) //returns true if internet available
    {/*ww  w.  j  av a  2 s .c om*/

        SharedPreferences sp = getActivity().getApplicationContext().getSharedPreferences("loginSaved",
                Context.MODE_PRIVATE);
        pid = sp.getString("pid", null);
        naam = sp.getString("naam", null);
        username = sp.getString("username", null);
        password = sp.getString("password", null);
        foto = sp.getString("foto", null);
        foto_num = sp.getString("foto_num", null);
        Bundle bundle = getActivity().getIntent().getExtras();

        Bundle args = getArguments();

        Log.i("args", args.toString());
        if (args != null && args.containsKey("pid_user")) {

            pid_user = args.getString("pid_user");
            user = args.getString("user");
            user_foto_num = args.getString("user_foto_num");
            user_foto = args.getString("user_foto");
        } else {

            pid_user = bundle.getString("pid_user");
            user = bundle.getString("user");
            user_foto_num = bundle.getString("user_foto_num");
            user_foto = bundle.getString("user_foto");

        }
        // Toast.makeText(getApplicationContext(), "pid_user"+pid_user, Toast.LENGTH_SHORT).show();

        if (user.equalsIgnoreCase(naam.toString())) {
            Toast.makeText(getActivity().getApplicationContext(), "You can't message yourself!",
                    Toast.LENGTH_SHORT).show();
            getActivity().finish();
        }

        AbsListViewBaseActivity.imageLoader
                .init(ImageLoaderConfiguration.createDefault(getActivity().getBaseContext()));

        getActivity().registerReceiver(mHandleMessageReceiver2, new IntentFilter(DISPLAY_MESSAGE_ACTION));

        imageLoader.loadImage("https://www.sjizl.com/fotos/" + user_foto_num + "/thumbs/" + user_foto + "",
                new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        d1 = new BitmapDrawable(getResources(), loadedImage);

                    }
                });

        imageLoader.loadImage("https://www.sjizl.com/fotos/" + foto_num + "/thumbs/" + foto + "",
                new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        d2 = new BitmapDrawable(getResources(), loadedImage);

                    }
                });

        smilbtn = (ImageView) myView.findViewById(R.id.smilbtn);
        listView = (ListView) myView.findViewById(android.R.id.list);
        underlayout = (LinearLayout) myView.findViewById(R.id.underlayout);
        smiles_layout = (LinearLayout) myView.findViewById(R.id.smiles);
        textView1_bgtext = (TextView) getActivity().findViewById(R.id.textView1_bgtext);
        textView1_bgtext.setText(user);
        imageView2_dashboard = (ImageView) getActivity().findViewById(R.id.imageView2_dashboard);
        imageView1_logo = (ImageView) getActivity().findViewById(R.id.imageView1_logo);
        imageView_bericht = (ImageView) getActivity().findViewById(R.id.imageView_bericht);
        textView2_under_title = (TextView) getActivity().findViewById(R.id.textView2_under_title);
        right_lin = (LinearLayout) getActivity().findViewById(R.id.right_lin);
        left_lin1 = (LinearLayout) getActivity().findViewById(R.id.left_lin1);
        left_lin3 = (LinearLayout) getActivity().findViewById(R.id.left_lin3);
        left_lin4 = (LinearLayout) getActivity().findViewById(R.id.left_lin4);
        middle_lin = (LinearLayout) getActivity().findViewById(R.id.middle_lin);
        smile_lin = (LinearLayout) myView.findViewById(R.id.smile_lin);
        ber_lin = (LinearLayout) myView.findViewById(R.id.ber_lin);
        progressBar_hole = (ProgressBar) getActivity().findViewById(R.id.progressBar_hole);
        progressBar_hole.setVisibility(View.INVISIBLE);
        imageLoader.displayImage("http://sjizl.com/fotos/" + user_foto_num + "/thumbs/" + user_foto,
                imageView2_dashboard, options);
        new UpdateChat().execute();
        mNewMessage = (EditText) myView.findViewById(R.id.newmsg);
        ber_lin = (LinearLayout) myView.findViewById(R.id.ber_lin);

        /*
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    
                    
                    
            imageLoader.loadImage("http://sjizl.com/fotos/"+user_foto_num+"/thumbs/"+user_foto, new SimpleImageLoadingListener() {
               @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        super.onLoadingComplete(imageUri, view, loadedImage);
                
        Bitmap LoadedImage2 = loadedImage;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
           if(loadedImage!=null){
        LoadedImage2 = CommonUtilities.fastblur16(loadedImage, 4,getApplicationContext());
           }
        }
                
        if (Build.VERSION.SDK_INT >= 16) {
                
           listView.setBackground(new BitmapDrawable(getApplicationContext().getResources(), LoadedImage2));
                
          } else {
                
             listView.setBackgroundDrawable(new BitmapDrawable(LoadedImage2));
          }
                
        }
        }
            );
        }
        */

        listView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                mScrollState = scrollState;
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
            }

        });
        listView.setLongClickable(true);
        registerForContextMenu(listView);

        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        viewPager_smiles = new ViewPager(getActivity());
        viewPager_smiles.setId(0x1000);
        LayoutParams layoutParams555 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams555.width = LayoutParams.MATCH_PARENT;
        layoutParams555.height = (metrics.heightPixels / 2);
        viewPager_smiles.setLayoutParams(layoutParams555);
        TabsPagerAdapter mAdapter = new TabsPagerAdapter(getActivity().getSupportFragmentManager(),
                mNewMessage);
        viewPager_smiles.setAdapter(mAdapter);
        LayoutInflater inflater2 = null;
        viewPager_smiles.setVisibility(View.VISIBLE);
        smiles_layout.addView(viewPager_smiles);
        smiles_layout.setVisibility(View.GONE);

        left_lin4.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Intent profile = new Intent(getActivity().getApplicationContext(),
                            ProfileActivityMain.class);
                    profile.putExtra("user", user);
                    profile.putExtra("user_foto", user_foto);
                    profile.putExtra("user_foto_num", user_foto_num);
                    profile.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(profile);
                }
                return false;
            }
        });
        middle_lin.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Intent profile = new Intent(getActivity().getApplicationContext(),
                            ProfileActivityMain.class);
                    profile.putExtra("user", user);
                    profile.putExtra("user_foto", user_foto);
                    profile.putExtra("user_foto_num", user_foto_num);
                    profile.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(profile);
                }
                return false;
            }
        });

        smile_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                opensmiles();
            }
        });

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent dashboard = new Intent(getActivity().getApplicationContext(), ProfileActivityMain.class);
                dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                dashboard.putExtra("user", ArrChatLines.get(position).getNaam());
                dashboard.putExtra("user_foto", foto);
                dashboard.putExtra("user_foto_num", foto_num);
                startActivity(dashboard);
            }
        });

        mNewMessage.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {

                    v.setFocusable(true);
                    v.setFocusableInTouchMode(true);

                    smiles_layout.setVisibility(View.GONE);
                    smilbtn.setImageResource(R.drawable.emoji_btn_normal);
                    return false;
                }
                return false;
            }
        });

        TextWatcher textWatcher = new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //after text changed
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                CommonUtilities
                        .startandsendwebsock("" + pid_user + " " + naam + " " + pid + " is typing to you ...");
            }

            @Override
            public void afterTextChanged(Editable s) {
                /*
                 AsyncHttpClient.getDefaultInstance().websocket("ws://sjizl.com:9300", "my-protocol", new WebSocketConnectCallback() {
                  @Override
                     public void onCompleted(Exception ex, WebSocket webSocket) {
                         if (ex != null) {
                   ex.printStackTrace();
                   return;
                         }
                         webSocket.send(""+pid_user+" "+naam+" "+pid+" is typing to you ...");
                                 
                         webSocket.close();
                     }
                 });
                 */
            }
        };

        mNewMessage.addTextChangedListener(textWatcher);

        ber_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableStringBuilder spanStr = (SpannableStringBuilder) mNewMessage.getText();
                Spanned cs = (Spanned) mNewMessage.getText();
                String a = Html.toHtml(spanStr);
                String text = mNewMessage.getText().toString();
                mNewMessage.setText("");
                mNewMessage.requestFocus();
                mybmp2 = "http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto;
                if (text.length() < 1) {
                } else {
                    addItem(foto, foto_num, "0", naam, text.toString(),
                            "http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto, "", a);
                }
            }
        });

        hideSoftKeyboard();

    } else {

        Intent dashboard = new Intent(getActivity().getApplicationContext(), NoInternetActivity.class);
        dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(dashboard);

        getActivity().finish();
    }
    mNewMessage.clearFocus();
    listView.requestFocus();

    final String wsuri = "ws://sjizl.com:9300";

    WebSocketConnection mConnection8 = new WebSocketConnection();

    if (mConnection8.isConnected()) {
        mConnection8.reconnect();

    } else {
        try {
            mConnection8.connect(wsuri, new WebSocketConnectionHandler() {

                @Override
                public void onOpen() {
                    Log.d("TAG", "Status: Connected to " + wsuri);

                }

                @Override
                public void onTextMessage(String payload) {

                    if (payload.contains("message send")) {
                        String[] parts = payload.split(" ");
                        String zender = parts[0];
                        String send_from = parts[1];
                        String send_name = parts[2];
                        String send_foto = parts[3];
                        String send_foto_num = parts[4];
                        String send_xxx = parts[5];

                        //      Toast.makeText(getApplication(), "" +   "\n zender: "+zender+"" +   "\n pid_user: "+pid_user+"" +"\n pid: "+pid+"" +
                        //         "\n send_from: "+send_from, 
                        //                  Toast.LENGTH_LONG).show();
                        if (zender.equalsIgnoreCase(pid) || zender.equalsIgnoreCase(pid_user)) {

                            if (send_from.equalsIgnoreCase(pid_user) || send_from.equalsIgnoreCase(pid)) {

                                //Toast.makeText(getApplication(), "uu",    Toast.LENGTH_LONG).show();

                                new UpdateChat().execute();

                            }
                        }

                    } else if (payload.contains("is typing to you")) {

                        String[] parts = payload.split(" ");
                        String part1 = parts[0]; // 004
                        is_typing_name = parts[1]; // 034556
                        if (is_typing_name.equalsIgnoreCase(user)) {

                            if (ArrChatLines.size() > 0) {
                                oldvalue = ArrChatLines.get(0).getLaatstOnline();

                            } else {
                                oldvalue = textView2_under_title.getText().toString();
                            }

                            Timer t = new Timer(false);
                            t.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    getActivity().runOnUiThread(new Runnable() {
                                        public void run() {
                                            textView2_under_title.setText("typing ...");
                                        }
                                    });
                                }
                            }, 2);

                            Timer t2 = new Timer(false);
                            t2.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    getActivity().runOnUiThread(new Runnable() {
                                        public void run() {
                                            textView2_under_title.setText(oldvalue);
                                        }
                                    });
                                }
                            }, 2000);
                        }

                    }
                    Log.d("TAG", "Got echo: " + payload);
                }

                @Override
                public void onClose(int code, String reason) {
                    Log.d("TAG", "Connection lost.");
                }
            });
        } catch (WebSocketException e) {
            Log.d("TAG", e.toString());
        }
    }
    return myView;

}

From source file:io.puzzlebox.bloom.ui.MakerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View v = inflater.inflate(R.layout.fragment_maker, container, false);

    //      requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    //      setContentView(R.layout.main);
    //      getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

    progressBarRange = (ProgressBar) v.findViewById(R.id.progressBarRange);
    ////      ShapeDrawable progressBarRangeDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null,null));
    //      ShapeDrawable progressBarRangeDrawable = new ShapeDrawable();
    ////      String progressBarRangeColor = "#FF00FF";
    //      String progressBarRangeColor = "#990099";
    //      progressBarRangeDrawable.getPaint().setColor(Color.parseColor(progressBarRangeColor));
    //      ClipDrawable progressRange = new ClipDrawable(progressBarRangeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
    //      progressBarRange.setProgressDrawable(progressRange);
    //      progressBarRange.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));

    //      progressBarRange.setMax(128 + 127);
    progressBarRange.setMax(bloomRangeMax);

    //      imageViewStatus = (ImageView) v.findViewById(R.id.imageViewStatus);

    servoSeekBar = (SeekBar) v.findViewById(R.id.ServoSeekBar);
    servoSeekBar.setEnabled(false);/*from  w w  w .j av  a2s.  com*/
    //      servoSeekBar.setMax(180);
    servoSeekBar.setMax(100);
    servoSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            byte[] buf = new byte[] { (byte) 0x03, (byte) 0x00, (byte) 0x00 };

            buf[1] = (byte) servoSeekBar.getProgress();

            BloomSingleton.getInstance().characteristicTx.setValue(buf);
            BloomSingleton.getInstance().mBluetoothLeService
                    .writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
        }
    });

    //      rssiValue = (TextView) v.findViewById(R.id.rssiValue);

    connectBloom = (Button) v.findViewById(R.id.connectBloom);

    connectBloom.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                if (!BloomSingleton.getInstance().scanFlag) {
                    scanLeDevice();

                    Timer mTimer = new Timer();
                    mTimer.schedule(new TimerTask() {

                        @Override
                        public void run() {
                            if ((BloomSingleton.getInstance().mDevice != null)
                                    && (BloomSingleton.getInstance().mDevice.getAddress() != null)
                                    && (BloomSingleton.getInstance().mBluetoothLeService != null)) {
                                BloomSingleton
                                        .getInstance().mDeviceAddress = BloomSingleton.getInstance().mDevice
                                                .getAddress();
                                if (BloomSingleton.getInstance().mDeviceAddress != null)
                                    BloomSingleton.getInstance().mBluetoothLeService
                                            .connect(BloomSingleton.getInstance().mDeviceAddress);
                                else {
                                    Toast toast = Toast.makeText(getActivity(),
                                            "Error connecting to Puzzlebox Bloom", Toast.LENGTH_SHORT);
                                    toast.setGravity(0, 0, Gravity.CENTER | Gravity.BOTTOM);
                                    toast.show();
                                }
                                BloomSingleton.getInstance().scanFlag = true;
                            } else {
                                getActivity().runOnUiThread(new Runnable() {
                                    public void run() {
                                        Toast toast = Toast.makeText(getActivity(),
                                                "Error connecting to Puzzlebox Bloom", Toast.LENGTH_SHORT);
                                        toast.setGravity(0, 0, Gravity.CENTER | Gravity.BOTTOM);
                                        toast.show();
                                    }
                                });
                            }
                        }
                    }, BloomSingleton.getInstance().SCAN_PERIOD);
                }
            } catch (Exception e) {
                Log.e(TAG, "Exception connecting to Bloom: " + e);
                Toast toast = Toast.makeText(getActivity(), "Exception connecting to Puzzlebox Bloom",
                        Toast.LENGTH_SHORT);
                toast.setGravity(0, 0, Gravity.CENTER | Gravity.BOTTOM);
                toast.show();
            }

            System.out.println(BloomSingleton.getInstance().connState);
            //            Log.e(TAG, connState);
            //            if (connState == false) {
            if (!BloomSingleton.getInstance().connState
                    && BloomSingleton.getInstance().mDeviceAddress != null) {
                BloomSingleton.getInstance().mBluetoothLeService
                        .connect(BloomSingleton.getInstance().mDeviceAddress);
            } else {
                if (BloomSingleton.getInstance().mBluetoothLeService != null) {
                    setBloomRGBOff();
                    BloomSingleton.getInstance().mBluetoothLeService.disconnect();
                    BloomSingleton.getInstance().mBluetoothLeService.close();
                    setButtonDisable();
                }
            }
        }
    });

    redSeekBar = (SeekBar) v.findViewById(R.id.seekBarRed);
    redSeekBar.setEnabled(false);
    redSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            bloomColorRed = redSeekBar.getProgress();

            byte[] buf = new byte[] { (byte) 0x0A, (byte) 0x00, (byte) bloomColorRed };

            BloomSingleton.getInstance().characteristicTx.setValue(buf);
            BloomSingleton.getInstance().mBluetoothLeService
                    .writeCharacteristic(BloomSingleton.getInstance().characteristicTx);

        }
    });

    greenSeekBar = (SeekBar) v.findViewById(R.id.seekBarGreen);
    greenSeekBar.setEnabled(false);
    greenSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            bloomColorGreen = greenSeekBar.getProgress();

            byte[] buf = new byte[] { (byte) 0x0A, (byte) 0x01, (byte) bloomColorGreen };

            BloomSingleton.getInstance().characteristicTx.setValue(buf);
            BloomSingleton.getInstance().mBluetoothLeService
                    .writeCharacteristic(BloomSingleton.getInstance().characteristicTx);

        }
    });

    blueSeekBar = (SeekBar) v.findViewById(R.id.seekBarBlue);
    blueSeekBar.setEnabled(false);
    blueSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            bloomColorBlue = blueSeekBar.getProgress();

            byte[] buf = new byte[] { (byte) 0x0A, (byte) 0x02, (byte) bloomColorBlue };

            BloomSingleton.getInstance().characteristicTx.setValue(buf);
            BloomSingleton.getInstance().mBluetoothLeService
                    .writeCharacteristic(BloomSingleton.getInstance().characteristicTx);

        }
    });

    buttonOpen = (Button) v.findViewById(R.id.buttonOpen);
    buttonOpen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            byte[] buf = new byte[] { (byte) 0x01, (byte) 0x00, (byte) 0x00 };
            BloomSingleton.getInstance().characteristicTx.setValue(buf);
            BloomSingleton.getInstance().mBluetoothLeService
                    .writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
        }
    });

    buttonClose = (Button) v.findViewById(R.id.buttonClose);
    buttonClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            byte[] buf = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00 };
            BloomSingleton.getInstance().characteristicTx.setValue(buf);
            BloomSingleton.getInstance().mBluetoothLeService
                    .writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
        }
    });

    buttonCycleServo = (Button) v.findViewById(R.id.buttonDemoServo);
    buttonCycleServo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            byte[] buf = new byte[] { (byte) 0x03, (byte) 0x00, (byte) 0x00 }; // Cycle
            //            byte[] buf = new byte[] { (byte) 0x04, (byte) 0x00, (byte) 0x00 }; // CycleSlow
            BloomSingleton.getInstance().characteristicTx.setValue(buf);
            BloomSingleton.getInstance().mBluetoothLeService
                    .writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
        }
    });

    buttonCycleRGB = (Button) v.findViewById(R.id.buttonDemoRGB);
    buttonCycleRGB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            byte[] buf = new byte[] { (byte) 0x06, (byte) 0x00, (byte) 0x00 };
            BloomSingleton.getInstance().characteristicTx.setValue(buf);
            BloomSingleton.getInstance().mBluetoothLeService
                    .writeCharacteristic(BloomSingleton.getInstance().characteristicTx);

            updateBloomRGB();

        }
    });

    buttonDemo = (Button) v.findViewById(R.id.buttonDemo);
    buttonDemo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            byte[] buf = new byte[] { (byte) 0x05, (byte) 0x00, (byte) 0x00 };
            BloomSingleton.getInstance().characteristicTx.setValue(buf);
            BloomSingleton.getInstance().mBluetoothLeService
                    .writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
        }
    });

    //      buttonDemo = (Button) v.findViewById(R.id.buttonDemo);
    //      buttonDemo.setOnClickListener(new View.OnClickListener() {
    //         @Override
    //         public void onClick(View v) {
    //            byte[] buf;
    ////            if (! BloomSingleton.getInstance().demoActive) {
    //            BloomSingleton.getInstance().demoActive = true;
    //
    //            // bloomOpen()
    ////            buf = new byte[]{(byte) 0x01, (byte) 0x00, (byte) 0x00};
    ////            BloomSingleton.getInstance().characteristicTx.setValue(buf);
    ////            BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //
    //            // loopRGB()
    //            buf = new byte[]{(byte) 0x06, (byte) 0x00, (byte) 0x00};
    //            BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //            BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //
    //            // Set Red to 0
    //            buf = new byte[]{(byte) 0x0A, (byte) 0x00, (byte) 0x00}; // R = 0
    //            BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //            BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //
    //            // bloomClose()
    ////            buf = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00};
    ////            BloomSingleton.getInstance().characteristicTx.setValue(buf);
    ////            BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //
    //
    ////            } else {
    ////               BloomSingleton.getInstance().demoActive = false;
    //////               buf = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00};
    //////               BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //////               BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    ////               buf = new byte[]{(byte) 0x0A, (byte) 0x00, (byte) 0x00}; // R = 0
    ////               BloomSingleton.getInstance().characteristicTx.setValue(buf);
    ////               BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //////               buf = new byte[]{(byte) 0x0A, (byte) 0x01, (byte) 0x00}; // G = 0
    //////               BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //////               BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //////               buf = new byte[]{(byte) 0x0A, (byte) 0x02, (byte) 0x00}; // B = 0
    //////               BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //////               BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    ////            }
    //         }
    //      });

    if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(getActivity(), "Bluetooth LE not supported", Toast.LENGTH_SHORT).show();
        getActivity().finish();
    }

    final BluetoothManager mBluetoothManager = (BluetoothManager) getActivity()
            .getSystemService(Context.BLUETOOTH_SERVICE);
    BloomSingleton.getInstance().mBluetoothAdapter = mBluetoothManager.getAdapter();
    if (BloomSingleton.getInstance().mBluetoothAdapter == null) {
        Toast.makeText(getActivity(), "Bluetooth LE not supported", Toast.LENGTH_SHORT).show();
        getActivity().finish();
        return v;
    }

    Intent gattServiceIntent = new Intent(getActivity(), RBLService.class);
    //      bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    getActivity().bindService(gattServiceIntent, mServiceConnection, getActivity().BIND_AUTO_CREATE);

    /**
     * Update settings according to default UI
     */

    updateScreenLayout();

    //      updatePowerThresholds();
    //      updatePower();

    if (BloomSingleton.getInstance().connState) {
        setButtonEnable();
        updateBloomRGB();
    }

    return v;

}

From source file:com.csipsimple.ui.incall.CallActivity.java

private void sendCallConnectedBroadcast(boolean isIncoming, String calleeContact) {
    Log.i(TAG, "sendCallConnectedBroadcast");

    MakeCallService.CALLEE_NAME = "";
    Intent intent = new Intent();
    intent.putExtra(ApiConstants.API_RESPONSE_TYPE_INTENT_KEY, ApiConstants.API_RESPONSE_TYPE_CALL_CONNECTED);
    intent.putExtra(ApiConstants.IS_CALL_INCOMING_INTENT_KEY, isIncoming);
    intent.putExtra(ApiConstants.CALL_CONNECTED_CALLEE_INTENT_KEY, calleeContact);
    intent.setAction(ApiConstants.API_RESPONSE_BROADCAST_ACTION);
    Timer timer = new Timer();

    // wait for two seconds, then check if the call is still active
    // otherwise, we consider it as not connected
    timer.schedule(new SendConnectedTask(intent), 2000);
}

From source file:com.irets.datadownloader.SearchPropertyServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
    long reqInputArrivalTime = System.currentTimeMillis();
    Date resultdate = new Date(reqInputArrivalTime);
    System.out.println("Calling Me @:" + sdf.format(resultdate) + ", from: " + request.getRemoteAddr()
            + ", with url> " + request.getRequestURL() + "?" + request.getQueryString());

    long startTime = reqInputArrivalTime;

    WebApplicationContext wac = WebApplicationContextUtils
            .getRequiredWebApplicationContext(getServletContext());
    SearchService propServices = this.getSearchService(wac);
    propServices.setContextPath(this.getUrl3(request));
    //propServices.setServer(this.getServer(request));
    Filter filer = new Filter();
    ArrayList<FilterItem> filterItemArrayList = new ArrayList<FilterItem>(1);
    ArrayList<FilterItem> exactFilterItemArrayList = new ArrayList<FilterItem>(1);
    ArrayList<FilterItem> multipleFilterItemArrayList = new ArrayList<FilterItem>(1);
    ArrayList<String> keywordArrayList = new ArrayList<String>(1);
    Vector<SimpleRange> rangeVector = new Vector<SimpleRange>(1);
    GeoParameter geoParam = null;/*  ww  w  .j a  va2  s.  com*/
    //        SimpleRange aRange = new SimpleRange("price_list",null,50000);
    //        filer.setRanges(new SimpleRange[]{aRange});
    int start = 0;
    int limit = -1;
    //        if(request.getParameter("ListingId") != null){
    //           FilterItem filterItem = new FilterItem();
    //            filterItem.setField("number_MLS");
    //            filterItem.setValue(request.getParameter("ListingId"));
    //            filterItemArrayList.add(filterItem);
    //        }
    if (request.getParameter("ListPrice") != null) {
        SimpleRange aRange;
        String listPrice = request.getParameter("ListPrice");
        System.out.println("List price is " + listPrice);
        String min = "";
        String max = "";
        if (!listPrice.equalsIgnoreCase("No Min-No Max")) {
            if (listPrice.indexOf(":") != -1) {
                //                 System.out.println("listPrice : -->>"+listPrice);
                min = listPrice.substring(0, listPrice.indexOf(":"));
                max = listPrice.substring(listPrice.indexOf(":") + 1, listPrice.length());
                aRange = new SimpleRange("price_list", min, max);
            } else if (listPrice.endsWith("+")) {
                //                 System.out.println("listPrice +-->>"+listPrice);
                min = listPrice.substring(0, listPrice.indexOf("+"));
                aRange = new SimpleRange("price_list", min, null);
            } else if (listPrice.endsWith("-")) {
                //                 System.out.println("listPrice - -->>"+listPrice);
                max = listPrice.substring(0, listPrice.indexOf("-"));
                aRange = new SimpleRange("price_list", null, max);
            } else if (listPrice.length() > 0) { // Exact match....
                min = listPrice.substring(0, listPrice.length());
                max = min;
                aRange = new SimpleRange("price_list", min, max);
            } else {
                aRange = new SimpleRange("price_list", null, null);
            }

            rangeVector.add(aRange);
        }
    }

    if (request.getParameter("Bedrooms") != null) {
        SimpleRange aRange;
        String bedrooms = request.getParameter("Bedrooms");
        String min = "";
        String max = "";
        if (!bedrooms.equalsIgnoreCase("No Min-No Max")) {
            if (bedrooms.indexOf(":") != -1) {
                //                 System.out.println("Bedrooms: -->>"+bedrooms);
                min = bedrooms.substring(0, bedrooms.indexOf(":"));
                max = bedrooms.substring(bedrooms.indexOf(":") + 1, bedrooms.length());
                aRange = new SimpleRange("number_beds_Total", min, max);
            } else if (bedrooms.endsWith("+")) {
                //                 System.out.println("Bedrooms+ -->>"+bedrooms);
                min = bedrooms.substring(0, bedrooms.indexOf("+"));
                aRange = new SimpleRange("number_beds_Total", min, null);
            } else if (bedrooms.endsWith("-")) {
                //                 System.out.println("Bedrooms- -->>"+bedrooms);
                max = bedrooms.substring(0, bedrooms.indexOf("-"));
                aRange = new SimpleRange("number_beds_Total", null, max);
            } else if (bedrooms.length() > 0) { // Exact match....
                min = bedrooms.substring(0, bedrooms.length());
                max = min;
                aRange = new SimpleRange("number_beds_Total", min, max);
            } else {
                aRange = new SimpleRange("number_beds_Total", null, null);
            }
            rangeVector.add(aRange);
        }
    }
    if (request.getParameter("FullBathrooms") != null) {
        SimpleRange aRange;
        String fullBath = request.getParameter("FullBathrooms");
        String min = "";
        String max = "";
        if (!fullBath.equalsIgnoreCase("No Min-No Max")) {
            if (fullBath.indexOf(":") != -1) {
                //                 System.out.println("FullBathrooms: -->>"+fullBath);
                min = fullBath.substring(0, fullBath.indexOf(":"));
                max = fullBath.substring(fullBath.indexOf(":") + 1, fullBath.length());
                aRange = new SimpleRange("number_baths_Full", min, max);
            } else if (fullBath.endsWith("+")) {
                //                 System.out.println("FullBathrooms+ -->>"+fullBath);
                min = fullBath.substring(0, fullBath.indexOf("+"));
                aRange = new SimpleRange("number_baths_Full", min, null);
            } else if (fullBath.endsWith("-")) {
                //                 System.out.println("FullBathrooms- -->>"+fullBath);
                max = fullBath.substring(0, fullBath.indexOf("-"));
                aRange = new SimpleRange("number_baths_Full", null, max);
            } else if (fullBath.length() > 0) {
                min = fullBath.substring(0, fullBath.length());
                max = min;
                aRange = new SimpleRange("number_baths_Full", min, max);
            } else {
                aRange = new SimpleRange("number_baths_Full", null, null);
            }
            rangeVector.add(aRange);
        }
    }

    if (request.getParameter("SqFt") != null) {
        SimpleRange aRange;
        String sqFt = request.getParameter("SqFt");
        String min = "";
        String max = "";
        if (!sqFt.equalsIgnoreCase("No Min-No Max")) {
            if (sqFt.indexOf(":") != -1) {
                //                 System.out.println("SqFt: -->>"+sqFt);
                min = sqFt.substring(0, sqFt.indexOf(":"));
                max = sqFt.substring(sqFt.indexOf(":") + 1, sqFt.length());
                aRange = new SimpleRange("sqft_Structure", min, max);
            } else if (sqFt.endsWith("+")) {
                //                 System.out.println("SqFt+ -->>"+sqFt);
                min = sqFt.substring(0, sqFt.indexOf("+"));
                aRange = new SimpleRange("sqft_Structure", min, null);
            } else if (sqFt.endsWith("-")) {
                //                 System.out.println("SqFt- -->>"+sqFt);
                max = sqFt.substring(0, sqFt.indexOf("-"));
                aRange = new SimpleRange("sqft_Structure", null, max);
            } else if (sqFt.length() > 0) {
                min = sqFt.substring(0, sqFt.length());
                max = min;
                aRange = new SimpleRange("sqft_Structure", min, max);
            } else {
                aRange = new SimpleRange("sqft_Structure", null, null);
            }
            rangeVector.add(aRange);
        }
    }

    // Date range for the property.
    if (request.getParameter("Age") != null) {
        SimpleRange aRange;
        String age = request.getParameter("Age");
        String min = "";
        String max = "";
        if (!age.equalsIgnoreCase("No Min-No Max")) {
            if (age.indexOf(":") != -1) {
                System.out.println("age: -->>" + age);
                min = age.substring(0, age.indexOf(":"));
                max = age.substring(age.indexOf(":") + 1, age.length());
                aRange = new SimpleRange("date_Listing_Modification", min, max);
            } else if (age.endsWith("+")) {
                //                 System.out.println("SqFt+ -->>"+sqFt);
                min = age.substring(0, age.indexOf("+"));
                aRange = new SimpleRange("date_Listing_Modification", min, null);
            } else if (age.endsWith("-")) {
                //                 System.out.println("SqFt- -->>"+sqFt);
                max = age.substring(0, age.indexOf("-"));
                aRange = new SimpleRange("date_Listing_Modification", null, max);
            } else if (age.length() > 0) {
                min = age.substring(0, age.length());
                max = min;
                aRange = new SimpleRange("date_Listing_Modification", min, max);
            } else {
                aRange = new SimpleRange("date_Listing_Modification", null, null);
            }
            System.out.println("Range is " + aRange.getMinValue() + ", " + aRange.getMaxValue());
            rangeVector.add(aRange);
        }
    }

    // Range for Longitude
    if (request.getParameter("Longitude") != null) {
        SimpleRange aRange;
        String longitude = request.getParameter("Longitude");
        System.out.println("Longitude is " + longitude);
        String min = "";
        String max = "";
        if (longitude.indexOf(":") != -1) {
            min = longitude.substring(0, longitude.indexOf(":"));
            max = longitude.substring(longitude.indexOf(":") + 1, longitude.length());
            aRange = new SimpleRange("_long", min, max);
        } else {
            aRange = new SimpleRange("_long", null, null);
        }
        rangeVector.add(aRange);
    }

    // Range for Latitude
    if (request.getParameter("Latitude") != null) {
        SimpleRange aRange;
        String latitude = request.getParameter("Latitude");
        System.out.println("Latitude is " + latitude);
        String min = "";
        String max = "";
        if (latitude.indexOf(":") != -1) {
            min = latitude.substring(0, latitude.indexOf(":"));
            max = latitude.substring(latitude.indexOf(":") + 1, latitude.length());
            aRange = new SimpleRange("lat", min, max);
        } else {
            aRange = new SimpleRange("lat", null, null);
        }
        rangeVector.add(aRange);
    }

    // Near by homes
    // Format required is Latitude,Longitude,distance
    if (request.getParameter("NBH") != null) {
        String nbh = request.getParameter("NBH");
        String[] s = nbh.split(",");
        if (s.length == 3) {
            Float f = Float.valueOf(s[2]);
            if (f >= 10) // 10 miles radius max
                s[2] = "10";
            else if (f < 0) // if negative distance
                s[2] = "1";
            geoParam = new GeoParameter(s[0], s[1], s[2]);
        }
    } else {
        // City and Zip are optional if NBH is provided.
        if (request.getParameter("Zip") != null) {
            FilterItem filterItem = new FilterItem();
            filterItem.setField("zipCode");
            // remove the space first
            String inZipcode = request.getParameter("Zip");
            StringBuffer zipBuffer = new StringBuffer();
            if (inZipcode.indexOf(",") > -1) {
                StringTokenizer sToken = new StringTokenizer(inZipcode, ",");
                while (sToken.hasMoreElements()) {
                    String object = (String) sToken.nextElement();
                    zipBuffer.append("'");
                    zipBuffer.append(object);
                    zipBuffer.append("'");
                    if (sToken.countTokens() > 0)
                        zipBuffer.append(",");
                }
            } else {
                zipBuffer.append("'");
                zipBuffer.append(inZipcode);
                zipBuffer.append("'");
            }

            //System.out.println(zipBuffer.toString());
            filterItem.setValue(zipBuffer.toString());
            multipleFilterItemArrayList.add(filterItem);

        }

        if (request.getParameter("City") != null) {
            FilterItem filterItem = new FilterItem();
            filterItem.setField("name_City");

            String cityList = request.getParameter("City");
            StringBuffer cityMod = new StringBuffer();
            if (cityList.indexOf(",") > -1) {
                StringTokenizer sToken = new StringTokenizer(cityList, ",");
                while (sToken.hasMoreElements()) {
                    String object = (String) sToken.nextElement();
                    cityMod.append("'");
                    cityMod.append(getCity(object));
                    cityMod.append("'");
                    if (sToken.countTokens() > 0)
                        cityMod.append(",");
                }
            } else {
                cityMod.append("'");
                cityMod.append(getCity(cityList));
                cityMod.append("'");
            }

            filterItem.setValue(cityMod.toString());
            multipleFilterItemArrayList.add(filterItem);
        }
    }

    // Status of property, link Active or Pending
    // For backward compatibility, Status=A. we added extra checks
    // for Status=ACTIVE or PENDING
    /*
     * if(request.getParameter("Status") != null &&
      (request.getParameter("Status").equalsIgnoreCase("ACTIVE")||
      request.getParameter("Status").equalsIgnoreCase("PENDING"))){
       FilterItem filterItem = new FilterItem();
    filterItem.setField("status_Listing");
    filterItem.setValue(request.getParameter("Status"));
    if (request.getParameter("Status").equalsIgnoreCase("PENDING")){
       filterItem.setValue(propServices.getPendingStatus());
    }           
    filterItemArrayList.add(filterItem);
    }
    */
    if (request.getParameter("Status") != null && (request.getParameter("Status").equalsIgnoreCase("ACTIVE")
            || request.getParameter("Status").equalsIgnoreCase("PENDING"))) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("status_Listing");
        StringBuffer statusMod = new StringBuffer();
        String statusList = null;
        if (request.getParameter("Status").equalsIgnoreCase("ACTIVE")) {
            statusList = propServices.getActiveStatus();
        } else if (request.getParameter("Status").equalsIgnoreCase("PENDING")) {
            statusList = propServices.getPendingStatus();
        }
        if (statusList.indexOf(",") > -1) {
            StringTokenizer sToken = new StringTokenizer(statusList, ",");
            while (sToken.hasMoreElements()) {
                String object = (String) sToken.nextElement();
                statusMod.append("'");
                statusMod.append(object);
                statusMod.append("'");
                if (sToken.countTokens() > 0)
                    statusMod.append(",");
            }
        } else {
            statusMod.append("'");
            statusMod.append(statusList);
            statusMod.append("'");
        }
        System.out.println("Status query..: " + statusMod.toString());
        filterItem.setValue(statusMod.toString());
        multipleFilterItemArrayList.add(filterItem);
    }

    if (request.getParameter("ListingId") != null) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("number_MLS");
        String listingId = request.getParameter("ListingId");
        String mlsNumberPrefix = propServices.getMlsNumberPrefix();
        StringBuffer listingIdList = new StringBuffer();
        if (listingId.indexOf(",") > -1) {
            StringTokenizer sToken = new StringTokenizer(listingId, ",");
            while (sToken.hasMoreElements()) {
                String object = (String) sToken.nextElement();
                if ((mlsNumberPrefix != null) && (!mlsNumberPrefix.equals(""))
                        && (!object.contains(mlsNumberPrefix))) {
                    listingIdList.append("'" + mlsNumberPrefix);
                } else {
                    listingIdList.append("'");
                }
                listingIdList.append(object);
                listingIdList.append("'");
                if (sToken.countTokens() > 0)
                    listingIdList.append(",");
            }
        } else {
            if ((mlsNumberPrefix != null) && (!mlsNumberPrefix.equals(""))
                    && (!listingId.contains(mlsNumberPrefix)))
                listingIdList.append("'" + mlsNumberPrefix);
            else
                listingIdList.append("'");
            listingIdList.append(listingId);
            listingIdList.append("'");
        }

        filterItem.setValue(listingIdList.toString());
        multipleFilterItemArrayList.add(filterItem);
        //System.out.println("got listing id "+ request.getParameter("ListingId"));
    }

    if (request.getParameter("ListingAgentLic") != null) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("listing_license_number");
        String listingId = request.getParameter("ListingAgentLic");

        if (listingId.indexOf(",") > -1) {
            StringTokenizer sToken = new StringTokenizer(listingId, ",");
            while (sToken.hasMoreElements()) {
                keywordArrayList.add((String) sToken.nextElement());
            }
        } else {
            keywordArrayList.add(listingId);
        }
        //System.out.println("got listing agent lic "+ request.getParameter("ListingAgentLic"));

    }

    if (request.getParameter("offset") != null) {
        start = Integer.parseInt(request.getParameter("offset"));
    }
    if (request.getParameter("limit") != null) {
        limit = Integer.parseInt(request.getParameter("limit"));
    }
    String sort = request.getParameter("sort");
    if (sort != null) {
        if (sort.equalsIgnoreCase("City")) {
            sort = "name_City";
        } else if (sort.equalsIgnoreCase("YearBuilt")) {
            sort = "year_Built";
        } else if (sort.equalsIgnoreCase("ListPrice")) {
            sort = "price_List";
        } else if (sort.equalsIgnoreCase("Sqft")) {
            sort = "sqft_Structure";
        } else if (sort.equalsIgnoreCase("LotSqFt")) {
            sort = "Size_Lot";
        } else if (sort.equalsIgnoreCase("Type")) {
            sort = "";
        } else if (sort.equalsIgnoreCase("Bedrooms")) {
            sort = "number_beds_Total";
        } else if (sort.equalsIgnoreCase("FullBathrooms")) {
            sort = "number_baths_Full";
        } else if (sort.equalsIgnoreCase("ExteriorFeatures")) {
            sort = "type_Property";
        } else if (sort.equalsIgnoreCase("none")) {
            sort = null;
        }
    }

    String sort_direction = request.getParameter("sort_direction");
    if (sort_direction != null) {
        if (sort_direction.equalsIgnoreCase("none")) {
            sort_direction = null;
        } else if (sort_direction.equalsIgnoreCase("ASC")) {
            sort_direction = "asc";
        } else {
            sort_direction = "desc";
        }

    } else { //{TOD: why do we need this??
        if (request.getParameter("ListingAgentLic") != null) {
            sort = "price_List";
            sort_direction = "desc"; // with agent listing, they want desc
        } else {
            sort_direction = "asc"; // default sorting order
        }

    }

    // Type of property, link Single Family, Townhouse, Condominium
    if (request.getParameter("ExteriorFeatures") != null) {
        String param = request.getParameter("ExteriorFeatures");
        FilterItem filterItem = new FilterItem();
        filterItem.setField("type_Property");
        List<ExteriorFeaturesData> extFeatureData = propServices.getExtFeaturesData();
        // Getting ExFeatures list from properties files
        if (extFeatureData != null) {
            System.out.println("Exterior Features param is " + param);
            for (ExteriorFeaturesData efd : extFeatureData) {
                if (efd.getName().equalsIgnoreCase(param)) {
                    filterItem.setValue(efd.getInSearchFields());
                    break;
                }
            }
            if (filterItem.getValue() != null) {
                System.out.println("Exterior Features value " + filterItem.getValue());
                multipleFilterItemArrayList.add(filterItem);
            }
        } else {// Getting ExFeatures list from DB                        
            filterItem.setValue(param);
            System.out.println("Exterior Features (single) " + filterItem.getValue());
            filterItemArrayList.add(filterItem);
        }

    }

    // Adding the search parameter for Full Address
    if (request.getParameter("FullAddress") != null) {
        FilterItem filterItem = new FilterItem();
        filterItem.setField("address_Filtered");
        filterItem.setValue(request.getParameter("FullAddress"));
        filterItemArrayList.add(filterItem);
    }

    boolean returnOpenHouseData = false;
    if (request.getParameter("OpenHouse") != null) {
        if (request.getParameter("OpenHouse").equals("1")) {
            returnOpenHouseData = true;
        }
    }

    // Put the keyword search (using it for license id)
    String[] filterArrayKeyword = new String[keywordArrayList.size()];
    filterArrayKeyword = keywordArrayList.toArray(filterArrayKeyword);
    filer.setKeywords(filterArrayKeyword);

    // Put range in the filter
    SimpleRange[] sRangeArray = new SimpleRange[rangeVector.size()];
    sRangeArray = rangeVector.toArray(sRangeArray);
    filer.setRanges(sRangeArray);

    // Put single value item in the filter with '%value%'
    FilterItem[] filterArray = new FilterItem[filterItemArrayList.size()];
    filterArray = filterItemArrayList.toArray(filterArray);
    filer.setFilters(filterArray);

    // Put single value item in the filter, with exact search with 'value'
    FilterItem[] exactFilterArray = new FilterItem[exactFilterItemArrayList.size()];
    exactFilterArray = exactFilterItemArrayList.toArray(exactFilterArray);
    filer.setExactFilters(exactFilterArray);

    // Put the multiple values (',' separated) item in the filter.
    FilterItem[] filterItemA = new FilterItem[multipleFilterItemArrayList.size()];
    filterItemA = multipleFilterItemArrayList.toArray(filterItemA);
    filer.setSearchForFieldItems(filterItemA);

    //System.out.println("time in making query:"+(new Date().getTime()-startTime)+" msecs");   
    //System.out.println("limit " + request.getParameter("limit") + ", offset " + 
    //      request.getParameter("offset") +", sort " + sort + ", sort direction "+ sort_direction);

    Object returnObj = null;
    startTime = new Date().getTime();

    // Create a Timer and a TimerTask
    Timer timer = new Timer();
    TimerTask task = new SearchPropertyTimerTask(request, response, this.getOutputType());

    // Set timer for 30 sec, method takes args in milliseconds.
    timer.schedule(task, 30 * 1000);
    boolean timedoutResponse = true;// Default is timed out response.

    try {
        /* for testing of timer functionality.
        try {
         Thread.sleep(10000);
        } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }*/

        Properties prop = propServices.searchForProperties(start, limit, sort, sort_direction, filer, geoParam,
                returnOpenHouseData);
        prop.setElapsedTime(BigInteger.valueOf(System.currentTimeMillis() - reqInputArrivalTime));

        if (this.getOutputType().equalsIgnoreCase("json")) {
            returnObj = getJSONReturnObj(prop);
        } else {
            returnObj = prop;
        }
    } catch (LargeResultSetException e) {
        Errors errors = new Errors();
        com.irets.generated.Error error = new com.irets.generated.Error();
        error.setCode(e.getErrorCode());
        error.setDescription(e.getMessage());
        errors.getError().add(error);
        errors.setTotalcount(BigInteger.valueOf(e.getTotalCount()));
        errors.setElapsedtime(BigInteger.valueOf(System.currentTimeMillis() - reqInputArrivalTime));
        returnObj = errors;
        System.out.println(e.getMessage());
    } finally {
        if (task.cancel()) {
            timedoutResponse = false;// No timeout, send normal response.             
        }
    }

    System.out.println("time in database call:" + (new Date().getTime() - startTime) + " msecs");

    //startTime = new Date().getTime();
    //GSONHelper.serializeToJSON(prop, response.getOutputStream());
    if (!timedoutResponse) {
        if (this.getOutputType().equalsIgnoreCase("json")) {
            response.setContentType("application/json");
            JacksonJSONHelper.serializeToJSON(returnObj, response.getOutputStream(), response);
        } else {
            response.setContentType("text/xml");
            JAXBHelper.serializeToXML(returnObj, response.getOutputStream());
        }
    }
    //System.out.println("time in making output:"+(new Date().getTime()-startTime)+" msecs");
    System.out.println("Done!!!! elapsed time: " + (System.currentTimeMillis() - reqInputArrivalTime));
}

From source file:io.puzzlebox.bloom.ui.BloomFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View v = inflater.inflate(R.layout.fragment_bloom, container, false);

    //      requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    //      setContentView(R.layout.main);
    //      getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

    progressBarAttention = (ProgressBar) v.findViewById(R.id.progressBarAttention);
    final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
    ShapeDrawable progressBarAttentionDrawable = new ShapeDrawable(
            new RoundRectShape(roundedCorners, null, null));
    String progressBarAttentionColor = "#FF0000";
    progressBarAttentionDrawable.getPaint().setColor(Color.parseColor(progressBarAttentionColor));
    ClipDrawable progressAttention = new ClipDrawable(progressBarAttentionDrawable, Gravity.LEFT,
            ClipDrawable.HORIZONTAL);/*from   w ww  . j a v  a2s .c  om*/
    progressBarAttention.setProgressDrawable(progressAttention);
    progressBarAttention
            .setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));

    progressBarMeditation = (ProgressBar) v.findViewById(R.id.progressBarMeditation);
    ShapeDrawable progressBarMeditationDrawable = new ShapeDrawable(
            new RoundRectShape(roundedCorners, null, null));
    String progressBarMeditationColor = "#0000FF";
    progressBarMeditationDrawable.getPaint().setColor(Color.parseColor(progressBarMeditationColor));
    ClipDrawable progressMeditation = new ClipDrawable(progressBarMeditationDrawable, Gravity.LEFT,
            ClipDrawable.HORIZONTAL);
    progressBarMeditation.setProgressDrawable(progressMeditation);
    progressBarMeditation
            .setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));

    progressBarSignal = (ProgressBar) v.findViewById(R.id.progressBarSignal);
    ShapeDrawable progressBarSignalDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null, null));
    String progressBarSignalColor = "#00FF00";
    progressBarSignalDrawable.getPaint().setColor(Color.parseColor(progressBarSignalColor));
    ClipDrawable progressSignal = new ClipDrawable(progressBarSignalDrawable, Gravity.LEFT,
            ClipDrawable.HORIZONTAL);
    progressBarSignal.setProgressDrawable(progressSignal);
    progressBarSignal.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));
    //      progressBarSignal.setProgress(tgSignal);

    progressBarPower = (ProgressBar) v.findViewById(R.id.progressBarPower);
    ShapeDrawable progressBarPowerDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null, null));
    String progressBarPowerColor = "#FFFF00";
    progressBarPowerDrawable.getPaint().setColor(Color.parseColor(progressBarPowerColor));
    ClipDrawable progressPower = new ClipDrawable(progressBarPowerDrawable, Gravity.LEFT,
            ClipDrawable.HORIZONTAL);
    progressBarPower.setProgressDrawable(progressPower);
    progressBarPower.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));

    //      progressBarRange = (ProgressBar) v.findViewById(R.id.progressBarRange);
    ////      ShapeDrawable progressBarRangeDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null,null));
    //      ShapeDrawable progressBarRangeDrawable = new ShapeDrawable();
    ////      String progressBarRangeColor = "#FF00FF";
    //      String progressBarRangeColor = "#990099";
    //      progressBarRangeDrawable.getPaint().setColor(Color.parseColor(progressBarRangeColor));
    //      ClipDrawable progressRange = new ClipDrawable(progressBarRangeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
    //      progressBarRange.setProgressDrawable(progressRange);
    //      progressBarRange.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));
    //
    ////      progressBarRange.setMax(128 + 127);
    //      progressBarRange.setMax(bloomRangeMax);

    //      progressBarBloom = (ProgressBar) v.findViewById(R.id.progressBarBloom);
    //      ShapeDrawable progressBarBloomDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null,null));
    //      String progressBarBloomColor = "#7F0000";
    //      progressBarBloomDrawable.getPaint().setColor(Color.parseColor(progressBarBloomColor));
    //      ClipDrawable progressBloom = new ClipDrawable(progressBarBloomDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
    //      progressBarBloom.setProgressDrawable(progressBloom);
    //      progressBarBloom.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.progress_horizontal));

    seekBarAttention = (SeekBar) v.findViewById(R.id.seekBarAttention);
    seekBarAttention.setOnSeekBarChangeListener(this);
    seekBarMeditation = (SeekBar) v.findViewById(R.id.seekBarMeditation);
    seekBarMeditation.setOnSeekBarChangeListener(this);

    //      imageViewStatus = (ImageView) v.findViewById(R.id.imageViewStatus);

    servoSeekBar = (SeekBar) v.findViewById(R.id.ServoSeekBar);
    servoSeekBar.setEnabled(false);
    //      servoSeekBar.setMax(180);
    servoSeekBar.setMax(100);
    servoSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            byte[] buf = new byte[] { (byte) 0x03, (byte) 0x00, (byte) 0x00 };

            buf[1] = (byte) servoSeekBar.getProgress();

            BloomSingleton.getInstance().characteristicTx.setValue(buf);
            BloomSingleton.getInstance().mBluetoothLeService
                    .writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
        }
    });

    //      rssiValue = (TextView) v.findViewById(R.id.rssiValue);

    connectBloom = (Button) v.findViewById(R.id.connectBloom);

    connectBloom.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                if (!BloomSingleton.getInstance().scanFlag) {
                    scanLeDevice();

                    Timer mTimer = new Timer();
                    mTimer.schedule(new TimerTask() {

                        @Override
                        public void run() {
                            if ((BloomSingleton.getInstance().mDevice != null)
                                    && (BloomSingleton.getInstance().mDevice.getAddress() != null)
                                    && (BloomSingleton.getInstance().mBluetoothLeService != null)) {
                                BloomSingleton
                                        .getInstance().mDeviceAddress = BloomSingleton.getInstance().mDevice
                                                .getAddress();
                                if (BloomSingleton.getInstance().mDeviceAddress != null)
                                    BloomSingleton.getInstance().mBluetoothLeService
                                            .connect(BloomSingleton.getInstance().mDeviceAddress);
                                else {
                                    Toast toast = Toast.makeText(getActivity(),
                                            "Error connecting to Puzzlebox Bloom", Toast.LENGTH_SHORT);
                                    toast.setGravity(0, 0, Gravity.CENTER | Gravity.BOTTOM);
                                    toast.show();
                                }
                                BloomSingleton.getInstance().scanFlag = true;
                            } else {
                                getActivity().runOnUiThread(new Runnable() {
                                    public void run() {
                                        Toast toast = Toast.makeText(getActivity(),
                                                "Error connecting to Puzzlebox Bloom", Toast.LENGTH_SHORT);
                                        toast.setGravity(0, 0, Gravity.CENTER | Gravity.BOTTOM);
                                        toast.show();
                                    }
                                });
                            }
                        }
                    }, BloomSingleton.getInstance().SCAN_PERIOD);
                }
            } catch (Exception e) {
                Log.e(TAG, "Exception connecting to Bloom: " + e);
                Toast toast = Toast.makeText(getActivity(), "Exception connecting to Puzzlebox Bloom",
                        Toast.LENGTH_SHORT);
                toast.setGravity(0, 0, Gravity.CENTER | Gravity.BOTTOM);
                toast.show();
            }

            System.out.println(BloomSingleton.getInstance().connState);
            //            Log.e(TAG, connState);
            //            if (connState == false) {
            if (!BloomSingleton.getInstance().connState
                    && BloomSingleton.getInstance().mDeviceAddress != null) {
                BloomSingleton.getInstance().mBluetoothLeService
                        .connect(BloomSingleton.getInstance().mDeviceAddress);
            } else {
                if (BloomSingleton.getInstance().mBluetoothLeService != null) {
                    setBloomRGBOff();
                    BloomSingleton.getInstance().mBluetoothLeService.disconnect();
                    BloomSingleton.getInstance().mBluetoothLeService.close();
                    setButtonDisable();
                }
            }
        }
    });

    //      Button buttonOpen = (Button) v.findViewById(R.id.buttonOpen);
    //      buttonOpen.setOnClickListener(new View.OnClickListener() {
    //         @Override
    //         public void onClick(View v) {
    //            byte[] buf = new byte[] { (byte) 0x01, (byte) 0x00, (byte) 0x00 };
    //            BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //            BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //         }
    //      });
    //      buttonOpen.setVisibility(View.GONE);
    //
    //      Button buttonClose = (Button) v.findViewById(R.id.buttonClose);
    //      buttonClose.setOnClickListener(new View.OnClickListener() {
    //         @Override
    //         public void onClick(View v) {
    //            byte[] buf = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00 };
    //            BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //            BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //         }
    //      });
    //      buttonClose.setVisibility(View.GONE);

    //      buttonDemo = (Button) v.findViewById(R.id.buttonDemo);
    //      buttonDemo.setOnClickListener(new View.OnClickListener() {
    //         @Override
    //         public void onClick(View v) {
    //            byte[] buf;
    ////            if (! BloomSingleton.getInstance().demoActive) {
    //            BloomSingleton.getInstance().demoActive = true;
    //
    //            // bloomOpen()
    ////            buf = new byte[]{(byte) 0x01, (byte) 0x00, (byte) 0x00};
    ////            BloomSingleton.getInstance().characteristicTx.setValue(buf);
    ////            BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //
    //            // loopRGB()
    //            buf = new byte[]{(byte) 0x06, (byte) 0x00, (byte) 0x00};
    //            BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //            BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //
    //            // Set Red to 0
    //            buf = new byte[]{(byte) 0x0A, (byte) 0x00, (byte) 0x00}; // R = 0
    //            BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //            BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //
    //            // bloomClose()
    ////            buf = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00};
    ////            BloomSingleton.getInstance().characteristicTx.setValue(buf);
    ////            BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //
    //
    ////            } else {
    ////               BloomSingleton.getInstance().demoActive = false;
    //////               buf = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00};
    //////               BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //////               BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    ////               buf = new byte[]{(byte) 0x0A, (byte) 0x00, (byte) 0x00}; // R = 0
    ////               BloomSingleton.getInstance().characteristicTx.setValue(buf);
    ////               BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //////               buf = new byte[]{(byte) 0x0A, (byte) 0x01, (byte) 0x00}; // G = 0
    //////               BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //////               BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    //////               buf = new byte[]{(byte) 0x0A, (byte) 0x02, (byte) 0x00}; // B = 0
    //////               BloomSingleton.getInstance().characteristicTx.setValue(buf);
    //////               BloomSingleton.getInstance().mBluetoothLeService.writeCharacteristic(BloomSingleton.getInstance().characteristicTx);
    ////            }
    //         }
    //      });

    if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(getActivity(), "Bluetooth LE not supported", Toast.LENGTH_SHORT).show();
        getActivity().finish();
    }

    final BluetoothManager mBluetoothManager = (BluetoothManager) getActivity()
            .getSystemService(Context.BLUETOOTH_SERVICE);
    BloomSingleton.getInstance().mBluetoothAdapter = mBluetoothManager.getAdapter();
    if (BloomSingleton.getInstance().mBluetoothAdapter == null) {
        Toast.makeText(getActivity(), "Bluetooth LE not supported", Toast.LENGTH_SHORT).show();
        getActivity().finish();
        return v;
    }

    Intent gattServiceIntent = new Intent(getActivity(), RBLService.class);
    //      bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    getActivity().bindService(gattServiceIntent, mServiceConnection, getActivity().BIND_AUTO_CREATE);

    /**
     * Update settings according to default UI
     */

    updateScreenLayout();

    //      updatePowerThresholds();
    //      updatePower();

    if (BloomSingleton.getInstance().connState)
        setButtonEnable();

    return v;

}

From source file:sjizl.com.ChatActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (CommonUtilities.isInternetAvailable(getApplicationContext())) //returns true if internet available
    {/*www.j  a  v a 2  s  .  c  o  m*/

        SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
        pid = sp.getString("pid", null);
        naam = sp.getString("naam", null);
        username = sp.getString("username", null);
        password = sp.getString("password", null);
        foto = sp.getString("foto", null);
        foto_num = sp.getString("foto_num", null);
        Bundle bundle = getIntent().getExtras();
        pid_user = bundle.getString("pid_user");
        user = bundle.getString("user");
        user_foto_num = bundle.getString("user_foto_num");
        user_foto = bundle.getString("user_foto");

        // Toast.makeText(getApplicationContext(), "pid_user"+pid_user, Toast.LENGTH_SHORT).show();

        if (user.equalsIgnoreCase(naam.toString())) {
            Toast.makeText(getApplicationContext(), "You can't message yourself!", Toast.LENGTH_SHORT).show();
            finish();
        }

        AbsListViewBaseActivity.imageLoader.init(ImageLoaderConfiguration.createDefault(getBaseContext()));

        //registerReceiver(mHandleMessageReceiver2, new IntentFilter(DISPLAY_MESSAGE_ACTION));
        setContentView(R.layout.activity_chat);

        imageLoader.loadImage("https://www.sjizl.com/fotos/" + user_foto_num + "/thumbs/" + user_foto + "",
                new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        d1 = new BitmapDrawable(getResources(), loadedImage);

                    }
                });

        imageLoader.loadImage("https://www.sjizl.com/fotos/" + foto_num + "/thumbs/" + foto + "",
                new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        d2 = new BitmapDrawable(getResources(), loadedImage);

                    }
                });

        smilbtn = (ImageView) findViewById(R.id.smilbtn);
        listView = (ListView) findViewById(android.R.id.list);
        underlayout = (LinearLayout) findViewById(R.id.underlayout);
        smiles_layout = (LinearLayout) findViewById(R.id.smiles);
        textView1_bgtext = (TextView) findViewById(R.id.textView1_bgtext);
        textView1_bgtext.setText(user);
        imageView2_dashboard = (ImageView) findViewById(R.id.imageView2_dashboard);
        imageView1_logo = (ImageView) findViewById(R.id.imageView1_logo);
        imageView_bericht = (ImageView) findViewById(R.id.imageView_bericht);
        textView2_under_title = (TextView) findViewById(R.id.textView2_under_title);
        right_lin = (LinearLayout) findViewById(R.id.right_lin);
        left_lin1 = (LinearLayout) findViewById(R.id.left_lin1);
        left_lin3 = (LinearLayout) findViewById(R.id.left_lin3);
        left_lin4 = (LinearLayout) findViewById(R.id.left_lin4);
        middle_lin = (LinearLayout) findViewById(R.id.middle_lin);
        smile_lin = (LinearLayout) findViewById(R.id.smile_lin);
        ber_lin = (LinearLayout) findViewById(R.id.ber_lin);
        progressBar_hole = (ProgressBar) findViewById(R.id.progressBar_hole);
        progressBar_hole.setVisibility(View.INVISIBLE);
        imageLoader.displayImage("http://sjizl.com/fotos/" + user_foto_num + "/thumbs/" + user_foto,
                imageView2_dashboard, options);
        new UpdateChat().execute();
        mNewMessage = (EditText) findViewById(R.id.newmsg);

        ber_lin = (LinearLayout) findViewById(R.id.ber_lin);
        photosend = (ImageView) findViewById(R.id.photosend);

        /*
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    
                    
                    
            imageLoader.loadImage("http://sjizl.com/fotos/"+user_foto_num+"/thumbs/"+user_foto, new SimpleImageLoadingListener() {
               @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        super.onLoadingComplete(imageUri, view, loadedImage);
                
        Bitmap LoadedImage2 = loadedImage;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
           if(loadedImage!=null){
        LoadedImage2 = CommonUtilities.fastblur16(loadedImage, 4,getApplicationContext());
           }
        }
                
        if (Build.VERSION.SDK_INT >= 16) {
                
           listView.setBackground(new BitmapDrawable(getApplicationContext().getResources(), LoadedImage2));
                
          } else {
                
             listView.setBackgroundDrawable(new BitmapDrawable(LoadedImage2));
          }
                
        }
        }
            );
        }
        */
        final ImageView left_button;
        left_button = (ImageView) findViewById(R.id.imageView1_back);
        CommonUtilities u = new CommonUtilities();
        u.setHeaderConrols(getApplicationContext(), this, right_lin, left_lin3, left_lin4, left_lin1,
                left_button);

        listView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                mScrollState = scrollState;
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
            }

        });
        listView.setLongClickable(true);
        registerForContextMenu(listView);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        viewPager_smiles = new ViewPager(this);
        viewPager_smiles.setId(0x1000);
        LayoutParams layoutParams555 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams555.width = LayoutParams.MATCH_PARENT;
        layoutParams555.height = (metrics.heightPixels / 2);
        viewPager_smiles.setLayoutParams(layoutParams555);
        TabsPagerAdapter mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), mNewMessage);
        viewPager_smiles.setAdapter(mAdapter);
        LayoutInflater inflater = null;
        viewPager_smiles.setVisibility(View.VISIBLE);
        smiles_layout.addView(viewPager_smiles);
        smiles_layout.setVisibility(View.GONE);

        left_lin4.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Intent profile = new Intent(getApplicationContext(), ProfileActivityMain.class);
                    profile.putExtra("user", user);
                    profile.putExtra("user_foto", user_foto);
                    profile.putExtra("user_foto_num", user_foto_num);
                    profile.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(profile);
                }
                return false;
            }
        });
        middle_lin.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Intent profile = new Intent(getApplicationContext(), ProfileActivityMain.class);
                    profile.putExtra("user", user);
                    profile.putExtra("user_foto", user_foto);
                    profile.putExtra("user_foto_num", user_foto_num);
                    profile.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(profile);
                }
                return false;
            }
        });

        smile_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                opensmiles();
            }
        });

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent dashboard = new Intent(getApplicationContext(), ProfileActivityMain.class);
                dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                dashboard.putExtra("user", ArrChatLines.get(position).getNaam());
                dashboard.putExtra("user_foto", foto);
                dashboard.putExtra("user_foto_num", foto_num);
                startActivity(dashboard);
            }
        });

        mNewMessage.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {

                    v.setFocusable(true);
                    v.setFocusableInTouchMode(true);

                    smiles_layout.setVisibility(View.GONE);
                    smilbtn.setImageResource(R.drawable.emoji_btn_normal);
                    return false;
                }
                return false;
            }
        });

        TextWatcher textWatcher = new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //after text changed
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                if (ArrChatLines.get(0).getblocked_profile().equals("1")) {

                } else if (ArrChatLines.get(0).getblocked_profile2().equals("1")) {

                } else {
                    CommonUtilities.startandsendwebsock(
                            "" + pid_user + " " + naam + " " + pid + " is typing to you ...");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                /*
                 AsyncHttpClient.getDefaultInstance().websocket("ws://sjizl.com:9300", "my-protocol", new WebSocketConnectCallback() {
                  @Override
                     public void onCompleted(Exception ex, WebSocket webSocket) {
                         if (ex != null) {
                   ex.printStackTrace();
                   return;
                         }
                         webSocket.send(""+pid_user+" "+naam+" "+pid+" is typing to you ...");
                                 
                         webSocket.close();
                     }
                 });
                 */
            }
        };

        photosend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ArrChatLines.get(0).getblocked_profile().equals("1")) {

                } else if (ArrChatLines.get(0).getblocked_profile2().equals("1")) {

                } else {
                    openGallery(SELECT_FILE1);
                }
            }
        });

        mNewMessage.addTextChangedListener(textWatcher);

        ber_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableStringBuilder spanStr = (SpannableStringBuilder) mNewMessage.getText();
                Spanned cs = (Spanned) mNewMessage.getText();
                String a = Html.toHtml(spanStr);
                String text = mNewMessage.getText().toString();
                mNewMessage.setText("");
                mNewMessage.requestFocus();
                mybmp2 = "http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto;
                if (text.length() < 1) {
                } else {
                    addItem(foto, foto_num, "0", naam, text.toString(),
                            "http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto, "", a);
                }
            }
        });

        hideSoftKeyboard();

    } else {

        Intent dashboard = new Intent(getApplicationContext(), NoInternetActivity.class);
        dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(dashboard);

        finish();
    }
    mNewMessage.clearFocus();
    listView.requestFocus();

    final String wsuri = "ws://sjizl.com:9300";

    WebSocketConnection mConnection8 = new WebSocketConnection();

    if (mConnection8.isConnected()) {
        mConnection8.reconnect();

    } else {
        try {
            mConnection8.connect(wsuri, new WebSocketConnectionHandler() {

                @Override
                public void onOpen() {
                    Log.d("TAG", "Status: Connected to " + wsuri);

                }

                @Override
                public void onTextMessage(String payload) {

                    if (payload.contains("message send")) {
                        String[] parts = payload.split(" ");
                        String zender = parts[0];
                        String send_from = parts[1];
                        String send_name = parts[2];
                        String send_foto = parts[3];
                        String send_foto_num = parts[4];
                        String send_xxx = parts[5];

                        //      Toast.makeText(getApplication(), "" +   "\n zender: "+zender+"" +   "\n pid_user: "+pid_user+"" +"\n pid: "+pid+"" +
                        //         "\n send_from: "+send_from, 
                        //                  Toast.LENGTH_LONG).show();
                        if (zender.equalsIgnoreCase(pid) || zender.equalsIgnoreCase(pid_user)) {

                            if (send_from.equalsIgnoreCase(pid_user) || send_from.equalsIgnoreCase(pid)) {

                                //Toast.makeText(getApplication(), "uu",    Toast.LENGTH_LONG).show();

                                new UpdateChat().execute();

                            }
                        }

                    } else if (payload.contains("is typing to you")) {

                        String[] parts = payload.split(" ");
                        String part1 = parts[0]; // 004
                        is_typing_name = parts[1]; // 034556
                        if (is_typing_name.equalsIgnoreCase(user)) {

                            if (ArrChatLines.size() > 0) {
                                oldvalue = ArrChatLines.get(0).getLaatstOnline();

                            } else {
                                oldvalue = textView2_under_title.getText().toString();
                            }

                            Timer t = new Timer(false);
                            t.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            textView2_under_title.setText("typing ...");
                                        }
                                    });
                                }
                            }, 2);

                            Timer t2 = new Timer(false);
                            t2.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            textView2_under_title.setText(oldvalue);
                                        }
                                    });
                                }
                            }, 2000);
                        }

                    }
                    Log.d("TAG", "Got echo: " + payload);
                }

                @Override
                public void onClose(int code, String reason) {
                    Log.d("TAG", "Connection lost.");
                }
            });
        } catch (WebSocketException e) {
            Log.d("TAG", e.toString());
        }
    }

}

From source file:com.gizwits.smartlight.activity.MainListActivity.java

@Override
public void onResume() {
    super.onResume();
    refreshMenu();/* w w  w.ja v  a  2  s .  co  m*/
    //?
    Log.d(TAG, "centralControlsetListener");
    centralControlDevice = (XPGWifiCentralControlDevice) mXpgWifiDevice;
    centralControlDevice.setListener(xpgWifiCentralControlDeviceListener);
    mCenter.cSetXPGWifiCentralControlDevice(centralControlDevice);
    mCenter.cSetDid(centralControlDevice.getDid());
    // bottomClose();
    ledList.clear();
    ControllerList.clear();
    showItemDevices.clear();
    //First get group information then subdeviceList
    mCenter.cGetGroups(setmanager.getUid(), setmanager.getToken(), Configs.PRODUCT_KEY_Sub);//?
    mCenter.cGetSubDevicesList(centralControlDevice);//??
    mCenter.cGetAllScenes(setmanager.getUid(), setmanager.getToken(), Configs.PRODUCT_KEY_Sub);//?

    //        // bottomClose();
    //        ledList.clear();
    //        ControllerList.clear();
    //        showItemDevices.clear();

    //3??Loadding
    getStatusProgress.show();
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            getStatusProgress.cancel();
            timer.cancel();
        }
    }, 3000);
}

From source file:org.apache.bookkeeper.util.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }//  ww  w  .j  av a 2  s.c o  m
    if (dir != null) {
        builder.directory(this.dir);
    }

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), Charsets.UTF_8));
    BufferedReader inReader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charsets.UTF_8));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = MathUtils.now();
    }
}

From source file:com.tencent.gaia.portal.util.Shell.java

/**
 * Run a command/*  w  ww  . j a  v  a 2s.c om*/
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        try {
            if (!completed.get()) {
                errThread.interrupt();
                errThread.join();
            }
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while joining errThread");
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}

From source file:org.springframework.yarn.test.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }//from www . j av  a2s .c  o  m
    if (dir != null) {
        builder.directory(this.dir);
    }

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        // One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        // the timeout thread handling
        // taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.now();
    }
}