Example usage for java.lang CharSequence toString

List of usage examples for java.lang CharSequence toString

Introduction

In this page you can find the example usage for java.lang CharSequence toString.

Prototype

public String toString();

Source Link

Document

Returns a string containing the characters in this sequence in the same order as this sequence.

Usage

From source file:codemirror.eclipse.ui.utils.IOUtils.java

/**
 * Convert the specified CharSequence to an input stream, encoded as bytes
 * using the specified character encoding.
 * <p>//from   ww w .  j  a  v  a  2  s. com
 * Character encoding names can be found at
 * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
 *
 * @param input the CharSequence to convert
 * @param encoding the encoding to use, null means platform default
 * @throws IOException if the encoding is invalid
 * @return an input stream
 * @since 2.0
 */
public static InputStream toInputStream(CharSequence input, String encoding) throws IOException {
    return toInputStream(input.toString(), encoding);
}

From source file:br.msf.commons.text.EnhancedStringBuilder.java

public boolean matches(final CharSequence regex) {
    return matches(Pattern.compile(regex.toString(), 0));
}

From source file:br.msf.commons.text.EnhancedStringBuilder.java

public boolean matches(final CharSequence regex, final int flags) {
    return matches(Pattern.compile(regex.toString(), flags));
}

From source file:de.schildbach.pte.AbstractNavitiaProvider.java

@Override
public NearbyLocationsResult queryNearbyLocations(final EnumSet<LocationType> types, final Location location,
        int maxDistance, final int maxLocations) throws IOException {
    final ResultHeader resultHeader = new ResultHeader(network, SERVER_PRODUCT, SERVER_VERSION, null, 0, null);

    // Build url depending of location type.
    final HttpUrl.Builder url = url();
    if (location.type == LocationType.COORD || location.type == LocationType.ADDRESS
            || location.type == LocationType.ANY) {
        if (!location.hasLocation())
            throw new IllegalArgumentException();
        final double lon = location.lon / 1E6;
        final double lat = location.lat / 1E6;
        url.addPathSegment("coords").addPathSegment(lon + ";" + lat);
    } else if (location.type == LocationType.STATION) {
        if (!location.isIdentified())
            throw new IllegalArgumentException();
        url.addPathSegment("stop_points").addPathSegment(location.id);
    } else if (location.type == LocationType.POI) {
        if (!location.isIdentified())
            throw new IllegalArgumentException();
        url.addPathSegment("pois").addPathSegment(location.id);
    } else {//from  w  w w . j av  a 2s  . com
        throw new IllegalArgumentException("Unhandled location type: " + location.type);
    }
    url.addPathSegment("places_nearby");
    url.addQueryParameter("type[]", "stop_point");
    url.addQueryParameter("distance", Integer.toString(maxDistance == 0 ? 50000 : maxDistance));
    if (maxLocations > 0)
        url.addQueryParameter("count", Integer.toString(maxLocations));
    url.addQueryParameter("depth", "3");
    final CharSequence page = httpClient.get(url.build());

    try {
        final JSONObject head = new JSONObject(page.toString());

        final JSONObject pagination = head.getJSONObject("pagination");
        final int nbResults = pagination.getInt("total_result");
        // If no result is available, location id must be
        // faulty.
        if (nbResults == 0) {
            return new NearbyLocationsResult(resultHeader, Status.INVALID_ID);
        } else {
            final List<Location> stations = new ArrayList<>();

            final JSONArray places = head.getJSONArray("places_nearby");

            // Cycle through nearby stations.
            for (int i = 0; i < places.length(); ++i) {
                final JSONObject place = places.getJSONObject(i);

                // Add location to station list only if
                // station is active, i.e. at least one
                // departure exists within one hour.
                final Location nearbyLocation = parseLocation(place);
                stations.add(nearbyLocation);
            }

            return new NearbyLocationsResult(resultHeader, stations);
        }
    } catch (final JSONException jsonExc) {
        throw new ParserException(jsonExc);
    }
}

From source file:de.schildbach.pte.AbstractNavitiaProvider.java

@Override
public Point[] getArea() throws IOException {
    final HttpUrl.Builder url = url();
    final CharSequence page = httpClient.get(url.build());

    try {//from   w ww .  ja v  a2 s  .co  m
        // Get shape string.
        final JSONObject head = new JSONObject(page.toString());
        final JSONArray regions = head.getJSONArray("regions");
        final JSONObject regionInfo = regions.getJSONObject(0);
        final String shape = regionInfo.getString("shape");

        // Parse string using JSON tokenizer for coordinates.
        List<Point> pointList = new ArrayList<>();
        final JSONTokener shapeTokener = new JSONTokener(shape);
        shapeTokener.skipTo('(');
        shapeTokener.next();
        shapeTokener.next();
        char c = shapeTokener.next();
        while (c != ')') {
            // Navitia coordinates are in (longitude, latitude) order.
            final String lonString = shapeTokener.nextTo(' ');
            shapeTokener.next();
            final String latString = shapeTokener.nextTo(",)");
            c = shapeTokener.next();

            // Append new point with (latitude, longitude) order.
            final double lat = Double.parseDouble(latString);
            final double lon = Double.parseDouble(lonString);
            pointList.add(Point.fromDouble(lat, lon));
        }

        // Fill point array.
        final Point[] pointArray = new Point[pointList.size()];
        for (int i = 0; i < pointList.size(); ++i)
            pointArray[i] = pointList.get(i);

        return pointArray;
    } catch (final JSONException jsonExc) {
        throw new ParserException(jsonExc);
    }
}

From source file:de.schildbach.pte.AbstractNavitiaProvider.java

@Override
public QueryDeparturesResult queryDepartures(final String stationId, final @Nullable Date time,
        final int maxDepartures, final boolean equivs) throws IOException {
    checkNotNull(Strings.emptyToNull(stationId));

    final ResultHeader resultHeader = new ResultHeader(network, SERVER_PRODUCT, SERVER_VERSION, null, 0, null);

    try {/*from   w w w  .  ja  v  a 2 s  .  c  om*/
        final QueryDeparturesResult result = new QueryDeparturesResult(resultHeader,
                QueryDeparturesResult.Status.OK);

        // If equivs is equal to true, get stop_area corresponding
        // to stop_point and query departures.
        final HttpUrl.Builder url = url();
        final String header = stationId.substring(0, stationId.indexOf(":"));
        if (equivs && header.equals("stop_point")) {
            final String stopAreaId = getStopAreaId(stationId);
            url.addPathSegment("stop_areas");
            url.addPathSegment(stopAreaId);
        } else if (header.equals("stop_area")) {
            url.addPathSegment("stop_areas");
            url.addPathSegment(stationId);
        } else {
            url.addPathSegment("stop_points");
            url.addPathSegment(stationId);
        }
        url.addPathSegment("departures");
        url.addQueryParameter("from_datetime", printDate(time));
        url.addQueryParameter("count", Integer.toString(maxDepartures));
        url.addQueryParameter("duration", "86400");
        url.addQueryParameter("depth", "0");

        final CharSequence page = httpClient.get(url.build());

        final JSONObject head = new JSONObject(page.toString());

        final JSONArray departures = head.getJSONArray("departures");

        // Fill departures in StationDepartures.
        for (int i = 0; i < departures.length(); ++i) {
            final JSONObject jsonDeparture = departures.getJSONObject(i);

            // Build departure date.
            final JSONObject stopDateTime = jsonDeparture.getJSONObject("stop_date_time");
            final String departureDateTime = stopDateTime.getString("departure_date_time");
            final Date plannedTime = parseDate(departureDateTime);

            // Build line.
            final JSONObject route = jsonDeparture.getJSONObject("route");
            final Line line = parseLine(route);

            final JSONObject stopPoint = jsonDeparture.getJSONObject("stop_point");
            final Location location = parsePlace(stopPoint, PlaceType.STOP_POINT);

            // If stop point has already been added, retrieve it from result,
            // otherwise add it and add station lines.
            StationDepartures stationDepartures = result.findStationDepartures(location.id);
            if (stationDepartures == null) {
                stationDepartures = new StationDepartures(location, new LinkedList<Departure>(),
                        new LinkedList<LineDestination>());
                result.stationDepartures.add(stationDepartures);
            }
            final LineDestination lineDestination = getStationLine(line, jsonDeparture);
            final List<LineDestination> lines = stationDepartures.lines;
            if (lines != null && !lines.contains(lineDestination))
                lines.add(lineDestination);
            final Location destination = lineDestination.destination;

            // Add departure to list.
            final Departure departure = new Departure(plannedTime, null, line, null, destination, null, null);
            stationDepartures.departures.add(departure);
        }

        return result;
    } catch (final JSONException jsonExc) {
        throw new ParserException(jsonExc);
    } catch (final ParseException parseExc) {
        throw new ParserException(parseExc);
    } catch (final NotFoundException fnfExc) {
        try {
            final JSONObject head = new JSONObject(fnfExc.getBodyPeek().toString());
            final JSONObject error = head.getJSONObject("error");
            final String id = error.getString("id");

            if (id.equals("unknown_object"))
                return new QueryDeparturesResult(resultHeader, QueryDeparturesResult.Status.INVALID_STATION);
            else
                throw new IllegalArgumentException("Unhandled error id: " + id);
        } catch (final JSONException jsonExc) {
            throw new ParserException("Cannot parse error content, original exception linked", fnfExc);
        }
    }
}

From source file:com.example.zf_android.trade.ApplyDetailActivity.java

/**
 * firstly init the merchant category with item keys,
 * and after user select the merchant the values will be set
 *//*from www .  j  a  v  a  2s  .  c  o  m*/
private void initMerchantDetailKeys() {
    // the first category
    mMerchantKeys = getResources().getStringArray(R.array.apply_detail_merchant_keys);

    mMerchantContainer.addView(getDetailItem(ITEM_CHOOSE, mMerchantKeys[0], null));
    mMerchantContainer.addView(getDetailItem(ITEM_EDIT, mMerchantKeys[1], null));

    LinearLayout ll = getDetailItem(ITEM_EDIT, mMerchantKeys[2], null);
    etMerchantName = (EditText) ll.findViewById(R.id.apply_detail_value);
    etMerchantName.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            etBankMerchantName.setText(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            etBankMerchantName.setText(s.toString());
        }
    });
    mMerchantContainer.addView(ll);

    View merchantGender = getDetailItem(ITEM_CHOOSE, mMerchantKeys[3], null);
    merchantGender.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(ApplyDetailActivity.this);
            final String[] items = getResources().getStringArray(R.array.apply_detail_gender);
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    setItemValue(mMerchantKeys[3], items[which]);
                }
            });
            builder.show();
        }
    });
    mMerchantContainer.addView(merchantGender);

    View merchantBirthday = getDetailItem(ITEM_CHOOSE, mMerchantKeys[4], null);
    merchantBirthday.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CommonUtil.showDatePicker(ApplyDetailActivity.this, mMerchantBirthday,
                    new CommonUtil.OnDateSetListener() {
                        @Override
                        public void onDateSet(String date) {
                            setItemValue(mMerchantKeys[4], date);
                        }
                    });
        }
    });
    mMerchantContainer.addView(merchantBirthday);
    mMerchantContainer.addView(getDetailItem(ITEM_EDIT, mMerchantKeys[5], null));
    mMerchantContainer.addView(getDetailItem(ITEM_EDIT, mMerchantKeys[6], null));
    mMerchantContainer.addView(getDetailItem(ITEM_EDIT, mMerchantKeys[7], null));

    View merchantCity = getDetailItem(ITEM_CHOOSE, mMerchantKeys[8], null);
    merchantCity.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(ApplyDetailActivity.this, CityProvinceActivity.class);
            intent.putExtra(SELECTED_PROVINCE, mMerchantProvince);
            intent.putExtra(SELECTED_CITY, mMerchantCity);
            startActivityForResult(intent, REQUEST_CHOOSE_CITY);
        }
    });
    mMerchantContainer.addView(merchantCity);

    // the second category
    mBankKeys = getResources().getStringArray(R.array.apply_detail_bank_keys);

    mCustomerContainer.addView(getDetailItem(ITEM_CHOOSE, mBankKeys[0], null));
    LinearLayout tmpll = (LinearLayout) mContainer.findViewWithTag(mBankKeys[0]);
    tmpll.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            customTag = mBankKeys[0];
            Intent intent = new Intent(ApplyDetailActivity.this, BankList.class);
            intent.putExtra(AGENT_NAME, mBankName);
            intent.putExtra("terminalId", mTerminalId);
            startActivityForResult(intent, REQUEST_CHOOSE_BANK);
        }
    });

    View bankAccountName = getDetailItem(ITEM_EDIT, mBankKeys[1], null);
    etBankMerchantName = (EditText) bankAccountName.findViewById(R.id.apply_detail_value);
    etBankMerchantName.setEnabled(false);

    mCustomerContainer.addView(bankAccountName);
    mCustomerContainer.addView(getDetailItem(ITEM_EDIT, mBankKeys[2], null));
    mCustomerContainer.addView(getDetailItem(ITEM_EDIT, mBankKeys[3], null));
    mCustomerContainer.addView(getDetailItem(ITEM_EDIT, mBankKeys[4], null));

    View chooseChannel = getDetailItem(ITEM_CHOOSE, getString(R.string.apply_detail_channel), null);
    chooseChannel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(ApplyDetailActivity.this, ChannelSelecter.class);
            startActivityForResult(intent, REQUEST_CHOOSE_CHANNEL);

        }
    });
    mCustomerContainer.addView(chooseChannel);
}

From source file:de.schildbach.pte.VrsProvider.java

private void queryLinesForStation(String stationId, List<LineDestination> lineDestinations) throws IOException {
    Set<String> lineNumbersAlreadyKnown = new HashSet<String>();
    for (LineDestination lineDestionation : lineDestinations) {
        lineNumbersAlreadyKnown.add(lineDestionation.line.label);
    }// ww w  .  j a v  a2 s  . co  m
    final HttpUrl.Builder url = API_BASE.newBuilder();
    url.addQueryParameter("eID", "tx_vrsinfo_his_info");
    url.addQueryParameter("i", stationId);

    final CharSequence page = httpClient.get(url.build());

    try {
        final JSONObject head = new JSONObject(page.toString());
        final JSONObject his = head.optJSONObject("his");
        if (his != null) {
            final JSONArray lines = his.optJSONArray("lines");
            if (lines != null) {
                for (int iLine = 0; iLine < lines.length(); iLine++) {
                    final JSONObject line = lines.getJSONObject(iLine);
                    final String number = processLineNumber(line.getString("number"));
                    if (lineNumbersAlreadyKnown.contains(number)) {
                        continue;
                    }
                    final Product product = productFromLineNumber(number);
                    String direction = null;
                    final JSONArray postings = line.optJSONArray("postings");
                    if (postings != null) {
                        for (int iPosting = 0; iPosting < postings.length(); iPosting++) {
                            final JSONObject posting = (JSONObject) postings.get(iPosting);
                            direction = posting.getString("direction");
                            lineDestinations.add(new LineDestination(
                                    new Line(null /* id */, NetworkId.VRS.toString(), product, number,
                                            lineStyle("vrs", product, number)),
                                    new Location(LocationType.STATION, null /* id */, null /* place */,
                                            direction)));
                        }
                    } else {
                        lineDestinations.add(
                                new LineDestination(new Line(null /* id */, NetworkId.VRS.toString(), product,
                                        number, lineStyle("vrs", product, number)), null /* direction */));
                    }
                }
            }
        }
    } catch (final JSONException x) {
        throw new RuntimeException("cannot parse: '" + page + "' on " + url, x);
    }
    Collections.sort(lineDestinations, new LineDestinationComparator());
}

From source file:de.schildbach.pte.AbstractNavitiaProvider.java

@Override
public QueryTripsResult queryMoreTrips(final QueryTripsContext contextObj, final boolean later)
        throws IOException {
    final ResultHeader resultHeader = new ResultHeader(network, SERVER_PRODUCT, SERVER_VERSION, null, 0, null);

    final Context context = (Context) contextObj;
    final Location from = context.from;
    final Location to = context.to;
    final HttpUrl queryUrl = HttpUrl.parse(later ? context.nextQueryUri : context.prevQueryUri);
    final CharSequence page = httpClient.get(queryUrl);

    try {/*  w  ww .  java 2s . c om*/
        if (from.isIdentified() && to.isIdentified()) {
            final JSONObject head = new JSONObject(page.toString());

            // Fill context.
            final JSONArray links = head.getJSONArray("links");
            final JSONObject prev = links.getJSONObject(0);
            final HttpUrl prevQueryUrl = HttpUrl.parse(prev.getString("href"));
            final JSONObject next = links.getJSONObject(1);
            final HttpUrl nextQueryUrl = HttpUrl.parse(next.getString("href"));

            final QueryTripsResult result = new QueryTripsResult(resultHeader, queryUrl.toString(), from, null,
                    to, new Context(from, to, prevQueryUrl.toString(), nextQueryUrl.toString()),
                    new LinkedList<Trip>());

            parseQueryTripsResult(head, from, to, result);

            return result;
        } else {
            return new QueryTripsResult(null, QueryTripsResult.Status.NO_TRIPS);
        }
    } catch (final JSONException jsonExc) {
        throw new ParserException(jsonExc);
    }
}

From source file:it.unimi.di.big.mg4j.index.DiskBasedIndex.java

/** Returns a new disk-based index, loading exactly the specified parts and using preloaded {@link Properties}.
 * /*from   www.ja  v  a  2s.c o  m*/
 * @param ioFactory the factory that will be used to perform I/O.
 * @param basename the basename of the index.
 * @param properties the properties obtained from the given basename.
 * @param termMap the term map for this index, or <code>null</code> for no term map.
 * @param prefixMap the prefix map for this index, or <code>null</code> for no prefix map.
 * @param randomAccess whether the index should be accessible randomly (e.g., if it will
 * be possible to call {@link IndexReader#documents(long)} on the index readers returned by the index).
 * @param documentSizes if true, document sizes will be loaded (note that sometimes document sizes
 * might be loaded anyway because the compression method for positions requires it).
 * @param queryProperties a map containing associations between {@link Index.UriKeys} and values, or <code>null</code>.
 */
@SuppressWarnings("resource")
public static Index getInstance(final IOFactory ioFactory, final CharSequence basename, Properties properties,
        final StringMap<? extends CharSequence> termMap, final PrefixMap<? extends CharSequence> prefixMap,
        final boolean randomAccess, final boolean documentSizes, final EnumMap<UriKeys, String> queryProperties)
        throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException {

    // This could be null if old indices contain SkipIndex
    Class<?> indexClass = null;
    try {
        // Compatibility with previous versions
        indexClass = Class.forName(properties.getString(Index.PropertyKeys.INDEXCLASS, "(missing index class)")
                .replace(".dsi.", ".di."));
    } catch (Exception ignore) {
    }

    final long numberOfDocuments = properties.getLong(Index.PropertyKeys.DOCUMENTS);
    final long numberOfTerms = properties.getLong(Index.PropertyKeys.TERMS);
    final long numberOfPostings = properties.getLong(Index.PropertyKeys.POSTINGS);
    final long numberOfOccurrences = properties.getLong(Index.PropertyKeys.OCCURRENCES, -1);
    final int maxCount = properties.getInt(Index.PropertyKeys.MAXCOUNT, -1);
    final String field = properties.getString(Index.PropertyKeys.FIELD,
            new File(basename.toString()).getName());

    if (termMap != null && termMap.size64() != numberOfTerms)
        throw new IllegalArgumentException("The size of the term map (" + termMap.size64()
                + ") is not equal to the number of terms (" + numberOfTerms + ")");
    if (prefixMap != null && prefixMap.size64() != numberOfTerms)
        throw new IllegalArgumentException("The size of the prefix map (" + prefixMap.size64()
                + ") is not equal to the number of terms (" + numberOfTerms + ")");

    final Payload payload = (Payload) (properties.containsKey(Index.PropertyKeys.PAYLOADCLASS)
            ? Class.forName(properties.getString(Index.PropertyKeys.PAYLOADCLASS)).newInstance()
            : null);

    final int skipQuantum = properties.getInt(BitStreamIndex.PropertyKeys.SKIPQUANTUM, -1);

    final int bufferSize = properties.getInt(BitStreamIndex.PropertyKeys.BUFFERSIZE,
            BitStreamIndex.DEFAULT_BUFFER_SIZE);
    final int offsetStep = queryProperties != null && queryProperties.get(UriKeys.OFFSETSTEP) != null
            ? Integer.parseInt(queryProperties.get(UriKeys.OFFSETSTEP))
            : DEFAULT_OFFSET_STEP;

    final boolean highPerformance = indexClass != null && FileHPIndex.class.isAssignableFrom(indexClass);
    final boolean inMemory = queryProperties != null && queryProperties.containsKey(UriKeys.INMEMORY);
    final TermProcessor termProcessor = Index.getTermProcessor(properties);

    // Load document sizes if forced to do so, or if the pointer/position compression methods make it necessary.
    IntBigList sizes = null;

    if (queryProperties != null && queryProperties.containsKey(UriKeys.SUCCINCTSIZES)
            && ioFactory != IOFactory.FILESYSTEM_FACTORY)
        throw new IllegalArgumentException(
                "Succinct sizes are deprecated and available only using the file system I/O factory.");

    if (QuasiSuccinctIndex.class == indexClass) {
        if (ioFactory != IOFactory.FILESYSTEM_FACTORY && !inMemory)
            throw new IllegalArgumentException(
                    "Memory-mapped quasi-succinct indices require the file system I/O factory.");
        final Map<Component, Coding> flags = CompressionFlags.valueOf(
                properties.getStringArray(Index.PropertyKeys.CODING),
                CompressionFlags.DEFAULT_QUASI_SUCCINCT_INDEX);
        final File pointersFile = new File(basename + POINTERS_EXTENSIONS);
        if (!pointersFile.exists())
            throw new FileNotFoundException("Cannot find pointers file " + pointersFile.getName());

        if (documentSizes) {
            sizes = queryProperties != null && queryProperties.containsKey(UriKeys.SUCCINCTSIZES)
                    ? readSizesSuccinct(basename + DiskBasedIndex.SIZES_EXTENSION, numberOfDocuments)
                    : readSizes(ioFactory, basename + DiskBasedIndex.SIZES_EXTENSION, numberOfDocuments);
            if (sizes.size64() != numberOfDocuments)
                throw new IllegalStateException("The length of the size list (" + sizes.size64()
                        + ") is not equal to the number of documents (" + numberOfDocuments + ")");
        }

        final ByteOrder byteOrder = byteOrder(properties.getString(PropertyKeys.BYTEORDER));
        final boolean hasCounts = flags.containsKey(Component.COUNTS);
        final boolean hasPositions = flags.containsKey(Component.POSITIONS);
        return new QuasiSuccinctIndex(
                inMemory ? loadLongBigList(ioFactory, basename + POINTERS_EXTENSIONS, byteOrder)
                        : ByteBufferLongBigList.map(
                                new FileInputStream(basename + POINTERS_EXTENSIONS).getChannel(), byteOrder,
                                MapMode.READ_ONLY),
                hasCounts
                        ? (inMemory ? loadLongBigList(ioFactory, basename + COUNTS_EXTENSION, byteOrder)
                                : ByteBufferLongBigList.map(
                                        new FileInputStream(basename + COUNTS_EXTENSION).getChannel(),
                                        byteOrder, MapMode.READ_ONLY))
                        : null,
                hasPositions ? (inMemory ? loadLongBigList(ioFactory, basename + POSITIONS_EXTENSION, byteOrder)
                        : ByteBufferLongBigList.map(
                                new FileInputStream(basename + POSITIONS_EXTENSION).getChannel(), byteOrder,
                                MapMode.READ_ONLY))
                        : null,
                numberOfDocuments, numberOfTerms, numberOfPostings, numberOfOccurrences, maxCount, payload,
                Fast.mostSignificantBit(skipQuantum), hasCounts, hasPositions,
                Index.getTermProcessor(properties), field, properties, termMap, prefixMap, sizes,
                DiskBasedIndex.offsets(ioFactory, basename + POINTERS_EXTENSIONS + OFFSETS_POSTFIX,
                        numberOfTerms, offsetStep),
                hasCounts
                        ? DiskBasedIndex.offsets(ioFactory, basename + COUNTS_EXTENSION + OFFSETS_POSTFIX,
                                numberOfTerms, offsetStep)
                        : null,
                hasPositions
                        ? DiskBasedIndex.offsets(ioFactory, basename + POSITIONS_EXTENSION + OFFSETS_POSTFIX,
                                numberOfTerms, offsetStep)
                        : null);

    }

    final Map<Component, Coding> flags = CompressionFlags
            .valueOf(properties.getStringArray(Index.PropertyKeys.CODING), null);

    final Coding frequencyCoding = flags.get(Component.FREQUENCIES);
    final Coding pointerCoding = flags.get(Component.POINTERS);
    final Coding countCoding = flags.get(Component.COUNTS);
    final Coding positionCoding = flags.get(Component.POSITIONS);
    if (countCoding == null && positionCoding != null)
        throw new IllegalArgumentException(
                "Index " + basename + " has positions but no counts (this can't happen)");

    if (payload == null
            && (documentSizes || positionCoding == Coding.GOLOMB || positionCoding == Coding.INTERPOLATIVE)) {
        sizes = queryProperties != null && queryProperties.containsKey(UriKeys.SUCCINCTSIZES)
                ? readSizesSuccinct(basename + DiskBasedIndex.SIZES_EXTENSION, numberOfDocuments)
                : readSizes(basename + DiskBasedIndex.SIZES_EXTENSION, numberOfDocuments);
        if (sizes.size64() != numberOfDocuments)
            throw new IllegalStateException("The length of the size list (" + sizes.size64()
                    + ") is not equal to the number of documents (" + numberOfDocuments + ")");
    }

    final int height = properties.getInt(BitStreamIndex.PropertyKeys.SKIPHEIGHT, -1);
    // Load offsets if forced to do so. Depending on a property, we use the core-memory or the semi-external version.
    final LongBigList offsets = payload == null && randomAccess
            ? offsets(ioFactory, basename + OFFSETS_EXTENSION, numberOfTerms, offsetStep)
            : null;

    final String indexFile = basename + INDEX_EXTENSION;
    if (!ioFactory.exists(indexFile))
        throw new FileNotFoundException("Cannot find index file " + indexFile);

    if (inMemory) {
        /*if ( SqrtSkipIndex.class.isAssignableFrom( indexClass ) )
           return new SqrtSkipInMemoryIndex( BinIO.loadBytes( indexFile.toString() ), 
          numberOfDocuments, numberOfTerms, numberOfPostings, numberOfOccurrences, maxCount, 
          frequencyCoding, pointerCoding, countCoding, positionCoding,
          termProcessor,
          field, properties, termMap, prefixMap, sizes, offsets );*/
        return highPerformance
                ? new InMemoryHPIndex(IOFactories.loadBytes(ioFactory, indexFile),
                        IOFactories.loadBytes(ioFactory, basename + POSITIONS_EXTENSION), numberOfDocuments,
                        numberOfTerms, numberOfPostings, numberOfOccurrences, maxCount, payload,
                        frequencyCoding, pointerCoding, countCoding, positionCoding, skipQuantum, height,
                        termProcessor, field, properties, termMap, prefixMap, sizes, offsets)
                : new InMemoryIndex(IOFactories.loadBytes(ioFactory, indexFile.toString()), numberOfDocuments,
                        numberOfTerms, numberOfPostings, numberOfOccurrences, maxCount, payload,
                        frequencyCoding, pointerCoding, countCoding, positionCoding, skipQuantum, height,
                        termProcessor, field, properties, termMap, prefixMap, sizes, offsets);
    } else if (queryProperties != null && queryProperties.containsKey(UriKeys.MAPPED)) {
        if (ioFactory != IOFactory.FILESYSTEM_FACTORY)
            throw new IllegalArgumentException("Mapped indices require the file system I/O factory.");
        final File positionsFile = new File(basename + POSITIONS_EXTENSION);
        final ByteBufferInputStream index = ByteBufferInputStream
                .map(new FileInputStream(indexFile).getChannel(), MapMode.READ_ONLY);
        return highPerformance
                ? new MemoryMappedHPIndex(index,
                        ByteBufferInputStream.map(new FileInputStream(positionsFile).getChannel(),
                                MapMode.READ_ONLY),
                        numberOfDocuments, numberOfTerms, numberOfPostings, numberOfOccurrences, maxCount,
                        payload, frequencyCoding, pointerCoding, countCoding, positionCoding, skipQuantum,
                        height, termProcessor, field, properties, termMap, prefixMap, sizes, offsets)
                : new MemoryMappedIndex(index, numberOfDocuments, numberOfTerms, numberOfPostings,
                        numberOfOccurrences, maxCount, payload, frequencyCoding, pointerCoding, countCoding,
                        positionCoding, skipQuantum, height, termProcessor, field, properties, termMap,
                        prefixMap, sizes, offsets);

    }
    /*if ( SqrtSkipIndex.class.isAssignableFrom( indexClass ) )
       return new SqrtSkipFileIndex( basename.toString(), 
    numberOfDocuments, numberOfTerms, numberOfPostings, numberOfOccurrences, maxCount, 
    frequencyCoding, pointerCoding, countCoding, positionCoding,
    termProcessor,
    field, properties, termMap, prefixMap, sizes, offsets, indexFile );*/

    return highPerformance
            ? new FileHPIndex(basename.toString(), numberOfDocuments, numberOfTerms, numberOfPostings,
                    numberOfOccurrences, maxCount, payload, frequencyCoding, pointerCoding, countCoding,
                    positionCoding, skipQuantum, height, bufferSize, termProcessor, field, properties, termMap,
                    prefixMap, sizes, offsets)
            : new FileIndex(ioFactory, basename.toString(), numberOfDocuments, numberOfTerms, numberOfPostings,
                    numberOfOccurrences, maxCount, payload, frequencyCoding, pointerCoding, countCoding,
                    positionCoding, skipQuantum, height, bufferSize, termProcessor, field, properties, termMap,
                    prefixMap, sizes, offsets);

}