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:Main.java

/**
 * Return text content of clipboard as individual lines 
 * @param ctx/*www.  j a v  a2  s  . co m*/
 * @return
 */
@SuppressLint("NewApi")
private static ArrayList<String> getTextLines(Context ctx) {

    String EOL = "\\r?\\n|\\r";

    if (checkForText(ctx)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);

            // Gets the clipboard as text.
            CharSequence cs = item.getText();
            if (cs == null) { // item might be an URI
                Uri pasteUri = item.getUri();
                if (pasteUri != null) { // FIXME untested
                    try {
                        Log.d("ClipboardUtils", "Clipboard contains an uri");
                        ContentResolver cr = ctx.getContentResolver();
                        String uriMimeType = cr.getType(pasteUri);
                        //               pasteData = resolveUri(pasteUri);
                        // If the return value is not null, the Uri is a content Uri
                        if (uriMimeType != null) {

                            // Does the content provider offer a MIME type that the current application can use?
                            if (uriMimeType.equals(ClipDescription.MIMETYPE_TEXT_PLAIN)) {

                                // Get the data from the content provider.
                                Cursor pasteCursor = cr.query(pasteUri, null, null, null, null);

                                // If the Cursor contains data, move to the first record
                                if (pasteCursor != null) {
                                    if (pasteCursor.moveToFirst()) {
                                        String pasteData = pasteCursor.getString(0);
                                        return new ArrayList<String>(Arrays.asList(pasteData.split(EOL)));
                                    }
                                    // close the Cursor
                                    pasteCursor.close();
                                }
                            }
                        }
                    } catch (Exception e) { // FIXME given that the above is unteted, cath all here
                        Log.e("ClipboardUtils", "Resolving URI failed " + e);
                        e.printStackTrace();
                        return null;
                    }
                }
            } else {
                Log.d("ClipboardUtils", "Clipboard contains text");
                String pasteData = cs.toString();
                return new ArrayList<String>(Arrays.asList(pasteData.split(EOL)));
            }
        } else {
            // Gets the clipboard as text.
            @SuppressWarnings("deprecation")
            CharSequence cs = oldClipboard.getText();
            if (cs != null) {
                String pasteData = cs.toString();
                if (pasteData != null) { // should always be the case
                    return new ArrayList<String>(Arrays.asList(pasteData.split(EOL)));
                }
            }
        }
        Log.e("ClipboardUtils", "Clipboard contains an invalid data type");
    }
    return null;
}

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

@Override
public QueryTripsResult queryTrips(final Location from, final @Nullable Location via, final Location to,
        final Date date, final boolean dep, final @Nullable Set<Product> products,
        final @Nullable Optimize optimize, final @Nullable WalkSpeed walkSpeed,
        final @Nullable Accessibility accessibility, final @Nullable Set<Option> options) throws IOException {
    final ResultHeader resultHeader = new ResultHeader(network, SERVER_PRODUCT, SERVER_VERSION, null, 0, null);

    try {//from  ww  w  .ja  v  a 2  s .c om
        if (from != null && from.isIdentified() && to != null && to.isIdentified()) {
            final HttpUrl.Builder url = apiBase.newBuilder().addPathSegment("journeys");
            url.addQueryParameter("from", printLocation(from));
            url.addQueryParameter("to", printLocation(to));
            url.addQueryParameter("datetime", printDate(date));
            url.addQueryParameter("datetime_represents", dep ? "departure" : "arrival");
            url.addQueryParameter("min_nb_journeys", Integer.toString(this.numTripsRequested));
            url.addQueryParameter("depth", "0");

            // Set walking speed.
            if (walkSpeed != null) {
                final double walkingSpeed;
                switch (walkSpeed) {
                case SLOW:
                    walkingSpeed = 1.12 * 0.8;
                    break;
                case FAST:
                    walkingSpeed = 1.12 * 1.2;
                    break;
                case NORMAL:
                default:
                    walkingSpeed = 1.12;
                    break;
                }

                url.addQueryParameter("walking_speed", Double.toString(walkingSpeed));
            }

            if (options != null && options.contains(Option.BIKE)) {
                url.addQueryParameter("first_section_mode", "bike");
                url.addQueryParameter("last_section_mode", "bike");
            }

            // Set forbidden physical modes.
            if (products != null && !products.equals(Product.ALL)) {
                url.addQueryParameter("forbidden_uris[]", "physical_mode:Air");
                url.addQueryParameter("forbidden_uris[]", "physical_mode:Boat");
                if (!products.contains(Product.REGIONAL_TRAIN)) {
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Localdistancetrain");
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Train");
                }
                if (!products.contains(Product.SUBURBAN_TRAIN)) {
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Localtrain");
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Train");
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Rapidtransit");
                }
                if (!products.contains(Product.SUBWAY)) {
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Metro");
                }
                if (!products.contains(Product.TRAM)) {
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Tramway");
                }
                if (!products.contains(Product.BUS)) {
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Bus");
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Busrapidtransit");
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Coach");
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Shuttle");
                }
                if (!products.contains(Product.FERRY)) {
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Ferry");
                }
                if (!products.contains(Product.CABLECAR)) {
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Funicular");
                }
                if (!products.contains(Product.ON_DEMAND)) {
                    url.addQueryParameter("forbidden_uris[]", "physical_mode:Taxi");
                }
            }

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

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

                if (head.has("error")) {
                    final JSONObject error = head.getJSONObject("error");
                    final String id = error.getString("id");

                    if (id.equals("no_solution"))
                        return new QueryTripsResult(resultHeader, QueryTripsResult.Status.NO_TRIPS);
                    else
                        throw new IllegalArgumentException("Unhandled error id: " + id);
                } else {
                    // Fill context.
                    HttpUrl prevQueryUrl = null;
                    HttpUrl nextQueryUrl = null;
                    final JSONArray links = head.getJSONArray("links");
                    for (int i = 0; i < links.length(); ++i) {
                        final JSONObject link = links.getJSONObject(i);
                        final String type = link.getString("type");
                        if (type.equals("prev")) {
                            prevQueryUrl = HttpUrl.parse(link.getString("href"));
                        } else if (type.equals("next")) {
                            nextQueryUrl = HttpUrl.parse(link.getString("href"));
                        }
                    }

                    String prevQueryUrlString = prevQueryUrl != null ? prevQueryUrl.toString() : null;
                    String nextQueryUrlString = nextQueryUrl != null ? nextQueryUrl.toString() : null;

                    final QueryTripsResult result = new QueryTripsResult(resultHeader, url.build().toString(),
                            from, null, to, new Context(from, to, prevQueryUrlString, nextQueryUrlString),
                            new LinkedList<Trip>());

                    parseQueryTripsResult(head, from, to, result);

                    return result;
                }
            } catch (final JSONException jsonExc) {
                throw new ParserException(jsonExc);
            }
        } else if (from != null && to != null) {
            List<Location> ambiguousFrom = null, ambiguousTo = null;
            Location newFrom = null, newTo = null;

            if (!from.isIdentified() && from.hasName()) {
                ambiguousFrom = suggestLocations(from.name).getLocations();
                if (ambiguousFrom.isEmpty())
                    return new QueryTripsResult(resultHeader, QueryTripsResult.Status.UNKNOWN_FROM);
                if (ambiguousFrom.size() == 1 && ambiguousFrom.get(0).isIdentified())
                    newFrom = ambiguousFrom.get(0);
            }

            if (!to.isIdentified() && to.hasName()) {
                ambiguousTo = suggestLocations(to.name).getLocations();
                if (ambiguousTo.isEmpty())
                    return new QueryTripsResult(resultHeader, QueryTripsResult.Status.UNKNOWN_TO);
                if (ambiguousTo.size() == 1 && ambiguousTo.get(0).isIdentified())
                    newTo = ambiguousTo.get(0);
            }

            if (newTo != null && newFrom != null)
                return queryTrips(newFrom, via, newTo, date, dep, products, optimize, walkSpeed, accessibility,
                        options);

            if (ambiguousFrom != null || ambiguousTo != null)
                return new QueryTripsResult(resultHeader, ambiguousFrom, null, ambiguousTo);
        }
        return new QueryTripsResult(resultHeader, QueryTripsResult.Status.NO_TRIPS);
    } 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")) {
                // Identify unknown object.
                final String fromString = printLocation(from);
                final String toString = printLocation(to);

                final String message = error.getString("message");
                if (message.equals("Invalid id : " + fromString))
                    return new QueryTripsResult(resultHeader, QueryTripsResult.Status.UNKNOWN_FROM);
                else if (message.equals("Invalid id : " + toString))
                    return new QueryTripsResult(resultHeader, QueryTripsResult.Status.UNKNOWN_TO);
                else
                    throw new IllegalArgumentException("Unhandled error message: " + message);
            } else if (id.equals("date_out_of_bounds")) {
                return new QueryTripsResult(resultHeader, QueryTripsResult.Status.INVALID_DATE);
            } 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.insthub.O2OMobile.Activity.C1_PublishOrderActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.c1_publish_order);
    mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    File file = new File(newFileName());
    if (file.exists()) {
        file.delete();/*from w  ww  .  j  a va  2s.c o  m*/
    }

    Intent intent = getIntent();
    mServiceType = (SERVICE_TYPE) intent.getSerializableExtra(O2OMobileAppConst.SERVICE_TYPE);
    mDefaultReceiverId = intent.getIntExtra(DEFAULT_RECEIVER_ID, 0);
    service_list = intent.getStringExtra("service_list");

    mBack = (ImageView) findViewById(R.id.top_view_back);
    mTitle = (TextView) findViewById(R.id.top_view_title);
    mBack.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
        }
    });
    mArrowImage = (ImageView) findViewById(R.id.top_view_arrow_image);
    mClose = (ImageView) findViewById(R.id.top_view_right_close);
    mTitleView = (LinearLayout) findViewById(R.id.top_view_title_view);
    mServiceTypeView = (FrameLayout) findViewById(R.id.c1_publish_order_service_type_view);
    mServiceTypeListview = (ListView) findViewById(R.id.c1_publish_order_service_type_list);
    mPrice = (EditText) findViewById(R.id.c1_publish_order_price);
    mTime = (TextView) findViewById(R.id.c1_publish_order_time);
    mLocation = (EditText) findViewById(R.id.c1_publish_order_location);
    mText = (EditText) findViewById(R.id.c1_publish_order_text);
    mVoice = (Button) findViewById(R.id.c1_publish_order_voice);
    mVoicePlay = (Button) findViewById(R.id.c1_publish_order_voicePlay);
    mVoiceReset = (ImageView) findViewById(R.id.c1_publish_order_voiceReset);
    mPublish = (Button) findViewById(R.id.c1_publish_order_publish);
    mVoiceView = (FrameLayout) findViewById(R.id.c1_publish_order_voice_view);
    mVoiceAnim = (ImageView) findViewById(R.id.c1_publish_order_voice_anim);
    mVoiceAnim.setImageResource(R.anim.voice_animation);
    mAnimationDrawable = (AnimationDrawable) mVoiceAnim.getDrawable();
    mAnimationDrawable.setOneShot(false);
    mTitleView.setEnabled(false);
    mServiceTypeView.setOnClickListener(null);
    mServiceTypeListview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            if (mDefaultReceiverId == 0) {
                mTitle.setText(mHomeModel.publicServiceTypeList.get(position).title);
                mServiceTypeId = mHomeModel.publicServiceTypeList.get(position).id;
                mC1PublishOrderAdapter = new C1_PublishOrderAdapter(C1_PublishOrderActivity.this,
                        mHomeModel.publicServiceTypeList, position);
                mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                mClose.setVisibility(View.GONE);
                mArrowImage.setImageResource(R.drawable.b3_arrow_down);
                AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        mServiceTypeView.setVisibility(View.GONE);
                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 200);
            } else {
                mTitle.setText(mServiceTypeList.get(position).title);
                mServiceTypeId = mServiceTypeList.get(position).id;
                mC1PublishOrderAdapter = new C1_PublishOrderAdapter(C1_PublishOrderActivity.this,
                        mServiceTypeList, position);
                mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                mClose.setVisibility(View.GONE);
                mArrowImage.setImageResource(R.drawable.b3_arrow_down);
                AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        mServiceTypeView.setVisibility(View.GONE);
                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 200);
            }

        }
    });

    mTitleView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (mServiceTypeView.getVisibility() == View.GONE) {
                mServiceTypeView.setVisibility(View.VISIBLE);
                mClose.setVisibility(View.VISIBLE);
                mArrowImage.setImageResource(R.drawable.b4_arrow_up);
                AnimationUtil.showAnimationFromTop(mServiceTypeListview);
                closeKeyBoard();
            } else {
                mClose.setVisibility(View.GONE);
                mArrowImage.setImageResource(R.drawable.b3_arrow_down);
                AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        mServiceTypeView.setVisibility(View.GONE);
                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 200);
            }
        }
    });

    mClose.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mClose.setVisibility(View.GONE);
            mArrowImage.setImageResource(R.drawable.b3_arrow_down);
            AnimationUtil.backAnimationFromBottom(mServiceTypeListview);
            Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    mServiceTypeView.setVisibility(View.GONE);
                }
            };
            mHandler.sendEmptyMessageDelayed(0, 200);
        }
    });

    mPrice.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            if (s.toString().length() > 0) {
                if (s.toString().substring(0, 1).equals(".")) {
                    s = s.toString().substring(1, s.length());
                    mPrice.setText(s);
                }
            }
            if (s.toString().length() > 1) {
                if (s.toString().substring(0, 1).equals("0")) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        s = s.toString().substring(1, s.length());
                        mPrice.setText(s);
                        CharSequence charSequencePirce = mPrice.getText();
                        if (charSequencePirce instanceof Spannable) {
                            Spannable spanText = (Spannable) charSequencePirce;
                            Selection.setSelection(spanText, charSequencePirce.length());
                        }
                    }
                }
            }
            boolean flag = false;
            for (int i = 0; i < s.toString().length() - 1; i++) {
                String getstr = s.toString().substring(i, i + 1);
                if (getstr.equals(".")) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                int i = s.toString().indexOf(".");
                if (s.toString().length() - 3 > i) {
                    String getstr = s.toString().substring(0, i + 3);
                    mPrice.setText(getstr);
                    CharSequence charSequencePirce = mPrice.getText();
                    if (charSequencePirce instanceof Spannable) {
                        Spannable spanText = (Spannable) charSequencePirce;
                        Selection.setSelection(spanText, charSequencePirce.length());
                    }
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });

    initData();

    mHomeModel = new HomeModel(this);
    mHomeModel.addResponseListener(this);
    if (mDefaultReceiverId == 0) {
        mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
        mHomeData = mShared.getString("home_data", "");
        if ("".equals(mHomeData)) {
            mHomeModel.getServiceTypeList();
        } else {
            try {
                servicetypelistResponse response = new servicetypelistResponse();
                response.fromJson(new JSONObject(mHomeData));
                mHomeModel.publicServiceTypeList = response.services;
                setServiceTypeAdater();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } else {
        if (service_list != null && !"".equals(service_list)) {
            try {
                JSONObject userJson = new JSONObject(service_list);
                myservicelistResponse response = new myservicelistResponse();
                response.fromJson(userJson);
                for (int i = 0; i < response.services.size(); i++) {
                    SERVICE_TYPE service = new SERVICE_TYPE();
                    service = response.services.get(i).service_type;
                    mServiceTypeList.add(service);
                }
                if (mServiceTypeList.size() > 0) {
                    mTitleView.setEnabled(true);
                    mArrowImage.setVisibility(View.VISIBLE);
                    if (mServiceType != null) {
                        for (int i = 0; i < mServiceTypeList.size(); i++) {
                            if (mServiceType.id == mServiceTypeList.get(i).id) {
                                mC1PublishOrderAdapter = new C1_PublishOrderAdapter(this, mServiceTypeList, i);
                                mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                                mTitle.setText(mServiceTypeList.get(i).title);
                                mServiceTypeId = mServiceTypeList.get(i).id;
                                break;
                            }
                        }
                    } else {
                        mC1PublishOrderAdapter = new C1_PublishOrderAdapter(this, mServiceTypeList);
                        mServiceTypeListview.setAdapter(mC1PublishOrderAdapter);
                        mTitle.setText(getString(R.string.select_service));
                    }

                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
            mHomeData = mShared.getString("home_data", "");
            if ("".equals(mHomeData)) {
                mHomeModel.getServiceTypeList();
            } else {
                try {
                    servicetypelistResponse response = new servicetypelistResponse();
                    response.fromJson(new JSONObject(mHomeData));
                    mHomeModel.publicServiceTypeList = response.services;
                    setServiceTypeAdater();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    mLocationInfoModel = new LocationInfoModel(this);
    mLocationInfoModel.addResponseListener(this);
    mLocationInfoModel.get();

    mOrderPublishModel = new OrderPublishModel(this);
    mOrderPublishModel.addResponseListener(this);

    //??
    CharSequence charSequencePirce = mPrice.getText();
    if (charSequencePirce instanceof Spannable) {
        Spannable spanText = (Spannable) charSequencePirce;
        Selection.setSelection(spanText, charSequencePirce.length());
    }
    CharSequence charSequenceLocation = mLocation.getText();
    if (charSequenceLocation instanceof Spannable) {
        Spannable spanText = (Spannable) charSequenceLocation;
        Selection.setSelection(spanText, charSequenceLocation.length());
    }

    mVoice.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                closeKeyBoard();
                mVoice.setKeepScreenOn(true);
                mMaxTime = MAX_TIME;
                mVoiceView.setVisibility(View.VISIBLE);
                mAnimationDrawable.start();
                startRecording();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mVoice.setKeepScreenOn(false);
                mVoiceView.setVisibility(View.GONE);
                mAnimationDrawable.stop();
                if (mMaxTime > 28) {
                    mVoice.setEnabled(false);
                    Handler mHandler = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            stopRecording();
                            mVoice.setEnabled(true);
                        }
                    };
                    mHandler.sendEmptyMessageDelayed(0, 500);
                } else {
                    stopRecording();
                }
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
                mVoice.setKeepScreenOn(false);
                mVoiceView.setVisibility(View.GONE);
                mAnimationDrawable.stop();
                if (mMaxTime > 28) {
                    mVoice.setEnabled(false);
                    Handler mHandler = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            stopRecording();
                            mVoice.setEnabled(true);
                        }
                    };
                    mHandler.sendEmptyMessageDelayed(0, 500);
                } else {
                    stopRecording();
                }
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                mVoice.getParent().requestDisallowInterceptTouchEvent(true);
            }
            return false;
        }
    });

    mVoicePlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mPlayer == null) {
                File file = new File(mFileName);
                if (file.exists()) {
                    mPlayer = new MediaPlayer();
                    mVoicePlay.setBackgroundResource(R.anim.record_animation);
                    mAnimationDrawable2 = (AnimationDrawable) mVoicePlay.getBackground();
                    mAnimationDrawable2.setOneShot(false);
                    mAnimationDrawable2.start();
                    try {
                        mPlayer.setDataSource(mFileName);
                        mPlayer.prepare();
                        mPlayer.start();
                        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                mp.reset();
                                mPlayer = null;
                                mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn);
                                mAnimationDrawable2.stop();
                            }
                        });
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(C1_PublishOrderActivity.this, getString(R.string.file_does_not_exist),
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                mPlayer.release();
                mPlayer = null;
                mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn);
                mAnimationDrawable2.stop();
            }
        }
    });

    mVoiceReset.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mPlayer != null) {
                mPlayer.release();
                mPlayer = null;
                mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn);
                mAnimationDrawable2.stop();
            }
            File file = new File(mFileName);
            if (file.exists()) {
                file.delete();
            }
            mVoice.setVisibility(View.VISIBLE);
            mVoicePlay.setVisibility(View.GONE);
            mVoiceReset.setVisibility(View.GONE);
        }
    });

    mPublish.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            File file = new File(newFileName());
            int duration = 0;
            if (file.exists()) {
                MediaPlayer mp = MediaPlayer.create(C1_PublishOrderActivity.this, Uri.parse(mFileName));
                if (null != mp) {
                    duration = mp.getDuration();//? ms
                    mp.release();
                }
                if (duration % 1000 > 500) {
                    duration = duration / 1000 + 1;
                } else {
                    duration = duration / 1000;
                }
            } else {
                file = null;
            }
            int num = 0;
            try { // ??
                Date date = new Date();
                Date date1 = mFormat.parse(mFormat.format(date));
                Date date2 = mFormat.parse(mTime.getText().toString());
                num = date2.compareTo(date1);

                if (num < 0) {
                    long diff = date1.getTime() - date2.getTime();
                    long mins = diff / (1000 * 60);
                    if (mins < 3) {
                        num = 1;
                    }
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (mServiceTypeId == 0) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                        getString(R.string.select_service));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mPrice.getText().toString().equals("")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.price_range));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mPrice.getText().toString().equals("0.")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.right_price));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mTime.getText().toString().equals("")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.appoint_time));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (num < 0) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                        getString(R.string.wrong_appoint_time_hint));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else if (mLocation.getText().toString().equals("")) {
                ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                        getString(R.string.appoint_location_hint));
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            } else {
                mOrderPublishModel.publish(mPrice.getText().toString(), mTime.getText().toString(),
                        mLocation.getText().toString(), mText.getText().toString(), file, mServiceTypeId,
                        mDefaultReceiverId, duration);
            }
        }
    });
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.CaptureActivity.java

private void handleDecodeExternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {

    if (barcode != null) {
        viewfinderView.drawResultBitmap(barcode);
    }// ww w  . j  a va  2s .co m

    long resultDurationMS;
    if (getIntent() == null) {
        resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS;
    } else {
        resultDurationMS = getIntent().getLongExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS,
                DEFAULT_INTENT_RESULT_DURATION_MS);
    }

    // Since this message will only be shown for a second, just tell the
    // user what kind of
    // barcode was found (e.g. contact info) rather than the full contents,
    // which they won't
    // have time to read.
    if (resultDurationMS > 0) {
        statusView.setText(getString(resultHandler.getDisplayTitle()));
    }

    if (copyToClipboard && !resultHandler.areContentsSecure()) {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        CharSequence text = resultHandler.getDisplayContents();
        if (text != null) {
            clipboard.setText(text);
        }
    }

    if (source == IntentSource.NATIVE_APP_INTENT) {

        // Hand back whatever action they requested - this can be changed to
        // Intents.Scan.ACTION when
        // the deprecated intent is retired.
        Intent intent = new Intent(getIntent().getAction());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
        intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
        byte[] rawBytes = rawResult.getRawBytes();
        if (rawBytes != null && rawBytes.length > 0) {
            intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes);
        }
        Map<ResultMetadataType, ?> metadata = rawResult.getResultMetadata();
        if (metadata != null) {
            if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) {
                intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION,
                        metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString());
            }
            Integer orientation = (Integer) metadata.get(ResultMetadataType.ORIENTATION);
            if (orientation != null) {
                intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue());
            }
            String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL);
            if (ecLevel != null) {
                intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel);
            }
            Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS);
            if (byteSegments != null) {
                int i = 0;
                for (byte[] byteSegment : byteSegments) {
                    intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment);
                    i++;
                }
            }
        }
        sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS);

    } else if (source == IntentSource.PRODUCT_SEARCH_LINK) {

        // Reformulate the URL which triggered us into a query, so that the
        // request goes to the same
        // TLD as the scan URL.
        int end = sourceUrl.lastIndexOf("/scan");
        String replyURL = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents()
                + "&source=zxing";
        sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);

    } else if (source == IntentSource.ZXING_LINK) {

        // Replace each occurrence of RETURN_CODE_PLACEHOLDER in the
        // returnUrlTemplate
        // with the scanned code. This allows both queries and REST-style
        // URLs to work.
        if (returnUrlTemplate != null) {
            CharSequence codeReplacement = returnRaw ? rawResult.getText() : resultHandler.getDisplayContents();
            try {
                codeReplacement = URLEncoder.encode(codeReplacement.toString(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // can't happen; UTF-8 is always supported. Continue, I
                // guess, without encoding
            }
            String replyURL = returnUrlTemplate.replace(RETURN_CODE_PLACEHOLDER, codeReplacement);
            sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
        }

    }
}

From source file:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will take the url built to use the webservice
 * and will try to parse JSON from the webservice stream to get
 * the user and password if they are correct or not. In case correct, fills
 * the Android Account Manager./*from   w  w w .ja v a2s.c om*/
 *
 * <p>This method will throw a Toast message when user and password
 * are not valid
 *
 */

protected void startWebService(final CharSequence loginURL, final String username, final String password) {
    client.setBasicAuth(username, password, true);

    //new handler in case of login error in the thread
    handler = new Handler();

    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                int balanceCounter = 0;
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(loginURL.toString());
                Utils.writeNetworkLogFileOnSD(
                        Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString());
                httpGet.setHeader("Authorization", "Basic "
                        + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
                HttpResponse httpResponse = httpClient.execute(httpGet);
                InputStream inputStream = httpResponse.getEntity().getContent();
                Log.d("", loginURL.toString());

                ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream);
                Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext())
                        + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais));
                bais.reset();
                JsonFactory factory = new JsonFactory();
                JsonParser jsonParser = factory.createJsonParser(bais);
                JsonToken token = jsonParser.nextToken();

                if (token == JsonToken.START_OBJECT) {
                    balanceCounter++;
                    boolean idNextToHfId = false;
                    while (!(balanceCounter == 0)) {
                        token = jsonParser.nextToken();

                        if (token == JsonToken.START_OBJECT) {
                            balanceCounter++;
                        } else if (token == JsonToken.END_OBJECT) {
                            balanceCounter--;
                        } else if (token == JsonToken.FIELD_NAME) {
                            String object = jsonParser.getCurrentName();
                            switch (object) {
                            case "HealthFacilityId":
                                token = jsonParser.nextToken();
                                app.setLoggedInUserHealthFacilityId(jsonParser.getText());
                                Log.d("", "healthFacilityId is: " + jsonParser.getText());
                                idNextToHfId = true;
                                break;
                            case "Firstname":
                                token = jsonParser.nextToken();
                                app.setLoggedInFirstname(jsonParser.getText());
                                Log.d("", "firstname is: " + jsonParser.getText());
                                break;
                            case "Lastname":
                                token = jsonParser.nextToken();
                                app.setLoggedInLastname(jsonParser.getText());
                                Log.d("", "lastname is: " + jsonParser.getText());
                                break;
                            case "Username":
                                token = jsonParser.nextToken();
                                app.setLoggedInUsername(jsonParser.getText());
                                Log.d("", "username is: " + jsonParser.getText());
                                break;
                            case "Lastlogin":
                                token = jsonParser.nextToken();
                                Log.d("", "lastlogin is: " + jsonParser.getText());
                                break;
                            case "Id":
                                if (idNextToHfId) {
                                    token = jsonParser.nextToken();
                                    app.setLoggedInUserId(jsonParser.getText());
                                    Log.d("", "Id is: " + jsonParser.getText());
                                }
                                break;
                            default:
                                break;
                            }
                        }
                    }

                    Account account = new Account(username, ACCOUNT_TYPE);
                    AccountManager accountManager = AccountManager.get(LoginActivity.this);
                    //                        boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null);
                    boolean accountCreated = accountManager.addAccountExplicitly(account, password, null);

                    Bundle extras = LoginActivity.this.getIntent().getExtras();
                    if (extras != null) {
                        if (accountCreated) { //Pass the new account back to the account manager
                            AccountAuthenticatorResponse response = extras
                                    .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
                            Bundle res = new Bundle();
                            res.putString(AccountManager.KEY_ACCOUNT_NAME, username);
                            res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
                            res.putString(AccountManager.KEY_PASSWORD, password);
                            response.onResult(res);
                        }
                    }

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("secondSyncNeeded", true);
                    editor.commit();

                    ContentValues values = new ContentValues();
                    values.put(SQLHandler.SyncColumns.UPDATED, 1);
                    values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME());
                    values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME());
                    values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID());
                    values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID());
                    values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME());
                    values.put(SQLHandler.UserColumns.PASSWORD, password);
                    databaseHandler.addUser(values);

                    Log.d(TAG, "initiating offline for " + username + " password = " + password);
                    app.initializeOffline(username, password);

                    Intent intent;
                    if (prefs.getBoolean("synchronization_needed", true)) {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                    } else {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID());
                    }
                    app.setUsername(username);

                    startActivity(intent);
                }
                //if login failed show error
                else {
                    handler.post(new Runnable() {
                        public void run() {
                            progressDialog.show();
                            progressDialog.dismiss();
                            toastMessage("Login failed.\nPlease check your details!");
                            loginButton.setEnabled(true);
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    public void run() {
                        progressDialog.show();
                        progressDialog.dismiss();
                        toastMessage("Login failed Login failed.\n"
                                + "Please check your details or your web connectivity");
                        loginButton.setEnabled(true);

                    }
                });
                e.printStackTrace();
            }
        }
    });
    thread.start();

}

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

@Override
public QueryDeparturesResult queryDepartures(String stationId, @Nullable Date time, int maxDepartures,
        boolean equivs) throws IOException {
    // The stationId does not need the / character escaped
    HttpUrl url = buildApiUrl("locations/" + stationId + "/departure-times", new ArrayList<QueryParameter>());
    final CharSequence page;
    try {/* ww  w  . j  a va2  s . co  m*/
        page = httpClient.get(url);
    } catch (InternalErrorException | NotFoundException e) {
        return new QueryDeparturesResult(this.resultHeader, QueryDeparturesResult.Status.INVALID_STATION);
    } catch (Exception e) {
        return new QueryDeparturesResult(this.resultHeader, QueryDeparturesResult.Status.SERVICE_DOWN);
    }

    QueryDeparturesResult queryDeparturesResult = new QueryDeparturesResult(this.resultHeader);
    try {
        JSONObject head = new JSONObject(page.toString());
        JSONArray tabs = head.getJSONArray("tabs");
        for (int t = 0; t < tabs.length(); t++) {
            JSONObject tab = tabs.getJSONObject(t);

            JSONArray locations = tab.getJSONArray("locations");
            for (int l = 0; l < locations.length(); l++) {
                JSONObject location = locations.getJSONObject(l);

                // Ignore if equivs is false and stationId is not a strict match
                if (!equivs && !location.getString("id").equals(stationId)) {
                    continue;
                }

                // Get list of departures
                List<Departure> departuresResult = new ArrayList<>();
                List<LineDestination> lineDestinationResult = new ArrayList<>();

                JSONArray departures = tab.getJSONArray("departures");
                for (int i = 0; i < departures.length(); i++) {
                    JSONObject departure = departures.getJSONObject(i);
                    JSONObject mode = departure.getJSONObject("mode");

                    departuresResult.add(departureFromJSONObject(departure));

                    Product lineProduct = productFromMode(mode.getString("type"), mode.getString("name"));
                    lineDestinationResult.add(new LineDestination(
                            new Line(null, departure.getString("operatorName"), lineProduct,
                                    mode.getString("name"), null, Standard.STYLES.get(lineProduct), null, null),
                            new Location(LocationType.STATION, null, 0, 0, null,
                                    departure.getString("destinationName"), EnumSet.of(lineProduct))));
                }

                // Add to result object
                queryDeparturesResult.stationDepartures.add(new StationDepartures(
                        locationFromJSONObject(location), departuresResult, lineDestinationResult));
            }
        }

        return queryDeparturesResult;
    } catch (final JSONException x) {
        throw new RuntimeException("cannot parse: '" + page + "' on " + url, x);
    }
}

From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java

private void updateOfflineMissedCalls() {

    String from_summary = "", noc = "", from_detailed = "", lt = "", ct = "";
    Cursor c;/* w ww . jav  a 2  s. c  o  m*/
    String time = "", value;
    try {

        dbContacts = new DBContacts(mcontext);
        //   dbContacts.openToWrite();
        dbContacts.openToRead();
        c = dbContacts.fetch_details_from_MIssedCall_Offline_Table();

        if (c.getCount() > 0) {
            c.moveToFirst();
            value = c.getString(2);
            time = "&time=" + value;
            //  time = "&time=" + "1408434902";
        }

        c.close();
        dbContacts.close();

        Log.d("webService App Resume", "called");
        HttpParams p = new BasicHttpParams();
        p.setParameter("user", "1");
        HttpClient httpclient = new DefaultHttpClient(p);
        String url = "http://ip.roaming4world.com/esstel/app_resume_info.php?contact="
                + prefs.getString(stored_user_country_code, "NoValue")
                + prefs.getString(stored_user_mobile_no, "NoValue") + time;

        Log.d("url", url + " #");

        HttpGet httpget = new HttpGet(url);
        ResponseHandler<String> responseHandler;
        String responseBody;
        responseHandler = new BasicResponseHandler();
        responseBody = httpclient.execute(httpget, responseHandler);

        dbContacts.openToWrite();

        JSONObject json = new JSONObject(responseBody);

        Log.d("response11", json + " #");

        if (json.getString("verify_from_pc").equals("true")) {
            Intent i = new Intent(mcontext, DesktopVerificationcode_Activity.class);
            i.putExtra("verify_code", json.getString("verify_code"));
            i.putExtra("countdown_time", json.getString("countdown_time"));
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mcontext.startActivity(i);
        }

        prefs.edit().putString(stored_min_call_credit, json.getString("min_call_credit")).commit();
        prefs.edit().putString(stored_user_bal, json.getString("user_bal")).commit();
        prefs.edit().putString(stored_server_ipaddress, json.getString("server_ip")).commit();

        Log.d("stored_server_ip address", json.getString("server_ip") + " #");
        Log.d("stored_user_bal", json.getString("user_bal") + " #");

        if (json.getString("valid").equals("true")) {

            JSONArray summary = json.getJSONArray("summary");
            JSONArray detailed = json.getJSONArray("detailed");

            for (int i = 0; i < summary.length(); i++) {
                JSONObject summarydata = summary.getJSONObject(i);
                from_summary = summarydata.getString("from");
                noc = summarydata.getString("noc");
                lt = summarydata.getString("lt");

                Log.d("from_summary", from_summary + " #");
                Log.d("noc", noc + " #");
                Log.d("lt", lt + " #");

                dbContacts.insert_MIssedCall_Offline_detail_in_db(from_summary, lt, noc);

                /*
                mBuilder.setSmallIcon(R.drawable.notification_icon);
                mBuilder.setContentTitle("Missed call (" + noc +")");
                mBuilder.setContentText(from_summary + "   " + lt);
                mBuilder.setContentIntent(resultPendingIntent);
                mNotificationManager.notify(Integer.parseInt(lt), mBuilder.build());
                */
                String count = "Missed call (" + noc + ")";

                CharSequence dateText = DateUtils.getRelativeTimeSpanString(Long.parseLong(lt) * 1000,
                        System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS,
                        DateUtils.FORMAT_ABBREV_RELATIVE);

                String num_date = from_summary + "   last on " + dateText.toString();

                showNotification(count, num_date, Integer.parseInt(lt));

            }

            for (int i = 0; i < detailed.length(); i++) {
                JSONObject detaileddata = detailed.getJSONObject(i);
                from_detailed = detaileddata.getString("from");
                ct = detaileddata.getString("ct");

                Log.d("from_detailed", from_detailed + " #");
                Log.d("ct", ct + " #");

                dbContacts.insert_MIssedCall_detail_in_db(from_detailed, ct);
            }

            dbContacts.close();

        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:cn.sinobest.jzpt.framework.utils.string.StringUtils.java

/**
 * HTML/*from  w w  w  . jav  a  2  s. c o m*/
 */
public static CharSequence escapeHtml(CharSequence s, boolean unicode) {
    if (unicode)
        return StringEscapeUtils.escapeHtml3(s.toString());
    StringBuilder sb = new StringBuilder(s.length() + 16);
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        int n = htmlEscEntities.indexOf(c);
        if (n > -1) {
            sb.append(htmlEscapeSequence[n]);
        } else {
            sb.append(c);
        }
    }
    return sb.length() == s.length() ? s : sb.toString();// string
}

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

protected final QueryDeparturesResult jsonStationBoard(final String stationId, final @Nullable Date time,
        final int maxDepartures, final boolean equivs) throws IOException {
    final Calendar c = new GregorianCalendar(timeZone);
    c.setTime(time);//from   www  .j  a va2s  .  com
    final CharSequence jsonDate = jsonDate(c);
    final CharSequence jsonTime = jsonTime(c);
    final CharSequence normalizedStationId = normalizeStationId(stationId);
    final CharSequence stbFltrEquiv = Boolean.toString(!equivs);
    final CharSequence maxJny = Integer.toString(maxDepartures != 0 ? maxDepartures : DEFAULT_MAX_DEPARTURES);
    final CharSequence getPasslist = Boolean.toString(true); // traffic expensive
    final String request = wrapJsonApiRequest("StationBoard", "{\"type\":\"DEP\"," //
            + "\"date\":\"" + jsonDate + "\"," //
            + "\"time\":\"" + jsonTime + "\"," //
            + "\"stbLoc\":{\"type\":\"S\"," + "\"state\":\"F\"," // F/M
            + "\"extId\":" + JSONObject.quote(normalizedStationId.toString()) + "}," //
            + "\"stbFltrEquiv\":" + stbFltrEquiv + ",\"maxJny\":" + maxJny + ",\"getPasslist\":" + getPasslist
            + "}", false);

    final HttpUrl url = checkNotNull(mgateEndpoint);
    final CharSequence page = httpClient.get(url, request, "application/json");

    try {
        final JSONObject head = new JSONObject(page.toString());
        final String headErr = head.optString("err", null);
        if (headErr != null)
            throw new RuntimeException(headErr);
        final ResultHeader header = new ResultHeader(network, SERVER_PRODUCT, head.getString("ver"), null, 0,
                null);
        final QueryDeparturesResult result = new QueryDeparturesResult(header);

        final JSONArray svcResList = head.getJSONArray("svcResL");
        checkState(svcResList.length() == 1);
        final JSONObject svcRes = svcResList.optJSONObject(0);
        checkState("StationBoard".equals(svcRes.getString("meth")));
        final String err = svcRes.getString("err");
        if (!"OK".equals(err)) {
            final String errTxt = svcRes.getString("errTxt");
            log.debug("Hafas error: {} {}", err, errTxt);
            if ("LOCATION".equals(err) && "HCI Service: location missing or invalid".equals(errTxt))
                return new QueryDeparturesResult(header, QueryDeparturesResult.Status.INVALID_STATION);
            if ("FAIL".equals(err) && "HCI Service: request failed".equals(errTxt))
                return new QueryDeparturesResult(header, QueryDeparturesResult.Status.SERVICE_DOWN);
            throw new RuntimeException(err + " " + errTxt);
        } else if ("1.10".equals(apiVersion) && svcRes.toString().length() == 170) {
            // horrible hack, because API version 1.10 doesn't signal invalid stations via error
            return new QueryDeparturesResult(header, QueryDeparturesResult.Status.INVALID_STATION);
        }
        final JSONObject res = svcRes.getJSONObject("res");

        final JSONObject common = res.getJSONObject("common");
        /* final List<String[]> remarks = */ parseRemList(common.getJSONArray("remL"));
        final List<String> operators = parseOpList(common.getJSONArray("opL"));
        final List<Line> lines = parseProdList(common.getJSONArray("prodL"), operators);
        final JSONArray locList = common.getJSONArray("locL");
        final List<Location> locations = parseLocList(locList);

        final JSONArray jnyList = res.optJSONArray("jnyL");
        if (jnyList != null) {
            for (int iJny = 0; iJny < jnyList.length(); iJny++) {
                final JSONObject jny = jnyList.getJSONObject(iJny);
                final JSONObject stbStop = jny.getJSONObject("stbStop");

                final String stbStopPlatformS = stbStop.optString("dPlatfS", null);
                c.clear();
                ParserUtils.parseIsoDate(c, jny.getString("date"));
                final Date baseDate = c.getTime();

                final Date plannedTime = parseJsonTime(c, baseDate, stbStop.getString("dTimeS"));

                final Date predictedTime = parseJsonTime(c, baseDate, stbStop.optString("dTimeR", null));

                final Line line = lines.get(stbStop.getInt("dProdX"));

                final Location location = equivs ? locations.get(stbStop.getInt("locX"))
                        : new Location(LocationType.STATION, stationId);
                final Position position = normalizePosition(stbStopPlatformS);

                final String jnyDirTxt = jny.getString("dirTxt");
                final JSONArray stopList = jny.optJSONArray("stopL");
                final Location destination;
                if (stopList != null) {
                    final int lastStopIdx = stopList.getJSONObject(stopList.length() - 1).getInt("locX");
                    final String lastStopName = locList.getJSONObject(lastStopIdx).getString("name");
                    if (jnyDirTxt.equals(lastStopName))
                        destination = locations.get(lastStopIdx);
                    else
                        destination = new Location(LocationType.ANY, null, null, jnyDirTxt);
                } else {
                    destination = new Location(LocationType.ANY, null, null, jnyDirTxt);
                }

                final Departure departure = new Departure(plannedTime, predictedTime, line, position,
                        destination, null, null);

                StationDepartures stationDepartures = findStationDepartures(result.stationDepartures, location);
                if (stationDepartures == null) {
                    stationDepartures = new StationDepartures(location, new ArrayList<Departure>(8), null);
                    result.stationDepartures.add(stationDepartures);
                }

                stationDepartures.departures.add(departure);
            }
        }

        // sort departures
        for (final StationDepartures stationDepartures : result.stationDepartures)
            Collections.sort(stationDepartures.departures, Departure.TIME_COMPARATOR);

        return result;
    } catch (final JSONException x) {
        throw new ParserException("cannot parse json: '" + page + "' on " + url, x);
    }
}

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

@Override
public QueryTripsResult queryTrips(final Location from, final @Nullable Location via, final Location to,
        Date date, boolean dep, final @Nullable Set<Product> products, final @Nullable Optimize optimize,
        final @Nullable WalkSpeed walkSpeed, final @Nullable Accessibility accessibility,
        @Nullable Set<Option> options) throws IOException {
    // The EXACT_POINTS feature generates an about 50% bigger API response, probably well compressible.
    final boolean EXACT_POINTS = true;
    final List<Location> ambiguousFrom = new ArrayList<>();
    String fromString = generateLocation(from, ambiguousFrom);

    final List<Location> ambiguousVia = new ArrayList<>();
    String viaString = generateLocation(via, ambiguousVia);

    final List<Location> ambiguousTo = new ArrayList<>();
    String toString = generateLocation(to, ambiguousTo);

    if (!ambiguousFrom.isEmpty() || !ambiguousVia.isEmpty() || !ambiguousTo.isEmpty()) {
        return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                ambiguousFrom.isEmpty() ? null : ambiguousFrom, ambiguousVia.isEmpty() ? null : ambiguousVia,
                ambiguousTo.isEmpty() ? null : ambiguousTo);
    }/*from  ww w.  j ava  2s  .c  o m*/

    if (fromString == null) {
        return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                QueryTripsResult.Status.UNKNOWN_FROM);
    }
    if (via != null && viaString == null) {
        return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                QueryTripsResult.Status.UNKNOWN_VIA);
    }
    if (toString == null) {
        return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                QueryTripsResult.Status.UNKNOWN_TO);
    }

    final HttpUrl.Builder url = API_BASE.newBuilder();
    url.addQueryParameter("eID", "tx_vrsinfo_ass2_router");
    url.addQueryParameter("f", fromString);
    url.addQueryParameter("t", toString);
    if (via != null) {
        url.addQueryParameter("v", via.id);
    }
    url.addQueryParameter(dep ? "d" : "a", formatDate(date));
    url.addQueryParameter("s", "t");
    if (!products.equals(Product.ALL))
        url.addQueryParameter("p", generateProducts(products));
    url.addQueryParameter("o", "v" + (EXACT_POINTS ? "p" : ""));

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

    try {
        final List<Trip> trips = new ArrayList<>();
        final JSONObject head = new JSONObject(page.toString());
        final String error = Strings.emptyToNull(head.optString("error", "").trim());
        if (error != null) {
            if (error.equals("ASS2-Server lieferte leere Antwort."))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.SERVICE_DOWN);
            else if (error.equals("Zeitberschreitung bei der Verbindung zum ASS2-Server"))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.SERVICE_DOWN);
            else if (error.equals("Server Error"))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.SERVICE_DOWN);
            else if (error.equals("Keine Verbindungen gefunden."))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.NO_TRIPS);
            else if (error.startsWith("Keine Verbindung gefunden."))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.NO_TRIPS);
            else if (error.equals("Origin invalid."))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.UNKNOWN_FROM);
            else if (error.equals("Via invalid."))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.UNKNOWN_VIA);
            else if (error.equals("Destination invalid."))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.UNKNOWN_TO);
            else if (error.equals("Fehlerhaftes Ziel"))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.UNKNOWN_TO);
            else if (error.equals("Produkt ungltig."))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.NO_TRIPS);
            else if (error.equals("Keine Route."))
                return new QueryTripsResult(new ResultHeader(NetworkId.VRS, SERVER_PRODUCT),
                        QueryTripsResult.Status.NO_TRIPS);
            else
                throw new IllegalStateException("unknown error: " + error);
        }
        final JSONArray routes = head.getJSONArray("routes");
        final Context context = new Context();
        // for all routes
        for (int iRoute = 0; iRoute < routes.length(); iRoute++) {
            final JSONObject route = routes.getJSONObject(iRoute);
            final JSONArray segments = route.getJSONArray("segments");
            List<Leg> legs = new ArrayList<>();
            Location tripOrigin = null;
            Location tripDestination = null;
            // for all segments
            for (int iSegment = 0; iSegment < segments.length(); iSegment++) {
                final JSONObject segment = segments.getJSONObject(iSegment);
                final String type = segment.getString("type");
                final JSONObject origin = segment.getJSONObject("origin");
                final LocationWithPosition segmentOriginLocationWithPosition = parseLocationAndPosition(origin);
                Location segmentOrigin = segmentOriginLocationWithPosition.location;
                final Position segmentOriginPosition = segmentOriginLocationWithPosition.position;
                if (iSegment == 0) {
                    // special case: first origin is an address
                    if (from.type == LocationType.ADDRESS) {
                        segmentOrigin = from;
                    }
                    tripOrigin = segmentOrigin;
                }
                final JSONObject destination = segment.getJSONObject("destination");
                final LocationWithPosition segmentDestinationLocationWithPosition = parseLocationAndPosition(
                        destination);
                Location segmentDestination = segmentDestinationLocationWithPosition.location;
                final Position segmentDestinationPosition = segmentDestinationLocationWithPosition.position;
                if (iSegment == segments.length() - 1) {
                    // special case: last destination is an address
                    if (to.type == LocationType.ADDRESS) {
                        segmentDestination = to;
                    }
                    tripDestination = segmentDestination;
                }
                List<Stop> intermediateStops = new ArrayList<>();
                final JSONArray vias = segment.optJSONArray("vias");
                if (vias != null) {
                    for (int iVia = 0; iVia < vias.length(); iVia++) {
                        final JSONObject viaJsonObject = vias.getJSONObject(iVia);
                        final LocationWithPosition viaLocationWithPosition = parseLocationAndPosition(
                                viaJsonObject);
                        final Location viaLocation = viaLocationWithPosition.location;
                        final Position viaPosition = viaLocationWithPosition.position;
                        Date arrivalPlanned = null;
                        Date arrivalPredicted = null;
                        if (viaJsonObject.has("arrivalScheduled")) {
                            arrivalPlanned = parseDateTime(viaJsonObject.getString("arrivalScheduled"));
                            arrivalPredicted = (viaJsonObject.has("arrival"))
                                    ? parseDateTime(viaJsonObject.getString("arrival"))
                                    : null;
                        } else if (segment.has("arrival")) {
                            arrivalPlanned = parseDateTime(viaJsonObject.getString("arrival"));
                        }
                        final Stop intermediateStop = new Stop(viaLocation, false /* arrival */, arrivalPlanned,
                                arrivalPredicted, viaPosition, viaPosition);
                        intermediateStops.add(intermediateStop);
                    }
                }
                Date departurePlanned = null;
                Date departurePredicted = null;
                if (segment.has("departureScheduled")) {
                    departurePlanned = parseDateTime(segment.getString("departureScheduled"));
                    departurePredicted = (segment.has("departure"))
                            ? parseDateTime(segment.getString("departure"))
                            : null;
                    if (iSegment == 0) {
                        context.departure(departurePredicted);
                    }
                } else if (segment.has("departure")) {
                    departurePlanned = parseDateTime(segment.getString("departure"));
                    if (iSegment == 0) {
                        context.departure(departurePlanned);
                    }
                }
                Date arrivalPlanned = null;
                Date arrivalPredicted = null;
                if (segment.has("arrivalScheduled")) {
                    arrivalPlanned = parseDateTime(segment.getString("arrivalScheduled"));
                    arrivalPredicted = (segment.has("arrival")) ? parseDateTime(segment.getString("arrival"))
                            : null;
                    if (iSegment == segments.length() - 1) {
                        context.arrival(arrivalPredicted);
                    }
                } else if (segment.has("arrival")) {
                    arrivalPlanned = parseDateTime(segment.getString("arrival"));
                    if (iSegment == segments.length() - 1) {
                        context.arrival(arrivalPlanned);
                    }
                }
                long traveltime = segment.getLong("traveltime");
                long distance = segment.optLong("distance", 0);
                Line line = null;
                String direction = null;
                JSONObject lineObject = segment.optJSONObject("line");
                if (lineObject != null) {
                    line = parseLine(lineObject);
                    direction = lineObject.optString("direction", null);
                }
                StringBuilder message = new StringBuilder();
                JSONArray infos = segment.optJSONArray("infos");
                if (infos != null) {
                    for (int k = 0; k < infos.length(); k++) {
                        // TODO there can also be a "header" string
                        if (k > 0) {
                            message.append(", ");
                        }
                        message.append(infos.getJSONObject(k).getString("text"));
                    }
                }

                List<Point> points = new ArrayList<>();
                points.add(new Point(segmentOrigin.lat, segmentOrigin.lon));
                if (EXACT_POINTS && segment.has("polygon")) {
                    parsePolygon(segment.getString("polygon"), points);
                } else {
                    for (Stop intermediateStop : intermediateStops) {
                        points.add(new Point(intermediateStop.location.lat, intermediateStop.location.lon));
                    }
                }
                points.add(new Point(segmentDestination.lat, segmentDestination.lon));
                if (type.equals("walk")) {
                    if (departurePlanned == null)
                        departurePlanned = legs.get(legs.size() - 1).getArrivalTime();
                    if (arrivalPlanned == null)
                        arrivalPlanned = new Date(departurePlanned.getTime() + traveltime * 1000);

                    legs.add(new Trip.Individual(Trip.Individual.Type.WALK, segmentOrigin, departurePlanned,
                            segmentDestination, arrivalPlanned, points, (int) distance));
                } else if (type.equals("publicTransport")) {
                    legs.add(new Trip.Public(line,
                            direction != null
                                    ? new Location(LocationType.STATION, null /* id */, null /* place */,
                                            direction)
                                    : null,
                            new Stop(segmentOrigin, true /* departure */, departurePlanned, departurePredicted,
                                    segmentOriginPosition, segmentOriginPosition),
                            new Stop(segmentDestination, false /* departure */, arrivalPlanned,
                                    arrivalPredicted, segmentDestinationPosition, segmentDestinationPosition),
                            intermediateStops, points, Strings.emptyToNull(message.toString())));
                } else {
                    throw new IllegalStateException("unhandled type: " + type);
                }
            }
            int changes = route.getInt("changes");
            List<Fare> fares = parseFare(route.optJSONObject("costs"));

            trips.add(new Trip(null /* id */, tripOrigin, tripDestination, legs, fares, null /* capacity */,
                    changes));
        }
        long serverTime = parseDateTime(head.getString("generated")).getTime();
        final ResultHeader header = new ResultHeader(NetworkId.VRS, SERVER_PRODUCT, null, null, serverTime,
                null);
        context.from = from;
        context.to = to;
        context.via = via;
        context.products = products;
        if (trips.size() == 1) {
            if (dep)
                context.disableLater();
            else
                context.disableEarlier();
        }
        return new QueryTripsResult(header, url.build().toString(), from, via, to, context, trips);
    } catch (final JSONException x) {
        throw new RuntimeException("cannot parse: '" + page + "' on " + url, x);
    } catch (final ParseException e) {
        throw new RuntimeException("cannot parse: '" + page + "' on " + url, e);
    }
}