Example usage for java.util Calendar HOUR

List of usage examples for java.util Calendar HOUR

Introduction

In this page you can find the example usage for java.util Calendar HOUR.

Prototype

int HOUR

To view the source code for java.util Calendar HOUR.

Click Source Link

Document

Field number for get and set indicating the hour of the morning or afternoon.

Usage

From source file:com.clustercontrol.systemlog.bean.SyslogMessage.java

/**
 * syslog????????SyslogMessage????API<br>
 * <br>//  ww w  .ja  va2s.c o  m
 * <b>???</b><br>
 * 1. ???????????????<br>
 * 2. ???????????<br>
 * @param syslog syslog?
 * @return SyslogMessage
 * @throws ParseException syslog???????????
 * @throws HinemosUnknown 
 */
public static SyslogMessage parse(String syslog) throws ParseException, HinemosUnknown {
    if (log.isDebugEnabled()) {
        log.debug("parsing syslog : " + syslog);
    }

    // [0]:, [1]:(MMM), [2]:(dd), [3]:(HH), [4]:(mm), [5]:(ss), [6]:??, [7]:
    // ?{1,date,MMM dd HH:mm:ss}????????????1970????
    // ????????2/29???3/1?????(1970???????)
    MessageFormat syslogFormat = new MessageFormat("<{0,number,integer}>{1} {2} {3}:{4}:{5} {6} {7}",
            Locale.ENGLISH);

    // ??????
    Object[] syslogArgs = syslogFormat.parse(syslog);

    // RFC3164??????????????????
    if ("".equals(syslogArgs[SYSLOG_FORMAT_DAY])) {
        syslogFormat = new MessageFormat("<{0,number,integer}>{1}  {2} {3}:{4}:{5} {6} {7}", Locale.ENGLISH);
        syslogArgs = syslogFormat.parse(syslog);
    }

    if (syslogArgs == null)
        throw new HinemosUnknown("different syslog pattern");

    if (log.isDebugEnabled()) {
        int i = 0;
        for (Object arg : syslogArgs) {
            log.debug(String.format("syslog args [%d] : %s", i++, arg.toString()));
        }
    }

    // ???????(H)
    Integer syslogEffectiveTime = HinemosPropertyUtil
            .getHinemosPropertyNum("monitor.systemlog.period.hour", Long.valueOf(SYSLOG_DEFAULT_PERIOD_HOUR))
            .intValue();

    // 0???????????
    if (syslogEffectiveTime <= 0) {
        syslogEffectiveTime = SYSLOG_DEFAULT_PERIOD_HOUR;
    }

    Calendar nowCal = HinemosTime.getCalendarInstance();

    // ??(?)
    int year = nowCal.get(Calendar.YEAR) + 1;
    int month = editCalendarMonth((String) syslogArgs[SYSLOG_FORMAT_MONTH]);
    int dayOfMonth = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_DAY]);
    int hourOfDay = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_HH]);
    int minute = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_MM]);
    int second = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_SS]);

    // ?
    List<Calendar> checkCalList = new ArrayList<Calendar>();
    // (??
    Calendar syslogEffectiveCal = (Calendar) nowCal.clone();
    syslogEffectiveCal.add(Calendar.HOUR, syslogEffectiveTime);

    // ???
    for (int i = 0; checkCalList.size() < 2; i++) {

        // ??????
        if (LEAPYEAR_CHECK_COUNT <= i) {
            break;
        }
        Calendar syslogCheckCal = new GregorianCalendar(year, month, dayOfMonth, hourOfDay, minute, second);
        year--;

        // ???????(??)
        if (syslogEffectiveCal.compareTo(syslogCheckCal) < 0) {
            continue;
        }
        // ??????????????
        if (dayOfMonth != syslogCheckCal.get(Calendar.DAY_OF_MONTH)) {
            continue;
        }
        // ????
        checkCalList.add(syslogCheckCal);
    }

    Calendar editSyslogCal = null;

    // ?????
    if (checkCalList.size() > 0) {
        long absMinMillis = Long.MAX_VALUE;
        for (int i = 0; i < checkCalList.size(); i++) {
            long absDiff = Math.abs(checkCalList.get(i).getTimeInMillis() - nowCal.getTimeInMillis());
            if (absDiff < absMinMillis) {
                // ??????
                absMinMillis = absDiff;
                editSyslogCal = checkCalList.get(i);
            }
        }
    } else {
        // ??????
        editSyslogCal = new GregorianCalendar(nowCal.get(Calendar.YEAR), month, dayOfMonth, hourOfDay, minute,
                second);
        log.warn("System log date is invalid : " + syslog);
    }

    int pri = ((Long) syslogArgs[SYSLOG_FORMAT_PRIORITY]).intValue();
    String hostname = (String) syslogArgs[SYSLOG_FORMAT_HOSTNAME];
    String msg = (String) syslogArgs[SYSLOG_FORMAT_MESSAGE];
    Date date = editSyslogCal.getTime();

    // ??
    SyslogMessage instance = new SyslogMessage(getFacility((int) pri), getSeverity((int) pri), date.getTime(),
            hostname, msg, syslog);
    if (log.isDebugEnabled()) {
        log.debug("parsed syslog : " + instance);
    }

    return instance;
}

From source file:com.sourcey.materiallogindemo.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Permission StrictMode
    if (Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }//from w  w  w .  ja  v a2s  .c  o  m

    Bundle extras = getIntent().getExtras();
    // ?? null
    if (extras != null) {
        user_id = extras.getString("user_id");
        name = extras.getString("name");
        image = extras.getString("image");
    }

    txtStart = (AutoCompleteTextView) findViewById(R.id.txtStart);
    txtEnd = (AutoCompleteTextView) findViewById(R.id.txtEnd);
    txtAppoint = (AutoCompleteTextView) findViewById(R.id.txtAppoint);
    txtTime = (EditText) findViewById(R.id.txtTime);
    txtLicensePlate = (EditText) findViewById(R.id.txtLicensePlate);
    btnImageProfile = (ImageButton) findViewById(R.id.btnImageProfile);
    txtName = (TextView) findViewById(R.id.txtName);

    radioGroup = (RadioGroup) findViewById(R.id.radio);

    badge = (TextView) findViewById(R.id.badge);

    final Button btnSave = (Button) findViewById(R.id.btnSave);
    final Button btnCancel = (Button) findViewById(R.id.btnCancel);
    //final Button btnPost = (Button) findViewById(R.id.btnPost);
    final Button btnFeed = (Button) findViewById(R.id.btnFeed);
    final Button btnSearch = (Button) findViewById(R.id.btnSearch);
    final Button btnNotification = (Button) findViewById(R.id.btnNotification);
    final Button btnLogout = (Button) findViewById(R.id.btnLogout);
    final Button btnTime = (Button) findViewById(R.id.btnTime);
    final Button btnComment = (Button) findViewById(R.id.btnComment);
    // get the current time
    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    mHour = c.get(Calendar.HOUR);
    mMinute = c.get(Calendar.MINUTE);

    String url = getString(R.string.url) + "notification.php";
    notifications = master.GetCountNotification(user_id, url);
    if (notifications > 0) {
        badge.setVisibility(View.VISIBLE);
        badge.setText(String.valueOf(notifications));
    } else {
        badge.setVisibility(View.GONE);
    }

    // display the current time
    updateCurrentTime();
    LoadItems();
    //Create adapter
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, item);
    txtStart.setThreshold(1);
    //Set adapter to AutoCompleteTextView
    txtStart.setAdapter(adapter);
    txtStart.setOnItemSelectedListener(this);
    txtStart.setOnItemClickListener(this);

    //Set adapter to AutoCompleteTextView
    txtEnd.setAdapter(adapter);
    txtEnd.setOnItemSelectedListener(this);
    txtEnd.setOnItemClickListener(this);
    //Create adapter

    //Set adapter to AutoCompleteTextView
    txtAppoint.setAdapter(adapter);
    txtAppoint.setOnItemSelectedListener(this);
    txtAppoint.setOnItemClickListener(this);

    txtName.setText(name);
    String photo_url_str = getString(R.string.url_image)
            + (("".equals(image.trim()) || image == null) ? "no.png" : image.trim());
    URL newurl = null;
    try {
        newurl = new URL(photo_url_str);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    Bitmap b = null;
    try {
        b = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    btnImageProfile.setImageBitmap(Bitmap.createScaledBitmap(b, 80, 80, false));

    btnSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogMap();
        }
    });

    btnTime.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(TIME_DIALOG_ID);
        }
    });
    btnSave.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int selectedId = radioGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            type = ((RadioButton) findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
            if ("".equals(type)) {
                type = "CAR";
            } else {
                type = "NOCAR";
            }
            /* Toast.makeText(getBaseContext(),
                type, Toast.LENGTH_SHORT).show();*/

            start = txtStart.getText().toString();
            end = txtEnd.getText().toString();
            meeting_point = txtAppoint.getText().toString();
            map_datetime = datePoint.trim();
            license_plate = txtLicensePlate.getText().toString();

            if ("".equals(start) || "".equals(end) || "".equals(meeting_point) || "".equals(map_datetime)
                    || "".equals(license_plate) || "".equals(txtTime.getText().toString().trim())) {
                MessageDialog("???");
            } else {
                String url = getString(R.string.url) + "save.php";
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("user_id", user_id));
                params.add(new BasicNameValuePair("start", start));
                params.add(new BasicNameValuePair("end", end));
                params.add(new BasicNameValuePair("meeting_point", meeting_point));
                params.add(new BasicNameValuePair("map_datetime", map_datetime));
                params.add(new BasicNameValuePair("license_plate", license_plate));
                params.add(new BasicNameValuePair("type", type));

                String resultServer = getHttpPost(url, params);

                JSONObject c;
                try {
                    c = new JSONObject(resultServer);
                    String status = c.getString("status");
                    MessageDialog(status);
                    if ("?".equals(status)) {
                        ClearData();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    MessageDialog(e.getMessage());
                }
            }
        }
    });

    btnCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            ClearData();
        }
    });

    /*        btnPost.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
       *//* Intent i = new Intent(getBaseContext(), PostItemActivity.class);
          i.putExtra("user_id", user_id);
          startActivity(i);*//*
                              // get selected radio button from radioGroup
                                      
                              }
                              });*/

    btnFeed.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            /*  if(!start.getText().toString().equals("") &&!end.getText().toString().equals("")&&
                !point.getText().toString().equals("")&&!time.getText().toString().equals("")&&!license.getText().toString().equals("")) {
            Intent newActivity = new Intent(MainActivity.this, commit.class);
            startActivity(newActivity);
              }*/
            Intent i = new Intent(getBaseContext(), PostItemActivity.class);
            i.putExtra("user_id", user_id);
            i.putExtra("name", name);
            i.putExtra("image", image);
            startActivity(i);
        }
    });
    btnNotification.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getBaseContext(), NotificationActivity.class);
            i.putExtra("user_id", user_id);
            i.putExtra("name", name);
            i.putExtra("image", image);
            startActivity(i);
        }
    });
    btnLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getBaseContext(), LoginActivity.class);
            startActivity(i);
        }
    });
    btnComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getBaseContext(), CommentActivity.class);
            i.putExtra("user_id", user_id);
            i.putExtra("name", name);
            i.putExtra("image", image);
            startActivity(i);
        }
    });
    /*      final Button btn5 = (Button) findViewById(R.id.button3);
          btn5.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
    }
          });*/

    //RadioGroup car = (RadioGroup) this.findViewById ( R.id.textView18 );

    // car.check(R.id.radioButton);
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    //client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:com.ecofactor.qa.automation.consumerapi.DRAPI_Test.java

/**
 * Test_create_dr_event_nve.// w  ww  . ja  v  a 2 s. c  o  m
 */
@Test(groups = {
        Groups.SANITY1 }, dataProvider = "createDRAllGatewaysNVE", dataProviderClass = DRAPIDataProvider.class, priority = 3)
public void test_create_dr_event_nve(final String drUrl, final String programID, final String eventID,
        final String targetType, final String targetAllJson) {

    long timeStamp = System.currentTimeMillis();

    String directURL = drUrl;

    directURL = directURL.replaceFirst("<program_id>", programID)
            .replaceFirst("<event_id>", eventID + timeStamp).replaceFirst("<target_type>", targetType)
            .replaceFirst("<target_all>", "true");

    String json = targetAllJson;
    json = json
            .replaceFirst("<start_time>",
                    Long.toString(DateUtil.subtractFromUTCMilliSeconds(Calendar.MINUTE, 5)))
            .replaceFirst("<end_time>", Long.toString(DateUtil.addToUTCMilliSeconds(Calendar.HOUR, 1)));

    setLogString("URL Values of the API \n" + directURL + "\n" + json, true);

    final HttpResponse response = HTTPSClient.postResponse(directURL, json,
            HTTPSClient.getPKCSKeyHttpClient("ecofactorqanve.p12", "ecofactor"));
    Assert.assertTrue(response.getStatusLine().getStatusCode() == 200,
            "Error Status:" + response.getStatusLine());
    final String resultValueString = HTTPSClient.getResultString(response.getEntity());
    setLogString("response :'" + resultValueString + "'", true);
}

From source file:com.linuxbox.enkive.statistics.removal.RemovalJob.java

/**
 * generates a date cooresponding to the amount of time each type of
 * statistic should be kept. For instance, if monthKeepTime is set to 3 then
 * 3 months will be subtracted from the current date and that date will be
 * returned//from   w w w .ja  v  a2s  .com
 * 
 * @param time
 *            - the identifier corresponding to the amount of time to deduct
 */
private void setDate(int time) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.MILLISECOND, 0);
    cal.set(Calendar.SECOND, 0);

    switch (time) {
    case REMOVAL_MONTH_ID:// month
        cal.add(Calendar.MONTH, -monthKeepTime);
        break;
    case REMOVAL_WEEK_ID:// week
        cal.add(Calendar.WEEK_OF_YEAR, -weekKeepTime);
        break;
    case REMOVAL_DAY_ID:// day
        cal.add(Calendar.DATE, -dayKeepTime);
        break;
    case REMOVAL_HOUR_ID:// hour
        cal.add(Calendar.HOUR, -hourKeepTime);
        break;
    case REMOVAL_RAW_ID:// raw
        cal.add(Calendar.HOUR, -rawKeepTime);
    }
    dateFilter = cal.getTime();
}

From source file:com.simphony.managedbeans.ItineraryBean.java

/**
 * Guardamos el itinerario//from  w  w  w.  j a  va  2 s  .c o  m
 *
 * @param user
 * @return
 */
public void save(User user) {
    Boolean exist = true;
    if (this.itinerary.getOrigin() != null && this.itinerary.getDestiny() != null) {

        try {
            Itinerary itineratyTemp = this.itineraryService.getItineraryRepository().findByOriginAndDestiny(
                    this.itinerary.getDepartureTime(), this.itinerary.getOrigin().getId(),
                    this.itinerary.getDestiny().getId());
            if (itineratyTemp == null) {
                exist = false;
            }
        } catch (Exception ex) {
            System.out.println("Error");
            exist = false;

        }
        if (!exist) {
            itinerary.setUser(user);
            itinerary.setCreateDate(cal.getTime());
            itinerary.setStatus(_ENABLED);

            Cost c = this.costService.getCostRepository().findByOriDes(this.itinerary.getOrigin().getId(),
                    this.itinerary.getDestiny().getId());

            if (c != null) {
                Calendar calItinerary = Calendar.getInstance();
                calItinerary.setTime(itinerary.getDepartureTime());

                Calendar calCost = Calendar.getInstance();
                calCost.setTime(c.getRouteTime());
                calItinerary.add(Calendar.HOUR, calCost.get(Calendar.HOUR));
                this.itinerary.setCheckTime(calItinerary.getTime());
                if (itinerary.getRoute() == null) {
                    this.itinerary.setTypeOfRoute("L");
                } else
                    this.itinerary.setTypeOfRoute("P");

                this.itineraryService.getItineraryRepository().save(itinerary);
                if (this.itinerary.getTypeOfRoute().equals("L")) {
                    itinerary.setRoute(itinerary);
                    this.itineraryService.getItineraryRepository().save(itinerary);
                }
                GrowlBean.simplyInfoMessage(mp.getValue("msj_save"),
                        mp.getValue("msj_record_save") + this.itinerary.getOrigin().getDescription());
                itinerary = new Itinerary();
                itinerary.setAction(_ADD);
                boxItineraryService.fillBox();
            } else {
                GrowlBean.simplyErrorMessage(mp.getValue("error_cost_title"), mp.getValue("error_cost"));
            } //Existe tarifa?
        } else {
            GrowlBean.simplyErrorMessage(mp.getValue("error_keyId"), mp.getValue("error_keyId_Detail"));
        }
    } else {
        GrowlBean.simplyFatalMessage(mp.getValue("msj_save"),
                mp.getValue("msj_record_save") + this.itinerary.getOrigin().getDescription());
    }
}

From source file:com.acmeair.web.LoaderREST.java

private static Date getArrivalTime(Date departureTime, int mileage) {
    double averageSpeed = 600.0; // 600 miles/hours
    double hours = (double) mileage / averageSpeed; // miles / miles/hour =
                                                    // hours
    double partsOfHour = hours % 1.0;
    int minutes = (int) (60.0 * partsOfHour);
    Calendar c = Calendar.getInstance();
    c.setTime(departureTime);/*from   ww  w.jav a2  s .  co  m*/
    c.add(Calendar.HOUR, (int) hours);
    c.add(Calendar.MINUTE, minutes);
    return c.getTime();
}

From source file:mg.jerytodik.business.service.impl.JeryTodikSourceServiceImpl.java

private String createSubFolderName() {
    final Date now = new Date();
    final Calendar calendar = Calendar.getInstance();
    calendar.setTime(now);//from   w  w w. j av a 2s .co  m

    return new StringBuilder().append(calendar.get(Calendar.YEAR)).append(JerytodikUtil.DASHE_SEPARATOR)
            .append(calendar.get(Calendar.MONTH)).append(JerytodikUtil.DASHE_SEPARATOR)
            .append(calendar.get(Calendar.DAY_OF_MONTH)).append(JerytodikUtil.DASHE_SEPARATOR)
            .append(calendar.get(Calendar.HOUR)).append(JerytodikUtil.DASHE_SEPARATOR)
            .append(calendar.get(Calendar.MINUTE)).toString();
}

From source file:com.microsoftopentechnologies.azchat.web.common.utils.AzureChatStorageUtils.java

/**
 * This method will assign private access to the blob container.
 * /*w ww .ja  va2 s .  c  o  m*/
 * @param container
 * @return
 * @throws Exception
 */
public static String generateSASURL(CloudBlobContainer container) throws Exception {
    LOGGER.info("[AzureChatStorageUtils][assignPrivateAccess] start");
    String signature = AzureChatConstants.CONSTANT_EMPTY_STRING;
    SharedAccessBlobPolicy sharedAccessBlobPolicy = new SharedAccessBlobPolicy();
    GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone(AzureChatConstants.TIMEZONE_UTC));
    calendar.setTime(new Date());
    sharedAccessBlobPolicy.setSharedAccessStartTime(calendar.getTime());
    calendar.add(Calendar.HOUR, 23);
    sharedAccessBlobPolicy.setSharedAccessExpiryTime(calendar.getTime());
    sharedAccessBlobPolicy.setPermissions(EnumSet.of(SharedAccessBlobPermissions.READ));
    BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
    container.uploadPermissions(containerPermissions);
    LOGGER.debug("Private Access Permissions uploaded Successfully.");
    signature = container.generateSharedAccessSignature(sharedAccessBlobPolicy, null);
    LOGGER.info("[AzureChatStorageUtils][assignPrivateAccess] end");
    return signature;
}

From source file:cl.gisred.android.RepartoActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LicenseResult licenseResult = ArcGISRuntime.setClientId(CLIENT_ID);
    LicenseLevel licenseLevel = ArcGISRuntime.License.getLicenseLevel();

    if (licenseResult == LicenseResult.VALID && licenseLevel == LicenseLevel.BASIC) {
        //Toast.makeText(getApplicationContext(), "Licencia bsica vlida", Toast.LENGTH_SHORT).show();
    } else if (licenseResult == LicenseResult.VALID && licenseLevel == LicenseLevel.STANDARD) {
        //Toast.makeText(getApplicationContext(), "Licencia standard vlida", Toast.LENGTH_SHORT).show();
    }/* www  .ja va 2s  .c  om*/

    setContentView(R.layout.activity_reparto);

    Toolbar toolbar = (Toolbar) findViewById(R.id.apptool);
    setSupportActionBar(toolbar);

    myMapView = (MapView) findViewById(R.id.map);
    myMapView.enableWrapAround(true);

    /*Get Credenciales String*/
    Bundle bundle = getIntent().getExtras();
    usuar = bundle.getString("usuario");
    passw = bundle.getString("password");
    modulo = bundle.getString("modulo");
    empresa = bundle.getString("empresa");

    //Crea un intervalo entre primer dia del mes y dia actual
    Calendar oCalendarStart = Calendar.getInstance();
    oCalendarStart.set(Calendar.DAY_OF_MONTH, 1);
    oCalendarStart.set(Calendar.HOUR, 6);

    Calendar oCalendarEnd = Calendar.getInstance();
    oCalendarEnd.set(Calendar.HOUR, 23);

    TimeExtent oTimeInterval = new TimeExtent(oCalendarStart, oCalendarEnd);

    //Set Credenciales
    setCredenciales(usuar, passw);

    if (Build.VERSION.SDK_INT >= 23)
        verifPermisos();
    else
        startGPS();

    setLayersURL(this.getResources().getString(R.string.url_Mapabase), "MAPABASE");
    setLayersURL(this.getResources().getString(R.string.url_token), "TOKENSRV");
    setLayersURL(this.getResources().getString(R.string.srv_Repartos), "SRV_REPARTO");

    LyMapabase = new ArcGISDynamicMapServiceLayer(din_urlMapaBase, null, credenciales);
    LyMapabase.setVisible(true);

    LyReparto = new ArcGISFeatureLayer(srv_reparto, ArcGISFeatureLayer.MODE.ONDEMAND, credenciales);
    LyReparto.setDefinitionExpression(String.format("empresa = '%s'", empresa));
    LyReparto.setTimeInterval(oTimeInterval);
    LyReparto.setMinScale(8000);
    LyReparto.setVisible(true);

    myMapView.addLayer(mRoadBaseMaps, 0);
    myMapView.addLayer(LyReparto, 1);

    sqlReparto = new RepartoSQLiteHelper(RepartoActivity.this, dbName, null, 2);

    txtContador = (TextView) findViewById(R.id.tvContador);
    txtContSesion = (TextView) findViewById(R.id.tvContadorSesion);

    txtListen = (EditText) findViewById(R.id.txtListen);
    txtListen.setEnabled(bGpsActive);
    if (!txtListen.hasFocus())
        txtListen.requestFocus();
    txtListen.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) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().contains("\n") || s.toString().length() == RepartoClass.length_code) {
                guardarRegistro(s.toString().trim());
                s.clear();
            }
        }
    });

    final FloatingActionButton btnGps = (FloatingActionButton) findViewById(R.id.action_gps);
    btnGps.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                myMapView.setExtent(ldm.getPoint());
                myMapView.setScale(4000, true);
            }
        }
    });

    myMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
        @Override
        public void onStatusChanged(Object o, STATUS status) {
            if (ldm != null) {
                Point oPoint = ldm.getPoint();
                myMapView.centerAndZoom(oPoint.getX(), oPoint.getY(), 0.003f);
                myMapView.zoomin(true);
            }

            if (status == STATUS.LAYER_LOADING_FAILED) {
                // Check if a layer is failed to be loaded due to security
                if ((status.getError()) instanceof EsriSecurityException) {
                    EsriSecurityException securityEx = (EsriSecurityException) status.getError();
                    if (securityEx.getCode() == EsriSecurityException.AUTHENTICATION_FAILED)
                        Toast.makeText(myMapView.getContext(),
                                "Su cuenta tiene permisos limitados, contacte con el administrador para solicitar permisos faltantes",
                                Toast.LENGTH_SHORT).show();
                    else if (securityEx.getCode() == EsriSecurityException.TOKEN_INVALID)
                        Toast.makeText(myMapView.getContext(), "Token invlido! Vuelva a iniciar sesin!",
                                Toast.LENGTH_SHORT).show();
                    else if (securityEx.getCode() == EsriSecurityException.TOKEN_SERVICE_NOT_FOUND)
                        Toast.makeText(myMapView.getContext(),
                                "Servicio token no encontrado! Reintente iniciar sesin!", Toast.LENGTH_SHORT)
                                .show();
                    else if (securityEx.getCode() == EsriSecurityException.UNTRUSTED_SERVER_CERTIFICATE)
                        Toast.makeText(myMapView.getContext(), "Untrusted Host! Resubmit!", Toast.LENGTH_SHORT)
                                .show();

                    if (o instanceof ArcGISFeatureLayer) {
                        // Set user credential through username and password
                        UserCredentials creds = new UserCredentials();
                        creds.setUserAccount(usuar, passw);

                        LyMapabase.reinitializeLayer(creds);
                    }
                }
            }
        }
    });

    readCountData();
    updDashboard();

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (iContRep > 0) {
                        Toast.makeText(getApplicationContext(), "Sincronizando datos...", Toast.LENGTH_SHORT)
                                .show();
                        readData();
                        enviarDatos();
                    }
                }
            });

        }
    }, 0, 120000);
}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniServiceAccess.java

public String getTransitionTime(Date dTime) {
    Calendar c = Calendar.getInstance();
    c.setTime(dTime);//from  w w w . j a  va2  s  .  c  om
    StringBuilder sTime = new StringBuilder();
    sTime.append(c.get(Calendar.HOUR));
    sTime.append(":");
    sTime.append(c.get(Calendar.MINUTE));
    return sTime.toString();
}