Example usage for java.lang IndexOutOfBoundsException printStackTrace

List of usage examples for java.lang IndexOutOfBoundsException printStackTrace

Introduction

In this page you can find the example usage for java.lang IndexOutOfBoundsException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.repay.android.frienddetails.FriendActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (data != null && requestCode == PICK_CONTACT_REQUEST) {
        try {// w  w w  . ja  v a2 s .  c o m
            String contactUri = data.getData().toString();
            String displayName = ContactsContractHelper.getNameForContact(this, contactUri);

            Friend pickerResult = new Friend(mFriend.getRepayID(), contactUri, displayName, mFriend.getDebt());

            mDB.updateFriendRecord(pickerResult);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
            Toast.makeText(this, "Problem in getting result from your contacts", Toast.LENGTH_SHORT).show();
        } catch (SQLException e) {
            e.printStackTrace();
            Toast.makeText(this, "Unable to add this person to the database", Toast.LENGTH_SHORT).show();
        }
    }
}

From source file:com.repay.android.adddebt.AddDebtActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (data != null && requestCode == 1) {
        try {//from  ww  w.  ja  v  a  2 s.c  om
            Log.i(TAG, "Closing contact picker");
            Uri contactUri = data.getData();
            String[] cols = { ContactsContract.Contacts.DISPLAY_NAME };
            Cursor cursor = getContentResolver().query(contactUri, cols, null, null, null);
            cursor.moveToFirst();
            String result = cursor.getString(0).replaceAll("[-+.^:,']", "");
            Friend pickerResult = new Friend(DatabaseHandler.generateRepayID(), contactUri, result,
                    new BigDecimal("0"));
            mDB.addFriend(pickerResult);
            ((ChoosePersonFragment) mChoosePerson).dataSetChanged();
        } catch (IndexOutOfBoundsException e) {
            Toast.makeText(this, "Problem in getting result from your contacts", Toast.LENGTH_SHORT).show();
        } catch (SQLException e) {
            e.printStackTrace();
            AlertDialog alert = new AlertDialog.Builder(this).create();
            alert.setMessage("This person already exists in Repay");
            alert.setTitle("Person Already Exists");
            Log.i(TAG, "Person already exists within app database");
            alert.show();
        }
    }
}

From source file:io.indy.drone.activity.StrikeListActivity.java

protected void onDrawerItemClicked(int position) {
    // Highlight the selected item, update the title, and close the drawer
    mDrawerList.setItemChecked(position, true);
    setTitle(mDrawerTitles[position]);/*from w  w  w  .  j a v  a  2s .c  o m*/

    try {
        onRegionSelected(position);
        //mRegion = SQLDatabase.regionFromIndex(position);
        //mStrikeLocations = mDatabase.getStrikeLocationsInRegion(mRegion);

        ((StrikeListFragment) getSupportFragmentManager().findFragmentById(R.id.strike_list))
                .onRegionClicked(mRegion);

    } catch (IndexOutOfBoundsException e) {
        e.printStackTrace();
        throw e;
    }

    mDrawerLayout.closeDrawer(mDrawerList);
}

From source file:io.indy.drone.activity.StrikeListActivity.java

protected void setupNavigationDrawer() {

    try {/*from   www.j  a  v  a 2s .  c om*/
        mRegion = SQLDatabase.regionFromIndex(0); // worldwide
    } catch (IndexOutOfBoundsException e) {
        e.printStackTrace();
    }

    mStrikeLocations = mDatabase.getStrikeLocationsInRegion(mRegion);

    mTitle = mDrawerTitle = getTitle();
    mDrawerTitles = getResources().getStringArray(R.array.locations_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

    // Set the drawer toggle as the DrawerListener
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    // Set the adapter for the list view
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mDrawerTitles));
    // Set the list's click listener
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}

From source file:eu.operando.proxy.service.ProxyService.java

private HttpFiltersSource getFiltersSource() {

    return new HttpFiltersSourceAdapter() {

        //                @Override
        //                public int getMaximumRequestBufferSizeInBytes() {
        //                    // TODO Auto-generated method stub
        //                    return 10 * 1024 * 1024;
        ///*ww w.ja v  a  2 s . c o  m*/
        //                }
        //
        //                @Override
        //                public int getMaximumResponseBufferSizeInBytes() {
        //                    // TODO Auto-generated method stub
        //                    return 10 * 1024 * 1024;
        //                }

        @Override
        public HttpFilters filterRequest(HttpRequest originalRequest) {

            return new HttpFiltersAdapter(originalRequest) {

                @Override
                public HttpObject serverToProxyResponse(HttpObject httpObject) {

                    if (MainUtil.isProxyPaused(mainContext))
                        return httpObject;

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage response = (HttpMessage) httpObject;
                        response.headers().set(HttpHeaderNames.CACHE_CONTROL,
                                "no-cache, no-store, must-revalidate");
                        response.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
                        response.headers().set(HttpHeaderNames.EXPIRES, "0");
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            boolean flag = false;
                            List<ResponseFilter> responseFilters = db.getAllResponseFilters();
                            if (responseFilters.size() > 0) {

                                String contentStr = buf.toString(Charset.forName("UTF-8")); //Charset.forName(Charset.forName("UTF-8")
                                for (ResponseFilter responseFilter : responseFilters) {

                                    String toReplace = responseFilter.getContent();

                                    if (StringUtils.containsIgnoreCase(contentStr, toReplace)) {
                                        contentStr = contentStr.replaceAll("(?i)" + toReplace,
                                                StringUtils.leftPad("", toReplace.length(), '#'));
                                        flag = true;
                                    }

                                }
                                if (flag) {
                                    buf.clear().writeBytes(contentStr.getBytes(Charset.forName("UTF-8")));
                                }
                            }

                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }
                    return httpObject;
                }

                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {

                    if (MainUtil.isProxyPaused(mainContext))
                        return null;

                    String requestURI;
                    Set<RequestFilterUtil.FilterType> exfiltrated = new HashSet<>();
                    String[] locationInfo = requestFilterUtil.getLocationInfo();
                    String[] contactsInfo = requestFilterUtil.getContactsInfo();
                    String[] phoneInfo = requestFilterUtil.getPhoneInfo();

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage request = (HttpMessage) httpObject;
                        if (request.headers().contains(CustomHeaderField)) {
                            applicationInfoStr = request.headers().get(CustomHeaderField);
                            request.headers().remove(CustomHeaderField);
                        }

                        if (request.headers().contains(HttpHeaderNames.ACCEPT_ENCODING)) {
                            request.headers().remove(HttpHeaderNames.ACCEPT_ENCODING);
                        }

                        /*
                        Sanitize Hosts
                        */
                        if (!ProxyUtils.isCONNECT(request)
                                && request.headers().contains(HttpHeaderNames.HOST)) {
                            String hostName = request.headers().get(HttpHeaderNames.HOST).toLowerCase();
                            if (db.isDomainBlocked(hostName))
                                return getBlockedHostResponse(hostName);
                        }

                    }

                    if (httpObject instanceof HttpRequest) {

                        HttpRequest request = (HttpRequest) httpObject;
                        requestURI = request.uri();

                        try {
                            requestURI = URLDecoder.decode(requestURI, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        /*
                        Request URI checks
                         */
                        if (StringUtils.containsAny(requestURI, locationInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                        }

                        if (StringUtils.containsAny(requestURI, contactsInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                        }

                        if (StringUtils.containsAny(requestURI, phoneInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.PHONEINFO);
                        }

                        if (!exfiltrated.isEmpty()) {
                            mainContext.getNotificationUtil().displayExfiltratedNotification(applicationInfoStr,
                                    exfiltrated);
                            return getForbiddenRequestResponse(applicationInfoStr, exfiltrated);
                        }

                    }

                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);

                            String contentStr = buf.toString(Charset.forName("UTF-8"));

                            if (StringUtils.containsAny(contentStr, locationInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                            }

                            if (StringUtils.containsAny(contentStr, contactsInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                            }

                            if (StringUtils.containsAny(contentStr, phoneInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.PHONEINFO);
                            }

                            if (!exfiltrated.isEmpty()) {
                                mainContext.getNotificationUtil()
                                        .displayExfiltratedNotification(applicationInfoStr, exfiltrated);
                                return getForbiddenRequestResponse(applicationInfoStr, exfiltrated);
                            }

                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }

                    return null;
                }

            };
        }
    };
}

From source file:com.repay.android.frienddetails.FriendDetailsActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (data != null && requestCode == PICK_CONTACT_REQUEST) {
        try {/*ww w.j a v a  2  s  .c o m*/
            Uri contactUri = data.getData();
            String[] cols = { ContactsContract.Contacts.DISPLAY_NAME };
            Cursor cursor = getContentResolver().query(contactUri, cols, null, null, null);
            cursor.moveToFirst();
            String result = cursor.getString(0).replaceAll("[-+.^:,']", "");
            Friend pickerResult = new Friend(mFriend.getRepayID(), contactUri, result, mFriend.getDebt());
            mDB.updateFriendRecord(pickerResult);
            requestBackup();
        } catch (IndexOutOfBoundsException e) {
            Toast.makeText(this, "Problem in getting result from your contacts", Toast.LENGTH_SHORT).show();
        } catch (SQLException e) {
            e.printStackTrace();
            Toast.makeText(this, "Unable to add this person to the database", Toast.LENGTH_SHORT).show();
        }
    } else if (data != null && requestCode == AMOUNT_ENTER_REQUEST) {
        try {
            Bundle b = data.getExtras();
            // Get the amount sent back from the activity
            BigDecimal amount = new BigDecimal(b.getString(AddDebtActivity.AMOUNT));
            // Make the amount negative if their debt is negative
            if (mFriend.getDebt().compareTo(BigDecimal.ZERO) > 0) {
                amount = amount.negate();
            }
            mDB.addDebt(mFriend.getRepayID(), amount, "Repaid");
            mFriend.setDebt(mFriend.getDebt().add(amount));
            mDB.updateFriendRecord(mFriend);
            requestBackup();
        } catch (Exception e) {

        }
    }
}

From source file:eu.operando.operandoapp.service.ProxyService.java

private HttpFiltersSource getFiltersSource() {
    return new HttpFiltersSourceAdapter() {
        @Override/*from w  w w. ja  v  a 2  s.c o m*/
        public HttpFilters filterRequest(HttpRequest originalRequest) {
            return new HttpFiltersAdapter(originalRequest) {
                @Override
                public HttpObject serverToProxyResponse(HttpObject httpObject) {
                    //check for proxy running
                    if (MainUtil.isProxyPaused(mainContext))
                        return httpObject;

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage response = (HttpMessage) httpObject;
                        response.headers().set(HttpHeaderNames.CACHE_CONTROL,
                                "no-cache, no-store, must-revalidate");
                        response.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
                        response.headers().set(HttpHeaderNames.EXPIRES, "0");
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            boolean flag = false;
                            List<ResponseFilter> responseFilters = db.getAllResponseFilters();
                            if (responseFilters.size() > 0) {
                                String contentStr = buf.toString(Charset.forName("UTF-8")); //Charset.forName(Charset.forName("UTF-8")
                                for (ResponseFilter responseFilter : responseFilters) {
                                    String toReplace = responseFilter.getContent();
                                    if (StringUtils.containsIgnoreCase(contentStr, toReplace)) {
                                        contentStr = contentStr.replaceAll("(?i)" + toReplace,
                                                StringUtils.leftPad("", toReplace.length(), '#'));
                                        flag = true;
                                    }
                                }
                                if (flag) {
                                    buf.clear().writeBytes(contentStr.getBytes(Charset.forName("UTF-8")));
                                }
                            }
                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }
                    return httpObject;
                }

                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                    //check for proxy running
                    if (MainUtil.isProxyPaused(mainContext)) {
                        return null;
                    }

                    //check for trusted access point
                    String ssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo()
                            .getSSID();
                    String bssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo()
                            .getBSSID();
                    boolean trusted = false;
                    TrustedAccessPoint curr_tap = new TrustedAccessPoint(ssid, bssid);
                    for (TrustedAccessPoint tap : db.getAllTrustedAccessPoints()) {
                        if (curr_tap.isEqual(tap)) {
                            trusted = true;
                        }
                    }
                    if (!trusted) {
                        return getUntrustedGatewayResponse();
                    }

                    //check for blocked url

                    //check for exfiltration
                    requestFilterUtil = new RequestFilterUtil(getApplicationContext());
                    locationInfo = requestFilterUtil.getLocationInfo();
                    contactsInfo = requestFilterUtil.getContactsInfo();
                    IMEI = requestFilterUtil.getIMEI();
                    phoneNumber = requestFilterUtil.getPhoneNumber();
                    subscriberID = requestFilterUtil.getSubscriberID();
                    carrierName = requestFilterUtil.getCarrierName();
                    androidID = requestFilterUtil.getAndroidID();
                    macAdresses = requestFilterUtil.getMacAddresses();

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage request = (HttpMessage) httpObject;
                        if (request.headers().contains(CustomHeaderField)) {
                            applicationInfo = request.headers().get(CustomHeaderField);
                            request.headers().remove(CustomHeaderField);
                        }
                        if (request.headers().contains(HttpHeaderNames.ACCEPT_ENCODING)) {
                            request.headers().remove(HttpHeaderNames.ACCEPT_ENCODING);
                        }
                        if (!ProxyUtils.isCONNECT(request)
                                && request.headers().contains(HttpHeaderNames.HOST)) {
                            String hostName = ((HttpRequest) request).uri(); //request.headers().get(HttpHeaderNames.HOST).toLowerCase();
                            if (db.isDomainBlocked(hostName))
                                return getBlockedHostResponse(hostName);
                        }
                    }

                    String requestURI;
                    Set<RequestFilterUtil.FilterType> exfiltrated = new HashSet<>();

                    if (httpObject instanceof HttpRequest) {
                        HttpRequest request = (HttpRequest) httpObject;
                        requestURI = request.uri();
                        try {
                            requestURI = URLDecoder.decode(requestURI, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        if (locationInfo.length > 0) {
                            //tolerate location miscalculation
                            float latitude = Float.parseFloat(locationInfo[0]);
                            float longitude = Float.parseFloat(locationInfo[1]);
                            Matcher m = Pattern.compile("\\d+\\.\\d+").matcher(requestURI);
                            List<String> floats_in_uri = new ArrayList();
                            while (m.find()) {
                                floats_in_uri.add(m.group());
                            }
                            for (String s : floats_in_uri) {
                                if (Math.abs(Float.parseFloat(s) - latitude) < 0.5
                                        || Math.abs(Float.parseFloat(s) - longitude) < 0.1) {
                                    exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                                }
                            }
                        }
                        if (StringUtils.containsAny(requestURI, contactsInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                        }
                        if (StringUtils.containsAny(requestURI, macAdresses)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.MACADRESSES);
                        }
                        if (requestURI.contains(IMEI) && !IMEI.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.IMEI);
                        }
                        if (requestURI.contains(phoneNumber) && !phoneNumber.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.PHONENUMBER);
                        }
                        if (requestURI.contains(subscriberID) && !subscriberID.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.IMSI);
                        }
                        if (requestURI.contains(carrierName) && !carrierName.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CARRIERNAME);
                        }
                        if (requestURI.contains(androidID) && !androidID.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.ANDROIDID);
                        }
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            String contentStr = buf.toString(Charset.forName("UTF-8"));
                            if (locationInfo.length > 0) {
                                //tolerate location miscalculation
                                float latitude = Float.parseFloat(locationInfo[0]);
                                float longitude = Float.parseFloat(locationInfo[1]);
                                Matcher m = Pattern.compile("\\d+\\.\\d+").matcher(contentStr);
                                List<String> floats_in_uri = new ArrayList();
                                while (m.find()) {
                                    floats_in_uri.add(m.group());
                                }
                                for (String s : floats_in_uri) {
                                    if (Math.abs(Float.parseFloat(s) - latitude) < 0.5
                                            || Math.abs(Float.parseFloat(s) - longitude) < 0.1) {
                                        exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                                    }
                                }
                            }
                            if (StringUtils.containsAny(contentStr, contactsInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                            }
                            if (StringUtils.containsAny(contentStr, macAdresses)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.MACADRESSES);
                            }
                            if (contentStr.contains(IMEI) && !IMEI.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.IMEI);
                            }
                            if (contentStr.contains(phoneNumber) && !phoneNumber.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.PHONENUMBER);
                            }
                            if (contentStr.contains(subscriberID) && !subscriberID.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.IMSI);
                            }
                            if (contentStr.contains(carrierName) && !carrierName.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CARRIERNAME);
                            }
                            if (contentStr.contains(androidID) && !androidID.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.ANDROIDID);
                            }
                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }

                    //check exfiltrated list
                    if (!exfiltrated.isEmpty()) {
                        //retrieve all blocked and allowed domains
                        List<BlockedDomain> blocked = db.getAllBlockedDomains();
                        List<AllowedDomain> allowed = db.getAllAllowedDomains();
                        //get application name from app info
                        String appName = applicationInfo.replaceAll("\\(.+?\\)", "");
                        //check blocked domains
                        //if domain is stored as blocked, return a forbidden response
                        for (BlockedDomain b_dmn : blocked) {
                            if (b_dmn.info.equals(appName)) {
                                return getForbiddenRequestResponse(applicationInfo, exfiltrated);
                            }
                        }
                        //if domain is stored as allowed, return null for actual response
                        for (AllowedDomain a_dmn : allowed) {
                            if (a_dmn.info.equals(appName)) {
                                return null;
                            }
                        }
                        //get exfiltrated info to string array
                        String[] exfiltrated_array = new String[exfiltrated.size()];
                        int i = 0;
                        for (RequestFilterUtil.FilterType filter_type : exfiltrated) {
                            exfiltrated_array[i] = filter_type.name();
                            i++;
                        }
                        //retrieve all pending notifications
                        List<PendingNotification> pending = db.getAllPendingNotifications();
                        for (PendingNotification pending_notification : pending) {
                            //if pending notification includes specific app name and app permissions return response that a pending notification exists
                            if (pending_notification.app_info.equals(applicationInfo)) {
                                return getPendingResponse();
                            }
                        }
                        //if none pending notification exists, display a new notification
                        int notificationId = mainContext.getNotificationId();
                        mainContext.getNotificationUtil().displayExfiltratedNotification(getBaseContext(),
                                applicationInfo, exfiltrated, notificationId);
                        mainContext.setNotificationId(notificationId + 3);
                        //and update statistics
                        db.updateStatistics(exfiltrated);
                        return getAwaitingResponse();
                    }
                    return null;
                }
            };
        }
    };
}

From source file:org.openhab.binding.gpioremotecontrol.internal.GpioRemoteControlBinding.java

/**
 * @{inheritDoc}//from   w ww .  ja v  a 2s.com
 */
@Override
protected void internalReceiveCommand(String itemName, Command command) {
    // the code being executed when a command was sent on the openHAB
    // event bus goes here. This method is only called if one of the
    // BindingProviders provide a binding for the given 'itemName'.
    logger.debug("GpioRemoteControl: internalReceiveCommand({},{}) is called!", itemName, command);

    for (GpioRemoteControlBindingProvider provider : providers) {
        if (provider.getConfig(itemName).configMode != ConfigMode.OUTPUT) {
            logger.warn("The Item '{}' wasn't configured as output item. It can't receive any commands!",
                    itemName);
            return; //If it is not a output Item, stop here            
        }
        try {
            int pinNumber = provider.getConfig(itemName).pinConfiguration.getNumber();
            PinConfiguration pinConf = null;
            logger.debug("GpioRemoteControl: internalReceiveCommand: Event Auswahl folgt... "
                    + "ItemName: {}, Command: {}", itemName, command);
            if (command == OnOffType.ON || command.toString().toLowerCase().equals("on")) {
                pinConf = new PinConfiguration(Event.SET, pinNumber, true);
                provider.getConfig(itemName).pinConfiguration.setPwmValue(100);

            } else if (command == OnOffType.OFF || command.toString().toLowerCase().equals("off")) {
                pinConf = new PinConfiguration(Event.SET, pinNumber, false);
                provider.getConfig(itemName).pinConfiguration.setPwmValue(0);

            } else if (command.toString().toLowerCase().equals("toggle")) {
                pinConf = handleToggleCommand(provider, itemName, pinNumber, command);

            } else if (command == IncreaseDecreaseType.INCREASE
                    || command.toString().toLowerCase().equals("increase")) {
                provider.getConfig(itemName).pinConfiguration
                        .setPwmValue(provider.getConfig(itemName).pinConfiguration.getPwmValue() + 1);
                pinConf = new PinConfiguration(Event.DIM, pinNumber,
                        provider.getConfig(itemName).pinConfiguration.getPwmValue() + 1);

            } else if (command == IncreaseDecreaseType.DECREASE
                    || command.toString().toLowerCase().equals("decrease")) {
                provider.getConfig(itemName).pinConfiguration
                        .setPwmValue(provider.getConfig(itemName).pinConfiguration.getPwmValue() - 1);
                pinConf = new PinConfiguration(Event.DIM, pinNumber,
                        provider.getConfig(itemName).pinConfiguration.getPwmValue());

            } else if (command.toString().toLowerCase().contains("dim_")) {
                String[] split = command.toString().split("_");
                //Should be: 0:dim;1:pwmValue
                pinConf = new PinConfiguration(Event.DIM, pinNumber, Integer.parseInt(split[1]));
                provider.getConfig(itemName).pinConfiguration.setPwmValue(Integer.parseInt(split[1])); //Save value of PWM

            } else if (command.toString().toLowerCase().contains("fade_")) {
                pinConf = handleEvent(provider, itemName, pinNumber, command, Event.FADE);

            } else if (command.toString().toLowerCase().contains("fadeupdown_")) {
                pinConf = handleEvent(provider, itemName, pinNumber, command, Event.FADE_UP_DOWN);

            } else if (command.toString().toLowerCase().contains("blink_")) {
                pinConf = handleBlinkEvent(provider, itemName, pinNumber, command);

            } else {
                //parseable as Integer? 
                int tempPwmVal = Integer.parseUnsignedInt(command.toString());
                provider.getConfig(itemName).pinConfiguration.setPwmValue(tempPwmVal); //pinConfiguration.setPwmValue ensures the value is 0-100
                pinConf = new PinConfiguration(Event.DIM, pinNumber,
                        provider.getConfig(itemName).pinConfiguration.getPwmValue());
            }

            URI uriOfPin = new URI("ws://" + provider.getConfig(itemName).getHostWithPort());

            provider.getClientMap().get(uriOfPin).send(gson.toJson(pinConf)); //Send Command to Remote GPIO Pin
            //            provider.getClientMap().get(uriOfPin).send(gson.toJson("{\"event\":\"TEMP\",\"deviceId\":\"28-00044a72b1ff\"}"));
        } catch (IndexOutOfBoundsException e) {
            logger.warn(
                    "GpioRemoteControl: internalReceiveCommand: EventConfig not readable! Maybe wrong parameter in Sitemap? "
                            + "ItemName: {}, Command: {}",
                    itemName, command);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.openmrs.module.dataimporttool.TranslationManager.java

/**
 * This method generates insert query based on translation logic
 * /* ww  w  .  j  a  v a  2 s. c  o m*/
 * @param tuple
 * @param uuid
 * @param curr
 * @param top
 * @param currIndex
 * @return
 * @throws SystemException
 */
private synchronized String insertTuple(final TupleTree tree, final String uuid, final int currIndex)
        throws SystemException {
    skip = false;// reset skip to false
    String query = new SQL() {
        {
            TupleType tuple = tree.getHead();

            INSERT_INTO(tuple.getTable());
            // access matches of tuple
            for (MatchType match : tuple.getMatches()) {
                // if match default value is auto increment, skip it
                if (match.getDefaultValue().equals(MatchConstants.AI)) {
                    continue;
                }
                String selectQuery = null;// keep the composed select query

                // 1. If a match doesnt have the right side, it should
                // insert the default value
                if (match.getRight() == null) {
                    // 8. TOP  Should use the PK value of the parent tuple
                    String defaultValue = match.getDefaultValue().toString();
                    if (defaultValue.startsWith(MatchConstants.TOP)) {
                        // compute the type of top
                        int topType = (defaultValue.length() == 3) ? 1
                                : Integer.valueOf(defaultValue.substring(3));

                        TupleTree parentTree = tree;// parent tree is equal
                        // to current tree for
                        // now
                        for (int i = 0; i < topType; i++) {
                            parentTree = parentTree.getParent();// back to
                            // the
                            // desired
                            // parent
                        }
                        VALUES(match.getLeft().getColumn(), targetDAO.cast(parentTree.getTop()));
                    }
                    // 14. NOW  Should use the current system datetime
                    else if (match.getDefaultValue().equals(MatchConstants.NOW)) {
                        VALUES(match.getLeft().getColumn(), "NOW()");
                    } else {
                        // use default value
                        VALUES(match.getLeft().getColumn(), sourceDAO.cast(match.getDefaultValue()));
                    }
                } else {
                    selectQuery = selectMatch(match, tree);// generate

                    final List<List<Object>> results = sourceDAO.executeQuery(selectQuery);// execute select
                    // statement
                    // in case the database return more than one result, use
                    // the one at curr index
                    int rowIndex = (results.size() > 1) ? currIndex : 0;
                    Object value = null;
                    try {
                        value = results.get(rowIndex).get(0);// gets
                        // the
                        // database
                        // result
                    } catch (java.lang.IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        throw new SystemException("The # of results of the query: \"" + selectQuery
                                + "\" is not equal to the # of results of its CURRS. Found " + results.size()
                                + " results but expected " + (currIndex + 1) + " results or more. In match: "
                                + match.getId());
                    }
                    // in case the default value is AI_SKIP_TRUE or
                    // AI_SKIP_FALSE
                    if (match.getDefaultValue().equals(MatchConstants.AI_SKIP_TRUE)
                            || match.getDefaultValue().equals(MatchConstants.AI_SKIP_FALSE)) {
                        boolean boolValue = Boolean.valueOf(value.toString());
                        // 12.AI/SKIP/TRUE  Should skip the entire tuple if
                        // the value selected in the right side of the match
                        // is TRUE. Must use auto increment otherwise
                        if (match.getDefaultValue().equals(MatchConstants.AI_SKIP_TRUE) && boolValue) {
                            skip = true;// indicate that all the tuple must
                                        // be skipped
                            break;
                        }
                        // 13. AI/SKIP/FALSE  Should skip the entire tuple
                        // if the value selected in the right side of the
                        // match is FALSE. Must use auto increment
                        // otherwise.
                        else if (match.getDefaultValue().equals(MatchConstants.AI_SKIP_FALSE) && !boolValue) {
                            skip = true;// indicate that the entire tuple
                                        // must
                                        // be skipped
                            break;
                        } else {
                            continue;
                        }
                    }
                    // 5. If default value of a match is SKIP, the entire
                    // tuple must be skipped if the match select doesnt
                    // find any value.
                    // generate select statement
                    else if (match.getDefaultValue().equals(MatchConstants.SKIP) && value == null) {
                        skip = true;// indicate that all the tuple must be
                                    // skipped
                        break;
                    }
                    // 14. NOW  Should use the current system datetime
                    else if (match.getDefaultValue().equals(MatchConstants.NOW) && value == null) {
                        VALUES(match.getLeft().getColumn(), "NOW()");
                    }
                    // 4. If right side of the match is not required, it
                    // must insert default value in case the right side
                    // select doesnt find any value
                    else if (match.getRight().isIsRequired().equals(MatchConstants.NO) && value == null) {
                        // use default value
                        VALUES(match.getLeft().getColumn(), sourceDAO.cast(match.getDefaultValue()));
                    }
                    // 7. If there is a value match in a match, it must
                    // insert the value that the value match points to
                    else if (!match.getValueMatchId().equals(MatchConstants.NA)) {
                        Map<String, String> valueMatchGroup = ValueMatchType.valueMatches
                                .get(Integer.valueOf(match.getValueMatchId().toString()));
                        // log an error if value match group doesn't exist
                        if (valueMatchGroup == null) {
                            throw new SystemException(
                                    "An error ocurred during translation phase while processing value match group in match with id: "
                                            + match.getId() + ".\n Couldn't find group for id: " + value);
                        }
                        String valueMatch = valueMatchGroup.get(value.toString().toLowerCase());
                        // log an error if value match doesn't exist
                        if (valueMatch == null) {
                            // get the value of UNMATCHED match in case the
                            // value is not in the group
                            valueMatch = valueMatchGroup.get(MatchConstants.UNMATCHED.toLowerCase());
                            if (valueMatch == null) {
                                throw new SystemException(
                                        "An error ocurred during translation phase while processing value match in match with id: "
                                                + match.getId() + ".\n Couldn't find match for value: "
                                                + value);
                            }
                            // SKIP entire tuple if value match is SKIP
                            if (valueMatch.equalsIgnoreCase(MatchConstants.SKIP)) {
                                skip = true;// indicate that all the tuple
                                            // must be skipped
                                break;
                            }
                        }
                        VALUES(match.getLeft().getColumn(), sourceDAO.cast(valueMatch));
                    } else {
                        VALUES(match.getLeft().getColumn(), de.enforce(match.getLeft().getDatatype(), value));
                    }
                }
            }
            // foreign key columns
            if (!skip) {
                for (ReferenceType reference : tuple.getReferences().values()) {
                    // check if reference is direct
                    if (reference.getReferencee().getTable().equalsIgnoreCase(tuple.getTable())) {
                        String referencedValue = reference.getReferencedValue().toString();
                        // 8. TOP  Should use the PK value of the parent
                        // tuple
                        if (referencedValue.startsWith(MatchConstants.TOP)) {
                            // compute the type of top

                            TupleTree parentTree = tree;// parent tree is
                            // equal to current
                            // tree for now
                            // find the parent
                            while (true) {
                                parentTree = parentTree.getParent();// back
                                // to
                                // the
                                // desired
                                // parent
                                if (reference.getReferenced().getTable()
                                        .equalsIgnoreCase(parentTree.getHead().getTable())) {
                                    break;
                                }
                            }
                            VALUES(reference.getReferencee().getColumn(), targetDAO.cast(parentTree.getTop()));
                        } else {
                            // use default value
                            VALUES(reference.getReferencee().getColumn(), targetDAO.cast(referencedValue));
                        }
                    }
                }
                // metadata
                VALUES("creator", sourceDAO.cast(1));
                VALUES("date_created", "NOW()");
                if (!tuple.getTable().equalsIgnoreCase("PROVIDER"))
                    VALUES("voided", sourceDAO.cast(0));
                // avoid PATIENT table
                if (!tuple.getTable().equalsIgnoreCase("PATIENT"))
                    VALUES("uuid", sourceDAO.cast(uuid));
            }
        }
    }.toString();
    // check whether or not the query was skipped
    if (skip)
        return "";
    return query;
}

From source file:org.geometerplus.android.fbreader.QuotesFragmentActivity.java

private void postMassage(Quote quote) {
    Bundle parameters = new Bundle();
    final Book book = myCollection.getBookById(quote.getBookId());
    String text;// w w w . jav a2s. co m
    try {
        //if(book.authors().get(0)!=null && book.authors().get(0).DisplayName != null)
        text = "\"" + quote.getText() + "\"" + " (c) " + quote.getBookTitle() + ", "
                + book.authors().get(0).DisplayName;
    } catch (IndexOutOfBoundsException e) {
        ///else
        text = "\"" + quote.getText() + "\"" + " (c) " + quote.getBookTitle();
    }
    parameters.putString("message", text);
    try {
        facebook.request("me/feed", parameters, "POST");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}