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:edu.hawaii.soest.pacioos.text.SimpleTextSource.java

/**
 *  return the sample observation date given minimal sample metadata
 *//*from   ww  w  .j ava  2  s  . c  o m*/
public Date getSampleDate(String line) throws ParseException {

    /*
     * Date time formats and field locations are highly dependent on instrument
     * output settings.  The -d and -f options are used to set dateFormats and dateFields,
     * or in the XML-based configuration file
     * 
     * this.dateFormats will look something like {"yyyy-MM-dd", "HH:mm:ss"} or 
     * {"yyyy-MM-dd HH:mm:ss"} or {"yyyy", "MM", "dd", "HH", "mm", "ss"}
     * 
     * this.dateFields will also look something like {1,2} or {1} or {1, 2, 3, 4, 5, 6}
     * 
     * NS01 sample:
     * # 26.1675,  4.93111,    0.695, 0.1918, 0.1163,  31.4138, 09 Dec 2012 15:46:55
     * NS03 sample:
     * #  25.4746,  5.39169,    0.401,  35.2570, 09 Dec 2012, 15:44:36
     */
    // extract the date from the data line
    SimpleDateFormat dateFormat;
    String dateFormatStr = "";
    String dateString = "";
    String[] columns = line.trim().split(this.delimiter);
    log.debug("Delimiter is: " + this.delimiter);
    log.debug(Arrays.toString(columns));
    Date sampleDate = new Date();
    // build the total date format from the individual fields listed in dateFields
    int index = 0;
    if (this.dateFields != null && this.dateFormats != null) {
        for (Integer dateField : this.dateFields) {
            try {
                dateFormatStr += this.dateFormats.get(index); //zero-based list
                dateString += columns[dateField.intValue() - 1].trim(); //zero-based list
            } catch (IndexOutOfBoundsException e) {
                String msg = "There was an error parsing the date from the sample using the date format '"
                        + dateFormatStr + "' and the date field index of " + dateField.intValue();
                if (log.isDebugEnabled()) {
                    e.printStackTrace();
                }
                throw new ParseException(msg, 0);
            }
            index++;
        }
        log.debug("Using date format string: " + dateFormatStr);
        log.debug("Using date string       : " + dateString);
        log.debug("Using time zone         : " + this.timezone);

        this.tz = TimeZone.getTimeZone(this.timezone);
        if (this.dateFormats == null || this.dateFields == null) {
            log.warn("Using the default datetime field for sample data.");
            dateFormat = this.defaultDateFormat;
        }
        // init the date formatter
        dateFormat = new SimpleDateFormat(dateFormatStr);
        dateFormat.setTimeZone(this.tz);

        // parse the date string
        sampleDate = dateFormat.parse(dateString.trim());
    } else {
        log.info("No date formats or date fields were configured. Using the current date for this sample.");
    }

    return sampleDate;
}

From source file:com.heliumv.api.order.OrderApi.java

@GET
@Path("offline")
@Produces({ FORMAT_JSON, FORMAT_XML })//from w  ww . jav  a 2  s . c om
public OfflineOrderEntry getOfflineOrders(@HeaderParam(ParamInHeader.TOKEN) String headerUserId,
        @QueryParam(Param.USERID) String userId, @QueryParam(Param.LIMIT) Integer limit,
        @QueryParam(Param.STARTINDEX) Integer startIndex, @QueryParam("filter_cnr") String filterCnr,
        @QueryParam("filter_customer") String filterCustomer,
        @QueryParam("filter_delivery_customer") String filterDeliveryCustomer,
        @QueryParam("filter_project") String filterProject,
        @QueryParam("filter_withHidden") Boolean filterWithHidden) {
    OfflineOrderEntry entry = new OfflineOrderEntry();

    try {
        if (null == connectClient(headerUserId, userId))
            return entry;
        if (!mandantCall.hasModulAuftrag()) {
            respondNotFound();
            return entry;
        }

        FilterKriteriumCollector collector = new FilterKriteriumCollector();
        collector.add(offlineOrderQuery.getFilterCnr(StringHelper.removeXssDelimiters(filterCnr)));
        collector.add(offlineOrderQuery.getFilterProject(StringHelper.removeXssDelimiters(filterProject)));
        collector.add(offlineOrderQuery.getFilterCustomer(StringHelper.removeXssDelimiters(filterCustomer)));
        collector.add(offlineOrderQuery
                .getFilterDeliveryCustomer(StringHelper.removeXssDelimiters(filterDeliveryCustomer)));
        collector.add(offlineOrderQuery.getFilterWithHidden(filterWithHidden));
        FilterBlock filterCrits = new FilterBlock(collector.asArray(), "AND");

        QueryParametersFeatures params = offlineOrderQuery.getFeatureQueryParameters(filterCrits);
        params.setLimit(limit);
        params.setKeyOfSelectedRow(startIndex);
        params.addFeature(AuftragHandlerFeature.ADRESSE_KOMPLETT);
        params.addFeature(AuftragHandlerFeature.ADRESSE_ANSCHRIFT);
        params.addFeature(AuftragHandlerFeature.ADRESSE_IST_LIEFERADRESSE);
        AuftragQueryResult result = (AuftragQueryResult) offlineOrderQuery.setQuery(params);

        List<OrderEntry> orders = offlineOrderQuery.getResultList(result);
        List<OrderpositionsEntry> positions = new ArrayList<OrderpositionsEntry>();
        HashMap<String, IAddressContact> distinctAddresses = new HashMap<String, IAddressContact>();

        int orderIndex = 0;

        for (OrderEntry orderEntry : orders) {
            collector = new FilterKriteriumCollector();
            collector.add(orderPositionQuery.getOrderIdFilter(orderEntry.getId()));
            collector.add(orderPositionQuery.getIsIdentFilter());
            filterCrits = new FilterBlock(collector.asArray(), "AND");

            QueryParameters posParams = orderPositionQuery.getDefaultQueryParameters(filterCrits);
            posParams.setLimit(Integer.MAX_VALUE);
            posParams.setKeyOfSelectedRow(0);

            QueryResult positionResult = orderPositionQuery.setQuery(posParams);
            List<OrderpositionEntry> posEntries = orderPositionQuery.getResultList(positionResult);

            addPositionEntries(positions, orderEntry.getId(), posEntries);

            try {
                IAddressContact orderAddress = result.getFlrData()[orderIndex].getAddressContact();
                distinctAddresses.put(orderAddress.getPartnerAddress().getPartnerId().toString()
                        + (orderAddress.getContactAddress() != null
                                ? ("|" + orderAddress.getContactAddress().getPartnerId().toString())
                                : ""),
                        orderAddress);
            } catch (IndexOutOfBoundsException e) {
            }

            ++orderIndex;
        }
        entry.setOrders(orders);
        entry.setOrderpositions(positions);

        List<OrderAddressContact> resultAddresses = new ArrayList<OrderAddressContact>();
        for (IAddressContact orderAddress : distinctAddresses.values()) {
            //            OrderAddressContact newAddress = modelMapper.map(orderAddress, OrderAddressContact.class) ;
            OrderAddressContact newAddress = new OrderAddressContact();
            newAddress.setPartnerAddress(modelMapper.map(orderAddress.getPartnerAddress(), OrderAddress.class));
            if (orderAddress.getContactAddress() != null) {
                newAddress.setContactAddress(
                        modelMapper.map(orderAddress.getContactAddress(), OrderAddress.class));
            }
            resultAddresses.add(newAddress);
        }
        entry.setAddresses(resultAddresses);

    } catch (NamingException e) {
        respondUnavailable(e);
        e.printStackTrace();
    } catch (RemoteException e) {
        respondUnavailable(e);
        e.printStackTrace();
    } catch (EJBExceptionLP e) {
        respondBadRequest(e);
    }

    return entry;
}

From source file:webServices.RestServiceImpl.java

@POST
@Path("/saveMap/{host}/{endpoint}/{title}/{creator}/{license}/{theme}/{description}/{port}/{user}/{pass}/{mapId}")
@Consumes({ MediaType.WILDCARD, MediaType.APPLICATION_JSON })
@Produces({ MediaType.TEXT_PLAIN })// w  ww.  j av  a2s.  co  m
public String saveMap(String mapInfo, @PathParam("host") String host, @PathParam("endpoint") String endpoint,
        @PathParam("title") String title, @PathParam("creator") String creator,
        @PathParam("license") String license, @PathParam("theme") String theme,
        @PathParam("description") String description, @PathParam("port") int port,
        @PathParam("user") String user, @PathParam("pass") String pass, @PathParam("mapId") String mapId) {

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date date = new Date();

    //Generate folders for map files
    File dir = new File(context.getRealPath("/") + MAPONTOLOGYFOLDER);
    dir.mkdir();
    String filename = context.getRealPath("/") + MAPONTOLOGYFOLDER + title + "_map.nt";

    String layersInfo = mapInfo.substring(0, mapInfo.indexOf("@@@"));
    String geosparql = mapInfo.substring(mapInfo.indexOf("###") + 3, mapInfo.indexOf("!!!"));
    String userAddedInfo = null;
    String chartsInfo = null;
    try {
        chartsInfo = mapInfo.substring(mapInfo.indexOf("@@@") + 3, mapInfo.indexOf("###"));
        userAddedInfo = mapInfo.substring(mapInfo.indexOf("!!!") + 3, mapInfo.length());
    } catch (IndexOutOfBoundsException e) {
        e.printStackTrace();
    }

    //Parse layers' information
    Vector<Layer> layers = parseLayersInfo(layersInfo);

    //Create new mapID or keep the existing one. Also add creation/modification date
    String mapID = mapId;
    String createDate;
    String modifyDate;

    if (mapId.equalsIgnoreCase("empty")) {
        mapID = createNewMapId();
        createDate = dateFormat.format(date);
        modifyDate = dateFormat.format(date);
    } else {
        //Get create day from query and set modify date
        try {
            createDate = endpointStore.getMapCreateDate(mapID, host, endpoint, port);
            if (createDate.equalsIgnoreCase("none")) {
                createDate = dateFormat.format(date);
            }
        } catch (EndpointCommunicationException e) {
            e.printStackTrace();
            createDate = dateFormat.format(date);
        }

        modifyDate = dateFormat.format(date);
    }

    memoryStore.setMapID(mapID);

    //Save each layer
    for (int i = 0; i < layers.size(); i++) {
        memoryStore.saveLayer(i, layers.get(i).getQueryText(), layers.get(i).getUri(), layers.get(i).getName(),
                layers.get(i).getEndpoint(), layers.get(i).getFillColor(), layers.get(i).getStrokeColor(),
                layers.get(i).getIconUri(), layers.get(i).getIconSize(), layers.get(i).getIsTemp(),
                layers.get(i).getImageBox(), layers.get(i).getType(), title, creator, license, theme,
                createDate, modifyDate, geosparql, description);
    }

    //Parse charts' information
    if (chartsInfo != null) {
        Vector<Chart> charts = parseChartsInfo(chartsInfo);
        for (int i = 0; i < charts.size(); i++) {
            memoryStore.saveChart(i, charts.get(i).getQuery(), charts.get(i).getEndpoint(),
                    charts.get(i).getType(), charts.get(i).getMeasures(), charts.get(i).getFreeDims(),
                    charts.get(i).getInstances());
        }
    }

    //Create user added information KML file
    if (userAddedInfo != null) {
        // generate folder for kml files
        dir = new File(context.getRealPath("/") + STORE_FOLDER);
        dir.mkdir();

        try {
            PrintWriter out = new PrintWriter(context.getRealPath("/") + STORE_FOLDER + mapID + "userInfo.kml");
            out.println(userAddedInfo);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    memoryStore.storeFileToDisk(filename);

    endpointStore.saveMapToEndpoint(filename, mapID, host, endpoint, port, user, pass);

    return mapID + "," + host + "/" + endpoint + "," + createDate + "," + modifyDate;
}

From source file:org.dcm4chee.proxy.forward.ForwardFiles.java

private FileFilter fileFilter(final ProxyAEExtension proxyAEE, final String calledAET) {
    final long now = System.currentTimeMillis();
    return new FileFilter() {

        @Override/*from www  .  j av a 2 s .c o m*/
        public boolean accept(File file) {
            String path = file.getPath();
            int interval = proxyAEE.getApplicationEntity().getDevice()
                    .getDeviceExtension(ProxyDeviceExtension.class).getSchedulerInterval();
            if (path.endsWith(".dcm") || path.endsWith(".nevent")) {
                if (now > (file.lastModified() + interval))
                    return true;
                else
                    return false;
            }

            if (path.endsWith(".part") || path.endsWith(".snd") || path.endsWith(".info")
                    || path.endsWith(".naction"))
                return false;

            try {
                LOG.debug("Get matching retry for file " + file.getPath());
                String suffix = path.substring(path.lastIndexOf('.'));
                Retry matchingRetry = getMatchingRetry(proxyAEE, suffix);
                if (matchingRetry == null)
                    if (proxyAEE.isDeleteFailedDataWithoutRetryConfiguration())
                        deleteFailedFile(proxyAEE, calledAET, file,
                                ": delete files without retry configuration is ENABLED", 0);
                    else
                        moveToNoRetryPath(proxyAEE, calledAET, file,
                                ": delete files without retry configuration is DISABLED");
                else if (checkNumberOfRetries(proxyAEE, matchingRetry, suffix, file, calledAET)
                        && checkSendFileDelay(now, file, matchingRetry))
                    return true;
            } catch (IndexOutOfBoundsException e) {
                LOG.error("Error parsing suffix of " + path);
                try {
                    moveToNoRetryPath(proxyAEE, calledAET, file, "(error parsing suffix)");
                } catch (IOException e1) {
                    LOG.error("Error moving file {} to no retry directory: {}",
                            new Object[] { file.getName(), e.getMessage() });
                    if (LOG.isDebugEnabled())
                        e1.printStackTrace();
                }
            } catch (IOException e) {
                LOG.error("Error reading from directory: {}", e.getMessage());
                if (LOG.isDebugEnabled())
                    e.printStackTrace();
            }
            return false;
        }

        private boolean checkSendFileDelay(final long now, File file, Retry matchingRetry) {
            boolean sendNow = now > (file.lastModified() + (matchingRetry.delay * 1000));
            if (sendNow)
                LOG.debug(">> ready to send now");
            else
                LOG.debug(">> wait until last send delay > {}sec", matchingRetry.delay);
            return sendNow;
        }
    };
}

From source file:com.adafruit.bluefruit.le.connect.app.MainActivity.java

private void decodeScanRecords(BluetoothDeviceData deviceData) {
    // based on http://stackoverflow.com/questions/24003777/read-advertisement-packet-in-android
    final byte[] scanRecord = deviceData.scanRecord;

    ArrayList<UUID> uuids = new ArrayList<>();
    byte[] advertisedData = Arrays.copyOf(scanRecord, scanRecord.length);
    int offset = 0;
    deviceData.type = BluetoothDeviceData.kType_Unknown;

    // Check if is an iBeacon ( 0x02, 0x0x1, a flag byte, 0x1A, 0xFF, manufacturer (2bytes), 0x02, 0x15)
    final boolean isBeacon = advertisedData[0] == 0x02 && advertisedData[1] == 0x01 && advertisedData[3] == 0x1A
            && advertisedData[4] == (byte) 0xFF && advertisedData[7] == 0x02 && advertisedData[8] == 0x15;

    // Check if is an URIBeacon
    final byte[] kUriBeaconPrefix = { 0x03, 0x03, (byte) 0xD8, (byte) 0xFE };
    final boolean isUriBeacon = Arrays.equals(Arrays.copyOf(scanRecord, kUriBeaconPrefix.length),
            kUriBeaconPrefix) && advertisedData[5] == 0x16 && advertisedData[6] == kUriBeaconPrefix[2]
            && advertisedData[7] == kUriBeaconPrefix[3];

    if (isBeacon) {
        deviceData.type = BluetoothDeviceData.kType_Beacon;

        // Read uuid
        offset = 9;//from  ww w.jav a 2  s. c o m
        UUID uuid = BleUtils.getUuidFromByteArrayBigEndian(Arrays.copyOfRange(scanRecord, offset, offset + 16));
        uuids.add(uuid);
        offset += 16;

        // Skip major minor
        offset += 2 * 2; // major, minor

        // Read txpower
        final int txPower = advertisedData[offset++];
        deviceData.txPower = txPower;
    } else if (isUriBeacon) {
        deviceData.type = BluetoothDeviceData.kType_UriBeacon;

        // Read txpower
        final int txPower = advertisedData[9];
        deviceData.txPower = txPower;
    } else {
        // Read standard advertising packet
        while (offset < advertisedData.length - 2) {
            // Length
            int len = advertisedData[offset++];
            if (len == 0)
                break;

            // Type
            int type = advertisedData[offset++];
            if (type == 0)
                break;

            // Data
            //            Log.d(TAG, "record -> lenght: " + length + " type:" + type + " data" + data);

            switch (type) {
            case 0x02: // Partial list of 16-bit UUIDs
            case 0x03: { // Complete list of 16-bit UUIDs
                while (len > 1) {
                    int uuid16 = advertisedData[offset++] & 0xFF;
                    uuid16 |= (advertisedData[offset++] << 8);
                    len -= 2;
                    uuids.add(UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", uuid16)));
                }
                break;
            }

            case 0x06: // Partial list of 128-bit UUIDs
            case 0x07: { // Complete list of 128-bit UUIDs
                while (len >= 16) {
                    try {
                        // Wrap the advertised bits and order them.
                        UUID uuid = BleUtils.getUuidFromByteArraLittleEndian(
                                Arrays.copyOfRange(advertisedData, offset, offset + 16));
                        uuids.add(uuid);

                    } catch (IndexOutOfBoundsException e) {
                        Log.e(TAG, "BlueToothDeviceFilter.parseUUID: " + e.toString());
                    } finally {
                        // Move the offset to read the next uuid.
                        offset += 16;
                        len -= 16;
                    }
                }
                break;
            }

            case 0x09: {
                byte[] nameBytes = new byte[len - 1];
                for (int i = 0; i < len - 1; i++) {
                    nameBytes[i] = advertisedData[offset++];
                }

                String name = null;
                try {
                    name = new String(nameBytes, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                deviceData.advertisedName = name;
                break;
            }

            case 0x0A: { // TX Power
                final int txPower = advertisedData[offset++];
                deviceData.txPower = txPower;
                break;
            }

            default: {
                offset += (len - 1);
                break;
            }
            }
        }

        // Check if Uart is contained in the uuids
        boolean isUart = false;
        for (UUID uuid : uuids) {
            if (uuid.toString().equalsIgnoreCase(UartInterfaceActivity.UUID_SERVICE)) {
                isUart = true;
                break;
            }
        }
        if (isUart) {
            deviceData.type = BluetoothDeviceData.kType_Uart;
        }
    }

    deviceData.uuids = uuids;
}

From source file:com.hygenics.parser.ForceConformity.java

private void iter() {
    log.info("Starting Enforcement @ " + Calendar.getInstance().getTime().toString() + " | UTC "
            + Calendar.getInstance().getTimeInMillis());

    String sql;//w w  w. java2 s  . c o m
    boolean add = true;
    ArrayList<String> columns = null;
    ArrayList<String> tablecolumns = null;
    Quicksort<String> qs = new Quicksort<String>();
    Levenshtein lev = new Levenshtein();

    // iterate through each table
    for (String table : schema_columns.keySet()) {

        log.info("Checking for Table Existance " + table);
        String schema = null;

        try {
            schema = table.split("\\.")[0];
        } catch (IndexOutOfBoundsException e) {
            try {
                throw new SQLMalformedException("FATAL ERROR: Table name " + table + " malformed");
            } catch (SQLMalformedException e2) {
                e2.printStackTrace();
                System.exit(-1);
            }
        }

        log.info("Checking  table: " + table + "&& schema: " + schema);

        if (template.checkTable(table, schema)) {

            log.info("Conforming: " + table);
            // get the arraylist
            tablecolumns = template.getColumns(table);

            if (insensitive == true) {
                for (int i = 0; i < tablecolumns.size(); i++) {
                    tablecolumns.set(i, tablecolumns.get(i).toLowerCase());
                }
            }

            columns = (ArrayList<String>) schema_columns.get(table);

            if (insensitive == true) {
                for (int i = 0; i < columns.size(); i++) {
                    columns.set(i, columns.get(i).toLowerCase());
                }
            }

            if (exclude != null) {
                // remove unmatchable columns
                if (exclude.size() > 0) {
                    for (String col : exclude) {
                        tablecolumns.remove(col);
                        columns.remove(col);
                    }
                }
            }

            // sort each arraylist
            qs.setTosortlist(columns);
            columns = qs.sort();

            qs.setTosortlist(tablecolumns);
            tablecolumns = qs.sort();
            // check each remaining column
            for (int i = 0; i < columns.size(); i++) {

                if (tablecolumns.contains(columns.get(i).trim()) == false || (insensitive == true
                        && tablecolumns.contains(columns.get(i).toLowerCase().trim()) == false)) {

                    if (correct) {
                        int dist = Levenshtein.getLevenshteinDistance(tablecolumns.get(i), columns.get(i));
                        add = false;
                        log.info("Distance was " + dist + " Cutoff is " + levcutoff);

                        // check lev. distances if requested and ensure some
                        // match with fuzzy (use at your own risk)
                        if (levcutoff > -1 & dist <= levcutoff) {

                            log.info("Approximate Match: Correcting Column");

                            // if distance is within 1 or specified
                            // distances, correct it
                            sql = "ALTER TABLE " + table + " RENAME COLUMN " + tablecolumns.get(i) + " TO "
                                    + columns.get(i);
                            template.execute(sql);

                            // get the table columns
                            tablecolumns = template.getColumns(table);
                            qs.setTosortlist(tablecolumns);
                            tablecolumns = qs.sort();

                        } else {
                            add = true;
                        }
                    }

                    if (add) {
                        // add column if necessary
                        sql = "Alter Table " + table + " ADD COLUMN " + columns.get(i) + " text";
                        template.execute(sql);

                        // get the table columns again and resort them
                        tablecolumns = template.getColumns(table);

                        if (exclude != null) {
                            if (exclude.size() > 0) {
                                for (String ex : exclude) {
                                    tablecolumns.remove(ex);
                                    columns.remove(ex);
                                }
                            }
                        }

                        qs.setTosortlist(tablecolumns);
                        tablecolumns = qs.sort();
                    }
                    // iterate backward so that the integrety is assured
                    i--;
                }
            }
        } else {
            try {
                throw new SQLMalformedException("WARNING: Table " + table + " is missing");
            } catch (SQLMalformedException e) {
                e.printStackTrace();
            }
        }

    }
    log.info("Finishing Enforcement @ " + Calendar.getInstance().getTime().toString() + " | UTC "
            + Calendar.getInstance().getTimeInMillis());

}

From source file:de.dfki.iui.mmds.scxml.engine.impl.SCXMLEngineImpl.java

/**
 * Instantiate and initialize the underlying executor instance.
 * //www . j  ava  2s. co  m
 * @param stateMachine
 *            The state machine
 * @param topicInfix
 * @param rootCtx
 *            The root context
 * @param evaluator
 *            The expression evaluator
 * @param dispatcher
 */
private void initialize(final SCXML stateMachine, String idSuffix, final Context rootCtx,
        final Evaluator evaluator, EventDispatcher dispatcher, final ErrorReporter errorReporter) {
    engine = new SCXMLExecutor(evaluator, dispatcher, new SimpleErrorReporter());
    engine.setStateMachine(stateMachine);
    engine.setSuperStep(true);
    engine.setRootContext(rootCtx);
    engine.addListener(stateMachine, new EntryListener());
    engine.registerInvokerClass("scxml", SimpleSCXMLInvoker.class);

    // engine.registerInvokerClass("grounding", GroundingInvoker.class);

    // setId(stateMachine.getId());
    String topicId = stateMachine.getId() + idSuffix;
    setId(topicId);
    EventHandler handler = new EventHandler() {

        @Override
        public void handleEvent(Event event) {
            if (event instanceof SCXMLEventFiredEvent) {
                // logInfo( "Scxml event 'SCXMLEventFiredEvent' received!"
                // );
                fireEvent(((SCXMLEventFiredEvent) event).getEvent(), null);
            }
        }
    };
    serviceRegs.add(SCXMLEngineActivator.registerEventHandler(handler, SCXMLEventFiredEvent.getTopic(topicId)));
    handlers.add(handler);

    // One event handler to listen for macro/micro step instructions
    handler = new EventHandler() {
        @Override
        public void handleEvent(Event event) {
            // logInfo( "Scxml event 'SCXMLMacroMicroStepEvent' received!"
            // );
            engine.setSuperStep(SCXMLMacroMicroStepEvent.isMacroStepEvent(event));
            String ev = ((SCXMLMacroMicroStepEvent) event).getEvent();
            if (ev == null) {
                resume();
            } else {
                fireEvent(ev, null);
            }
        }
    };
    serviceRegs.add(SCXMLEngineActivator.registerEventHandler(handler,
            SCXMLMacroMicroStepEvent.getTopic(topicId, SCXMLMacroMicroStepEvent.TOPIC_SUFFIX_MACRO)));
    serviceRegs.add(SCXMLEngineActivator.registerEventHandler(handler,
            SCXMLMacroMicroStepEvent.getTopic(topicId, SCXMLMacroMicroStepEvent.TOPIC_SUFFIX_MICRO)));
    handlers.add(handler);

    // a handler for the transition cond evaluation/change events
    handler = new EventHandler() {

        public Transition findTransition(SCXMLTransitionEvent ev) {
            String stateId = ev.getStateId();
            for (TransitionTarget tt : engine.getCurrentStatus().getAllStates()) {
                if (tt.getId().equals(stateId)) {
                    try {
                        // the state is found, now take a look at the
                        // transitions
                        return tt.getTransitionsList().get(ev.getTransPos());
                    } catch (IndexOutOfBoundsException e) {
                        logError(e);
                    }
                }
            }
            return null;
        }

        @Override
        public void handleEvent(Event event) {
            if (SCXMLTransitionEvent.isEvalTransitionCondEvent(event)) {
                // logInfo( "Scxml event 'SCXMLTransitionEvent' received!"
                // );
                SCXMLTransitionEvent ev = (SCXMLTransitionEvent) event;
                Transition t = findTransition(ev);
                if (t != null) {
                    try {
                        String cond = t.getCond();
                        boolean evalResult = engine.getEvaluator()
                                .evalCond(engine.getSCInstance().getContext(t.getParent()), cond);

                        // now send the complete current state
                        Map<String, Map<String, List<Object[]>>> currentState = getAvailableEventsStates();
                        for (Map<String, List<Object[]>> evVal : currentState.values()) {
                            for (List<Object[]> stateVal : evVal.values()) {
                                for (Object[] values : stateVal) {
                                    if (values[0] instanceof Integer && values[1].equals(cond)) {
                                        // set the evaluation result
                                        values[2] = evalResult ? 1 : 0;
                                    }
                                }
                            }
                        }
                        // logInfo( "Send 'Active states'" );
                        SCXMLEngineActivator.sendActiveStates(id, getActiveStates(), getAllActiveStates());
                        // logInfo( "Send 'Scxml state'" );
                        SCXMLEngineActivator.sendScxmlState(id, State.IDLE, currentState);
                    } catch (SCXMLExpressionException e) {
                        logError(e);
                    }
                }
            } else if (SCXMLChangeTransitionCondEvent.isChangeTransitionCondEvent(event)) {
                // logInfo(
                // "Scxml event 'SCXMLChangeTransitionCondEvent' received!"
                // );
                SCXMLChangeTransitionCondEvent ev = (SCXMLChangeTransitionCondEvent) event;
                Transition t = findTransition(ev);
                if (t != null) {
                    t.setCond(ev.getNewCond());
                }
            }
        }
    };
    serviceRegs.add(SCXMLEngineActivator.registerEventHandler(handler,
            SCXMLTransitionEvent.getTopic(topicId, SCXMLTransitionEvent.Sort.COND)));
    handlers.add(handler);

    // a handler for the change of data values
    handler = new EventHandler() {

        @Override
        public void handleEvent(Event event) {
            if (event instanceof SCXMLChangeDataValueEvent) {
                // logInfo(
                // "Scxml event 'SCXMLChangeDataValueEvent' received!" );
                SCXMLChangeDataValueEvent ev = (SCXMLChangeDataValueEvent) event;
                String stateId = ev.getStateId();
                for (TransitionTarget tt : engine.getCurrentStatus().getAllStates()) {
                    if (tt.getId().equals(stateId)) {
                        try {
                            // here comes a 'silent' change of the content,
                            // i.e. there is no event 'dataId.change' sent
                            Context ctxt = engine.getSCInstance().getContext(tt);
                            Object result = engine.getEvaluator().eval(ctxt, ev.getValueScript());
                            String dataId = ev.getDataId();
                            ctxt.set(dataId, result);

                            // now send the complete current state
                            Map<String, Map<String, List<Object[]>>> currentState = getAvailableEventsStates();
                            for (Map<String, List<Object[]>> val : currentState.values()) {
                                for (List<Object[]> state : val.values()) {
                                    for (Object[] values : state) {
                                        if (values[0].equals(dataId)) {
                                            // indicate that the value
                                            // changed
                                            values[2] = true;
                                        }
                                    }
                                }
                            }

                            // logInfo( "Send 'Active states'" );
                            SCXMLEngineActivator.sendActiveStates(id, getActiveStates(), getAllActiveStates());
                            // logInfo( "Send 'Scxml state'" );
                            SCXMLEngineActivator.sendScxmlState(id, State.IDLE, currentState);

                            return;
                        } catch (SCXMLExpressionException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    };
    serviceRegs.add(
            SCXMLEngineActivator.registerEventHandler(handler, SCXMLChangeDataValueEvent.getTopic(topicId)));
    handlers.add(handler);
}

From source file:com.cecs492a_group4.sp.SingleEvent.java

public synchronized void getYelpSearchResult(final int index1, final String searchToken, final String Address)
        throws InterruptedException {
    Thread thread = new Thread(new Runnable() {
        @Override/*  w  w  w . ja  va 2 s . c o m*/
        public void run() {
            int randPick = ran.nextInt(limit);
            try {
                String name = "ldkfldsjkfd";
                int full = 0;
                do {

                    randPick = ran.nextInt(limit);
                    System.out.println("Event number : " + index1);
                    System.out.println(randPick);
                    System.out.println("Index: " + randPick);
                    response = yelp.searchByLocation(searchToken, Address, SingleEvent.currentRadius);
                    System.out.println("The current radius : " + SingleEvent.currentRadius);
                    System.out.println(searchToken + " gave me this response: " + response);
                    yp.setResponse(response);
                    // yp.parseBusiness();

                    int nameSIndex = response.indexOf("\"name\"", 1) + 8;

                    for (int i = 0; i < randPick; i++) {
                        nameSIndex = response.indexOf("\"name\"", ++nameSIndex) + 8;
                    }
                    int nameEIndex = response.indexOf("\",", ++nameSIndex);

                    String tmp = response;
                    name = tmp.substring(nameSIndex, nameEIndex);
                    System.out.println(name);
                    full++;
                    if (full >= 4) {
                        full = 0;
                        bussinessNames.clear(); //no more options reset array
                    }
                } while (bussinessNames.contains(name));

                try {
                    bussinessNames.add(index1, name);
                } catch (IndexOutOfBoundsException e) {
                    System.out.println("Array size " + bussinessNames.size());
                    bussinessNames.clear();
                }
                int imgSIndex = response.indexOf("\"image_url\"", 1) + 13;
                int ratingSIndex = response.indexOf("\"rating_img_url\"", 1) + 18;
                int urlSIndex = response.indexOf("\"mobile_url\"", 1) + 14;
                int phoneSIndex = response.indexOf("\"phone\":", 1) + 9;
                int addressSIndex = response.indexOf("\"display_address\"", 1) + 19;
                int distanceSIndex = response.indexOf("\"distance\"", 1) + 12;
                System.out.println("Start index :" + distanceSIndex);
                for (int i = 0; i < randPick; i++) {

                    imgSIndex = response.indexOf("\"image_url\"", ++imgSIndex) + 13;
                    ratingSIndex = response.indexOf("\"rating_img_url\"", ++ratingSIndex) + 18;
                    urlSIndex = response.indexOf("\"mobile_url\"", ++urlSIndex) + 14;
                    phoneSIndex = response.indexOf("\"phone\":", ++phoneSIndex) + 9;
                    addressSIndex = response.indexOf("\"display_address\"", ++addressSIndex) + 19;
                    distanceSIndex = response.indexOf("\"distance\"", ++distanceSIndex) + 12;
                }

                int ratingEIndex = response.indexOf("g\"", ++ratingSIndex) + 1;
                int imgEIndex = response.indexOf("g\"", ++imgSIndex) + 1;
                int phoneEIndex = response.indexOf("\",", ++phoneSIndex);
                int urlEIndex = response.indexOf("rating_img_url", ++urlSIndex) - 4;
                int addressEIndex = response.indexOf("\"], ", ++addressSIndex) + 1;

                //System.out.println("distance = " + response.substring(distanceSIndex,distanceSIndex + 9));
                //String distance = yp.getBusinessDistance(randPick);
                String distance = response.substring(distanceSIndex, distanceSIndex + 9);
                System.out.println("Distance: " + distance);
                double dis;
                try {
                    dis = Double.parseDouble(distance);
                } catch (NumberFormatException e) {
                    dis = 0.0;
                }
                System.out.println("Distance in meters:" + dis);
                System.out.println("Distance in miles:" + meters_to_miles(dis));
                BigDecimal bd = new BigDecimal(meters_to_miles(dis));
                bd = bd.round(new MathContext(2));
                dis = bd.doubleValue();
                System.out.println("dis after conversion " + dis);
                //distance = distance.substring(distanceSIndex,distanceEIndex);

                //activity = yp.getBusinessName(randPick);
                activity = name;
                //rating = yp.getBusinessRating(randPick);
                //I am going to parse the url my self fucking yelp!

                // int imgEIndex = response.indexOf("location",imgSIndex) - 4;
                String phoneNumber = response;
                phoneNumber = phoneNumber.substring(phoneSIndex, phoneEIndex);
                System.out.println("Phone number: " + phoneNumber);
                String tmp2 = response;
                tmp2 = tmp2.substring(imgSIndex, imgEIndex);
                System.out.println("mylink " + tmp2);
                //img_url = yp.getBusinessImageURL(randPick);
                img_url = tmp2;
                System.out.println(img_url);
                //rating_url = yp.getBusinessRatingUrl(randPick);
                String ratingURL = response;
                ratingURL = ratingURL.substring(ratingSIndex, ratingEIndex);
                System.out.println(ratingURL);

                String weburl = response;
                weburl = weburl.substring(urlSIndex, urlEIndex);
                System.out.println("Event URL: " + weburl);

                String eventaddress = response;
                eventaddress = eventaddress.substring(addressSIndex, addressEIndex);

                System.out.println("default Event Address" + eventaddress);

                int streaddSindex = eventaddress.indexOf("\"") + 1;

                int streaddEindex = eventaddress.indexOf("\",");
                int cityaddSindex = 1;
                try {
                    cityaddSindex = eventaddress.indexOf("\", \"") + 4;
                } catch (StringIndexOutOfBoundsException e) {
                    cityaddSindex = 0;
                    System.out.println("No city");
                }

                String streetadd = " ";
                try {
                    streetadd = eventaddress.substring(streaddSindex, streaddEindex);
                } catch (StringIndexOutOfBoundsException e) {
                    if (!Character.isDigit(eventaddress.charAt(0))) {
                        System.out.println("Faulty address");
                        streetadd = " ";
                    }
                }
                System.out.println("Street address:" + streetadd);
                String cityadd;
                if (cityaddSindex != 0)
                    cityadd = eventaddress.substring(cityaddSindex).replace("\"", "");
                else
                    cityadd = " ";

                System.out.println("City location: " + cityadd);
                eventaddress = streetadd + " " + cityadd;
                System.out.println("adjusted Event Address: " + eventaddress);

                //System.out.println(ratingURL);
                event_address = eventaddress;
                phoneNum = phoneNumber;
                web_url = weburl;
                rating_url = ratingURL;
                icon_url = new URL(img_url);
                url_rating = new URL(rating_url);
                try {
                    dayevent.add(index1, new DayEvent(activity, icon_url, url_rating, searchToken, dis, web_url,
                            phoneNum, event_address));
                } catch (IndexOutOfBoundsException e) {
                    System.out.println("Size of day event " + dayevent.size());
                }
                //} catch (JSONException e) {
                //e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    });
    thread.start();
    //test by removing the while loops (bad practice)
    /**       while (response == null) {
           }
           while (activity == null) {
           }
           while (web_url == null) {
           }
           while (img_url == null) {
           }
           while (rating_url == null) {
           }**/
    thread.join();

}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

/**
 * Gets the data table iterator./*from  w w w  .j av  a  2  s  .  c om*/
 * 
 * @param tableName
 *            the table name
 * @param associatedRows
 *            the associated rows
 * @return the data table iterator
 */
public final List<HashMap<String, String>> getDataTableIterator(final String tableNames,
        final String associatedRows) {

    List<HashMap<String, String>> iteratorList = new ArrayList<HashMap<String, String>>();
    List<DataTable> tableList = new ArrayList<DataTable>();
    List<int[]> rowList = new ArrayList<int[]>();
    String[] rowsPerTableArray = associatedRows.split("\\|");
    String[] tableNamesArray = tableNames.split("\\|");
    int rowsPerTableCounts = rowsPerTableArray.length;
    int tableNamesCount = tableNamesArray.length;
    if (rowsPerTableCounts == tableNamesCount) {
        try {
            for (int i = 0; i < tableNamesCount; i++) {
                DataTable table = getTable(tableNamesArray[i]);
                tableList.add(table);
                rowList.add(getAssociatedRowNumbers(table, rowsPerTableArray[i]));
            }

            for (int i = 0; i < tableNamesCount; i++) {
                int currentInsertRow = 0;
                DataTable dataTable = tableList.get(i);
                int[] reqRows = rowList.get(i);
                String tableName = tableNamesArray[i];
                for (int row : reqRows) {
                    if (iteratorList.size() <= currentInsertRow) {
                        iteratorList.add(new HashMap<String, String>());
                    }
                    HashMap<String, String> currRow = iteratorList.get(currentInsertRow);
                    List<String> columnHeaders = dataTable.getColumns();

                    for (String column : columnHeaders) {
                        currRow.put(tableName.concat("_").concat(column), dataTable.get(row, column));
                    }

                    currentInsertRow++;
                }
            }

        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
            String errString = e.getMessage();
            reportresult(true, "DATA TABLE ITERATION :", "FAILED",
                    "Cannot iterate over the data table. Cannot find the row numbers : " + associatedRows
                            + " in data table. " + "Actual Error : " + errString);
            checkTrue(false, true, "Cannot iterate over the data table. Actual Error : " + errString);
        } catch (Exception e) {
            e.printStackTrace();
            String errString = e.getMessage();
            reportresult(true, "DATA TABLE ITERATION :", "FAILED",
                    "Cannot iterate over the data table. Actual Error : " + errString);
            checkTrue(false, true, "Cannot iterate over the data table. Actual Error : " + errString);
        }

    } else {
        reportresult(true, "DATA TABLE ITERATION :", "FAILED",
                "Cannot iterate over the data table. Invalid input data. Actual error : Number of tables passed : "
                        + tableNamesCount + " does not match the associated data rows count : "
                        + rowsPerTableCounts);
        checkTrue(false, true,
                "Cannot iterate over the data table. Invalid input data. Actual error : Number of tables passed : "
                        + tableNamesCount + " does not match the associated data rows count : "
                        + rowsPerTableCounts);
    }
    return iteratorList;

}