Example usage for java.util Date toLocaleString

List of usage examples for java.util Date toLocaleString

Introduction

In this page you can find the example usage for java.util Date toLocaleString.

Prototype

@Deprecated
public String toLocaleString() 

Source Link

Document

Creates a string representation of this Date object in an implementation-dependent form.

Usage

From source file:TimeFormatter.java

/**
 * Format the given date as a string, according to the given
 * format string.//from  w ww  .  j a  v  a 2 s. c o m
 * The format string is of the form used by the strftime(3) UNIX
 * call.
 * @param date The date to format
 * @param format The formatting string
 * @return the String with the formatted date.  */
public static String format(Date date, String format) {
    StringBuffer buf = new StringBuffer(50);
    char ch;
    for (int i = 0; i < format.length(); i++) {
        ch = format.charAt(i);
        if (ch == '%') {
            ++i;
            if (i == format.length())
                break;
            ch = format.charAt(i);
            if (ch == 'E') {
                // Alternate Era
                ++i;
            } else if (ch == 'Q') {
                // Alternate numeric symbols
                ++i;
            }
            if (i == format.length())
                break;
            ch = format.charAt(i);
            switch (ch) {
            case 'A':
                buf.append(fullWeekDays[date.getDay()]);
                break;
            case 'a':
                buf.append(abrWeekDays[date.getDay()]);
                break;

            case 'B':
                buf.append(fullMonths[date.getMonth()]);
                break;

            case 'b':
            case 'h':
                buf.append(abrMonths[date.getMonth()]);
                break;

            case 'C':
                appendPadded(buf, (date.getYear() + 1900) / 100, 2);
                break;

            case 'c':
                buf.append(date.toLocaleString());
                break;

            case 'D':
                buf.append(TimeFormatter.format(date, "%m/%d/%y"));
                break;

            case 'd':
                appendPadded(buf, date.getDate(), 2);
                break;

            case 'e':
                appendPadded(buf, date.getMonth() + 1, 2, ' ');
                break;

            case 'H':
                appendPadded(buf, date.getHours(), 2);
                break;

            case 'I':
            case 'l':
                int a = date.getHours() % 12;
                if (a == 0)
                    a = 12;
                appendPadded(buf, a, 2, ch == 'I' ? '0' : ' ');
                break;

            case 'j':
                buf.append("[?]");
                // No simple way to get this as of now
                break;

            case 'k':
                appendPadded(buf, date.getHours(), 2, ' ');
                break;

            case 'M':
                appendPadded(buf, date.getMinutes(), 2);
                break;

            case 'm':
                appendPadded(buf, date.getMonth() + 1, 2);
                break;

            case 'n':
                buf.append('\n');
                break;

            case 'p':
                buf.append(date.getHours() < 12 ? "am" : "pm");
                break;

            case 'R':
                buf.append(TimeFormatter.format(date, "%H:%M"));
                break;

            case 'r':
                buf.append(TimeFormatter.format(date, "%l:%M%p"));
                break;

            case 'S':
                appendPadded(buf, date.getSeconds(), 2);
                break;

            case 'T':
                buf.append(TimeFormatter.format(date, "%H:%M:%S"));
                break;

            case 't':
                buf.append('\t');
                break;

            case 'U':
            case 'u':
            case 'V':
            case 'W':
                buf.append("[?]");
                // Weekdays are a pain, especially
                // without day of year (0-365) ;
                break;

            case 'w':
                buf.append(date.getDay());
                break;

            case 'X':
                buf.append(TimeFormatter.format(date, "%H:%M:%S"));
                break;

            case 'x':
                buf.append(TimeFormatter.format(date, "%B %e, %Y"));
                break;

            case 'y':
                appendPadded(buf, (date.getYear() + 1900) % 100, 2);
                break;

            case 'Y':
                appendPadded(buf, (date.getYear() + 1900), 4);
                break;

            case 'Z':
                String strdate = date.toString();
                buf.append(strdate.substring(20, 23));
                // (!)
                // There should be a better way
                // to do this...
                break;
            case '%':
                buf.append('%');
                break;

            }
        } else {
            buf.append(ch);
        }
    }
    return buf.toString();
}

From source file:com.intellectualcrafters.plot.commands.DebugExec.java

@Override
public boolean execute(final PlotPlayer player, final String... args) {
    final List<String> allowed_params = Arrays.asList("analyze", "reset-modified", "stop-expire",
            "start-expire", "show-expired", "update-expired", "seen", "trim-check");
    if (args.length > 0) {
        final String arg = args[0].toLowerCase();
        switch (arg) {
        case "analyze": {
            final Plot plot = MainUtil.getPlot(player.getLocation());
            HybridUtils.manager.analyzePlot(plot, new RunnableVal<PlotAnalysis>() {
                @Override//w  w  w.j  a v  a  2s. c  om
                public void run() {
                    List<Double> result = new ArrayList<>();
                    result.add(Math.round(value.air * 100) / 100d);
                    result.add(Math.round(value.changes * 100) / 100d);
                    result.add(Math.round(value.complexity * 100) / 100d);
                    result.add(Math.round(value.data * 100) / 100d);
                    result.add(Math.round(value.faces * 100) / 100d);
                    result.add(Math.round(value.air * 100) / 100d);
                    result.add(Math.round(value.variety * 100) / 100d);
                    Flag flag = new Flag(FlagManager.getFlag("analysis"), result);
                    FlagManager.addPlotFlag(plot, flag);
                }
            });
            return true;
        }
        case "stop-expire": {
            if (ExpireManager.task != -1) {
                Bukkit.getScheduler().cancelTask(ExpireManager.task);
            } else {
                return MainUtil.sendMessage(player, "Task already halted");
            }
            ExpireManager.task = -1;
            return MainUtil.sendMessage(player, "Cancelled task.");
        }
        case "remove-flag": {
            if (args.length != 2) {
                MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec reset-flat <flag>");
                return false;
            }
            String flag = args[1];
            for (Plot plot : PS.get().getPlots()) {
                if (FlagManager.getPlotFlag(plot, flag) != null) {
                    FlagManager.removePlotFlag(plot, flag);
                }
            }
            return MainUtil.sendMessage(player, "Cleared flag: " + flag);
        }
        case "start-rgar": {
            if (args.length != 2) {
                PS.log("&cInvalid syntax: /plot debugexec start-rgar <world>");
                return false;
            }
            boolean result;
            if (!PS.get().isPlotWorld(args[1])) {
                MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]);
                return false;
            }
            if (BukkitHybridUtils.regions != null) {
                result = ((BukkitHybridUtils) (HybridUtils.manager)).scheduleRoadUpdate(args[1],
                        BukkitHybridUtils.regions, 0);
            } else {
                result = HybridUtils.manager.scheduleRoadUpdate(args[1], 0);
            }
            if (!result) {
                PS.log("&cCannot schedule mass schematic update! (Is one already in progress?)");
                return false;
            }
            return true;
        }
        case "stop-rgar": {
            if (((BukkitHybridUtils) (HybridUtils.manager)).task == 0) {
                PS.log("&cTASK NOT RUNNING!");
                return false;
            }
            ((BukkitHybridUtils) (HybridUtils.manager)).task = 0;
            Bukkit.getScheduler().cancelTask(((BukkitHybridUtils) (HybridUtils.manager)).task);
            PS.log("&cCancelling task...");
            while (BukkitHybridUtils.chunks.size() > 0) {
                ChunkLoc chunk = BukkitHybridUtils.chunks.get(0);
                BukkitHybridUtils.chunks.remove(0);
                HybridUtils.manager.regenerateRoad(BukkitHybridUtils.world, chunk, 0);
                ChunkManager.manager.unloadChunk(BukkitHybridUtils.world, chunk);
            }
            PS.log("&cCancelled!");
            return true;
        }
        case "start-expire": {
            if (ExpireManager.task == -1) {
                ExpireManager.runTask();
            } else {
                return MainUtil.sendMessage(player, "Plot expiry task already started");
            }
            return MainUtil.sendMessage(player, "Started plot expiry task");
        }
        case "update-expired": {
            if (args.length > 1) {
                final String world = args[1];
                if (!BlockManager.manager.isWorld(world)) {
                    return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
                }
                MainUtil.sendMessage(player, "Updating expired plot list");
                ExpireManager.updateExpired(args[1]);
                return true;
            }
            return MainUtil.sendMessage(player, "Use /plot debugexec update-expired <world>");
        }
        case "show-expired": {
            if (args.length > 1) {
                final String world = args[1];
                if (!BlockManager.manager.isWorld(world)) {
                    return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
                }
                if (!ExpireManager.expiredPlots.containsKey(args[1])) {
                    return MainUtil.sendMessage(player, "No task for world: " + args[1]);
                }
                MainUtil.sendMessage(player,
                        "Expired plots (" + ExpireManager.expiredPlots.get(args[1]).size() + "):");
                for (final Plot plot : ExpireManager.expiredPlots.get(args[1])) {
                    MainUtil.sendMessage(player, " - " + plot.world + ";" + plot.id.x + ";" + plot.id.y + ";"
                            + UUIDHandler.getName(plot.owner) + " : " + ExpireManager.dates.get(plot.owner));
                }
                return true;
            }
            return MainUtil.sendMessage(player, "Use /plot debugexec show-expired <world>");
        }
        case "seen": {
            if (args.length != 2) {
                return MainUtil.sendMessage(player, "Use /plot debugexec seen <player>");
            }
            final UUID uuid = UUIDHandler.getUUID(args[1]);
            if (uuid == null) {
                return MainUtil.sendMessage(player, "player not found: " + args[1]);
            }
            final OfflinePlotPlayer op = UUIDHandler.uuidWrapper.getOfflinePlayer(uuid);
            if ((op == null) || (op.getLastPlayed() == 0)) {
                return MainUtil.sendMessage(player, "player hasn't connected before: " + args[1]);
            }
            final Timestamp stamp = new Timestamp(op.getLastPlayed());
            final Date date = new Date(stamp.getTime());
            MainUtil.sendMessage(player, "PLAYER: " + args[1]);
            MainUtil.sendMessage(player, "UUID: " + uuid);
            MainUtil.sendMessage(player, "Object: " + date.toGMTString());
            MainUtil.sendMessage(player, "GMT: " + date.toGMTString());
            MainUtil.sendMessage(player, "Local: " + date.toLocaleString());
            return true;
        }
        case "trim-check": {
            if (args.length != 2) {
                MainUtil.sendMessage(player, "Use /plot debugexec trim-check <world>");
                MainUtil.sendMessage(player, "&7 - Generates a list of regions to trim");
                return MainUtil.sendMessage(player, "&7 - Run after plot expiry has run");
            }
            final String world = args[1];
            if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(args[1])) {
                return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
            }
            final ArrayList<ChunkLoc> empty = new ArrayList<>();
            final boolean result = Trim.getTrimRegions(empty, world, new Runnable() {
                @Override
                public void run() {
                    Trim.sendMessage("Processing is complete! Here's how many chunks would be deleted:");
                    Trim.sendMessage(" - MCA #: " + empty.size());
                    Trim.sendMessage(" - CHUNKS: " + (empty.size() * 1024) + " (max)");
                    Trim.sendMessage("Exporting log for manual approval...");
                    final File file = new File(PS.get().IMP.getDirectory() + File.separator + "trim.txt");
                    PrintWriter writer;
                    try {
                        writer = new PrintWriter(file);
                        for (final ChunkLoc loc : empty) {
                            writer.println(world + "/region/r." + loc.x + "." + loc.z + ".mca");
                        }
                        writer.close();
                        Trim.sendMessage("File saved to 'plugins/PlotSquared/trim.txt'");
                    } catch (final FileNotFoundException e) {
                        e.printStackTrace();
                        Trim.sendMessage("File failed to save! :(");
                    }
                    Trim.sendMessage("How to get the chunk coords from a region file:");
                    Trim.sendMessage(
                            " - Locate the x,z values for the region file (the two numbers which are separated by a dot)");
                    Trim.sendMessage(" - Multiply each number by 32; this gives you the starting position");
                    Trim.sendMessage(" - Add 31 to each number to get the end position");
                }
            });
            if (!result) {
                MainUtil.sendMessage(player, "Trim task already started!");
            }
            return result;
        }
        }
    }
    MainUtil.sendMessage(player,
            "Possible sub commands: /plot debugexec <" + StringUtils.join(allowed_params, "|") + ">");
    return true;
}

From source file:co.sip.dmesmobile.bs.ScProductionOrderDao.java

@Override
@Transactional/*from ww  w.ja v a  2  s  .  co  m*/
public void insertLogInformation(Long idProcess, Long idOrder, Long idMachine, Date creationDate)
        throws Exception {
    entityManager = Factory.getEntityManagerFactory().createEntityManager();
    try {
        OtLogProduction logProduction = new OtLogProduction();
        logProduction.setCreationDate(creationDate);
        logProduction.setIdMachine(idMachine);
        logProduction.setIdOrder(idOrder);
        logProduction.setIdProcessProduct(idProcess);
        entityManager.getTransaction().begin();
        entityManager.persist(logProduction);
        entityManager.getTransaction().commit();
        entityManager.close();
    } catch (Exception e) {
        log.error("No fue posible insertar la Ordern: " + idOrder + ", Proceso: " + idProcess + " Fecha: "
                + creationDate.toLocaleString() + ", Mquina: " + idMachine, e);
        entityManager.getTransaction().rollback();
        entityManager.close();
        throw e;
    }
}

From source file:net.reichholf.dreamdroid.activities.TimerEditActivity.java

/**
 * Set the GUI-Content from <code>mTimer</code>
 */// w w w  .j a  v a 2  s . co  m
private void reload() {
    // Name
    mName.setText(mTimer.getString(Timer.NAME));
    mName.setHint(R.string.title);

    // Description
    mDescription.setText(mTimer.getString(Timer.DESCRIPTION));
    mDescription.setHint(R.string.description);

    // Enabled
    int disabled = new Integer(mTimer.getString(Timer.DISABLED));
    if (disabled == 0) {
        mEnabled.setChecked(true);
    } else {
        mEnabled.setChecked(false);
    }

    mService.setText(mTimer.getString(Timer.SERVICE_NAME));

    // Afterevents
    ArrayAdapter<CharSequence> aaAfterevent = ArrayAdapter.createFromResource(this, R.array.afterevents,
            android.R.layout.simple_spinner_item);
    aaAfterevent.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mAfterevent.setAdapter(aaAfterevent);

    int aeValue = new Integer(mTimer.getString(Timer.AFTER_EVENT)).intValue();
    mAfterevent.setSelection(aeValue);

    // Locations
    ArrayAdapter<String> aaLocations = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            DreamDroid.LOCATIONS);
    aaLocations.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mLocation.setAdapter(aaLocations);

    String timerLoc = mTimer.getString(Timer.LOCATION);
    for (int i = 0; i < DreamDroid.LOCATIONS.size(); i++) {
        String loc = DreamDroid.LOCATIONS.get(i);

        if (timerLoc != null) {
            if (timerLoc.equals(loc)) {
                mLocation.setSelection(i);
            }
        }
    }

    // Start and Endtime
    int begin = new Integer(mTimer.getString(Timer.BEGIN));
    int end = new Integer(mTimer.getString(Timer.END));
    long b = ((long) begin) * 1000;
    long e = ((long) end) * 1000;
    Date dateBegin = new Date(b);
    Date dateEnd = new Date(e);

    mStart.setText(dateBegin.toLocaleString());
    mEnd.setText(dateEnd.toLocaleString());

    // Repeatings
    int repeatedValue = new Integer(mTimer.getString(Timer.REPEATED));
    String repeatedText = getRepeated(repeatedValue);
    mRepeatings.setText(repeatedText);

    String text = mTimer.getString(Timer.TAGS);
    if (text == null) {
        text = "";
    }
    mTags.setText(text);
    String[] tags = text.split(" ");
    for (String tag : tags) {
        mSelectedTags.add(tag);
    }
}

From source file:ca.spencerelliott.mercury.Changesets.java

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    this.requestWindowFeature(Window.FEATURE_PROGRESS);
    this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.changesets);

    //Cancel any notifications previously setup
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancel(1);//w w  w  .j ava 2 s.  c o  m

    //Create a new array list for the changesets
    changesets_list = new ArrayList<Map<String, ?>>();
    changesets_data = new ArrayList<Beans.ChangesetBean>();

    //Get the list view to store the changesets
    changesets_listview = (ListView) findViewById(R.id.changesets_list);

    TextView empty_text = (TextView) findViewById(R.id.changesets_empty_text);

    //Set the empty view
    changesets_listview.setEmptyView(empty_text);

    //Use a simple adapter to display the changesets based on the array list made earlier
    changesets_listview.setAdapter(new SimpleAdapter(this, changesets_list, R.layout.changeset_item,
            new String[] { COMMIT, FORMATTED_INFO },
            new int[] { R.id.changesets_commit, R.id.changesets_info }));

    //Set the on click listener
    changesets_listview.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
            Intent intent = new Intent(Changesets.this, ChangesetViewer.class);

            //Pass the changeset information to the changeset viewer
            Bundle params = new Bundle();
            params.putString("changeset_commit_text", changesets_data.get(position).getTitle());
            params.putString("changeset_changes", changesets_data.get(position).getContent());
            params.putLong("changeset_updated", changesets_data.get(position).getUpdated());
            params.putString("changeset_authors", changesets_data.get(position).getAuthor());
            params.putString("changeset_link", changesets_data.get(position).getLink());
            //params.putBoolean("is_https", is_https);

            intent.putExtras(params);

            startActivity(intent);
        }

    });

    //Register the list view for opening the context menu
    registerForContextMenu(changesets_listview);

    //Get the intent passed by the program
    if (getIntent() != null) {
        //Check to see if this is a search window
        if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
            //Change the title of the activity and the empty text of the list so it looks like a search window
            this.setTitle(R.string.search_results_label);
            empty_text.setText(R.string.search_results_empty);

            //Retrieve the query the user entered
            String query = getIntent().getStringExtra(SearchManager.QUERY);

            //Convert the query to lower case
            query = query.toLowerCase();

            //Retrieve the bundle data
            Bundle retrieved_data = getIntent().getBundleExtra(SearchManager.APP_DATA);

            //If the bundle was passed, grab the changeset data
            if (retrieved_data != null) {
                changesets_data = retrieved_data
                        .getParcelableArrayList("ca.spencerelliott.mercury.SEARCH_DATA");
            }

            //If we're missing changeset data, stop here
            if (changesets_data == null)
                return;

            //Create a new array list to store the changesets that were a match
            ArrayList<Beans.ChangesetBean> search_beans = new ArrayList<Beans.ChangesetBean>();

            //Loop through each changeset
            for (Beans.ChangesetBean b : changesets_data) {
                //Check to see if any changesets match
                if (b.getTitle().toLowerCase().contains(query)) {
                    //Get the title and date of the commit
                    String commit_text = b.getTitle();
                    Date commit_date = new Date(b.getUpdated());

                    //Add a new changeset to display in the list view
                    changesets_list.add(createChangeset(
                            (commit_text.length() > 30 ? commit_text.substring(0, 30) + "..." : commit_text),
                            b.getRevisionID() + " - " + commit_date.toLocaleString()));

                    //Add this bean to the list of found search beans
                    search_beans.add(b);
                }
            }

            //Switch the changeset data over to the changeset data that was a match
            changesets_data = search_beans;

            //Update the list in the activity
            list_handler.sendEmptyMessage(SUCCESSFUL);

            //Notify the activity that it is a search window
            is_search_window = true;

            //Stop loading here
            return;
        }

        //Get the data from the intent
        Uri data = getIntent().getData();

        if (data != null) {
            //Extract the path in the intent
            String path_string = data.getEncodedPath();

            //Split it by the forward slashes
            String[] split_path = path_string.split("/");

            //Make sure a valid path was passed
            if (split_path.length == 3) {
                //Get the repository id from the intent
                repo_id = Long.parseLong(split_path[2].toString());
            } else {
                //Notify the user if there was a problem
                Toast.makeText(this, R.string.invalid_intent, 1000).show();
            }
        }
    }

    //Retrieve the changesets
    refreshChangesets();
}

From source file:ca.spencerelliott.mercury.Changesets.java

private synchronized void startThread() {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    //Create the thread that will process the incoming feed
    load_thread = new Thread() {
        @Override/*w  ww.  ja v a 2  s . co m*/
        public void run() {
            changesets_list.clear();

            DatabaseHelper db_helper = DatabaseHelper.getInstance(getApplicationContext());
            EncryptionHelper encrypt_helper = EncryptionHelper.getInstance("DEADBEEF".toCharArray(),
                    new byte[] { 'L', 'O', 'L' });

            //Get the repository information from the local database
            Beans.RepositoryBean repo_type = db_helper.getRepository(repo_id, encrypt_helper);
            AtomHandler feed_handler = null;

            //Detect the type of repository and create a parser based on that
            switch (repo_type.getType()) {
            case Mercury.RepositoryTypes.HGSERVE:
                feed_handler = new HGWebAtomHandler();
                break;
            case Mercury.RepositoryTypes.GOOGLECODE:
                feed_handler = new GoogleCodeAtomHandler();
                break;
            case Mercury.RepositoryTypes.BITBUCKET:
                feed_handler = new BitbucketAtomHandler();
                break;
            case Mercury.RepositoryTypes.CODEPLEX:
                feed_handler = new CodePlexAtomHandler();
                break;
            }

            HttpURLConnection conn = null;
            boolean connected = false;

            try {
                // XXX We need to use our own factory to make all ssl certs work
                HttpsURLConnection.setDefaultSSLSocketFactory(NaiveSSLSocketFactory.getSocketFactory());

                String repo_url_string = (repo_type.getUrl().endsWith("/") || repo_type.getUrl().endsWith("\\")
                        ? feed_handler
                                .formatURL(repo_type.getUrl().substring(0, repo_type.getUrl().length() - 1))
                        : feed_handler.formatURL(repo_type.getUrl()));

                switch (repo_type.getType()) {
                case Mercury.RepositoryTypes.BITBUCKET:
                    //Only add the token if the user requested it
                    if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.TOKEN)
                        repo_url_string = repo_url_string + "?token=" + repo_type.getSSHKey();
                    break;
                }

                URL repo_url = new URL(repo_url_string);
                conn = (HttpURLConnection) repo_url.openConnection();

                //Check to see if the user enabled HTTP authentication
                if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.HTTP) {
                    //Get their username and password
                    byte[] decrypted_info = (repo_type.getUsername() + ":" + repo_type.getPassword())
                            .getBytes();

                    //Add the header to the http request
                    conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBytes(decrypted_info));
                }
                conn.connect();
                connected = true;
            } catch (ClientProtocolException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("There was a problem with the HTTP protocol");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (IOException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("Server did not respond with a valid HTTP response");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (NullPointerException e3) {

            } catch (Exception e) {

            }

            BufferedReader reader = null;

            //Create a new reader based on the information retrieved
            if (connected) {
                try {
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Make sure both the feed handler and info loaded from the web are not null
            if (reader != null && feed_handler != null) {
                try {
                    Xml.parse(reader, feed_handler);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Stored beans in the devices database
            ArrayList<Beans.ChangesetBean> stored_beans = null;

            if (prefs.getBoolean("caching", false)) {
                long last_insert = db_helper.getHighestID(DatabaseHelper.DB_TABLE_CHANGESETS, repo_id);

                if (last_insert >= 0) {
                    //Get all of the stored changesets
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                    String rev_id = "";

                    //Try to find the revision id of the bean that has the id of the last inserted value
                    for (Beans.ChangesetBean b : stored_beans) {
                        if (b.getID() == last_insert) {
                            rev_id = b.getRevisionID();
                            break;
                        }
                    }

                    //Trim the list starting from this revision
                    feed_handler.trimStartingFromRevision(rev_id);
                }
            }

            //Create a new bundle for the progress
            Bundle progress_bundle = new Bundle();

            //Retreive all the beans from the handler
            ArrayList<Beans.ChangesetBean> beans = feed_handler.getAllChangesets();
            int bean_count = beans.size();

            //Store the amount of changesets
            progress_bundle.putInt("max", bean_count);

            //Create a new message and store the bundle and what type of message it is
            Message msg = new Message();
            msg.setData(progress_bundle);
            msg.what = SETUP_COUNT;
            list_handler.sendMessage(msg);

            //Add each of the beans to the list
            for (int i = 0; i < bean_count; i++) {
                String commit_text = beans.get(i).getTitle();
                Date commit_date = new Date(beans.get(i).getUpdated());
                changesets_list.add(createChangeset(
                        (commit_text.length() > 30 ? commit_text.substring(0, 30) + "..." : commit_text),
                        beans.get(i).getRevisionID() + " - " + commit_date.toLocaleString()));

                //Store the current progress of the changeset loading
                progress_bundle.putInt("progress", i);

                //Reuse the old message and send an update progress message
                msg = new Message();
                msg.setData(progress_bundle);
                msg.what = UPDATE_PROGRESS;
                list_handler.sendMessage(msg);
            }

            //Get the current count of changesets and the shared preferences
            long changeset_count = db_helper.getChangesetCount(repo_id);

            if (prefs.getBoolean("caching", false)) {
                //Get all of the stored beans from the device if not already done
                if (stored_beans == null)
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                //Add all the changesets from the device
                for (Beans.ChangesetBean b : stored_beans) {
                    changesets_list.add(createChangeset(
                            (b.getTitle().length() > 30 ? (b.getTitle().substring(0, 30)) + "..."
                                    : b.getTitle()),
                            b.getRevisionID() + " - " + new Date(b.getUpdated()).toLocaleString()));
                }

                //Reverse the list so the oldest changesets are stored first
                Collections.reverse(beans);

                //Iterate through each bean and add it to the device's database
                for (Beans.ChangesetBean b : beans) {
                    db_helper.insert(b, repo_id);
                }

                //Get the amount of changesets allowed to be stored on the device
                int max_changes = Integer.parseInt(prefs.getString("max_changesets", "-1"));

                //Delete the oldest changesets if too many have been stored
                if (changeset_count > max_changes) {
                    db_helper.deleteNumChangesets(repo_id, (changeset_count - max_changes));
                }
            } else if (changeset_count > 0) {
                //Since the user does not have caching enabled, delete the changesets
                db_helper.deleteAllChangesets(repo_id);
            }

            //Update the tables to the newest revision
            if (!beans.isEmpty())
                db_helper.updateLastRev(repo_id, beans.get(0).getRevisionID());

            //Add all of the data to the changeset list
            changesets_data.addAll(beans);

            if (prefs.getBoolean("caching", false))
                changesets_data.addAll(stored_beans);

            //Clean up the sql connection
            db_helper.cleanup();
            db_helper = null;

            //Notify the handler that the loading of the list was successful
            list_handler.sendEmptyMessage(SUCCESSFUL);
        }
    };

    //Start the thread
    load_thread.start();
}

From source file:com.landenlabs.all_devtool.NetFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();/*  w  w  w  .j  a v a2 s. c o m*/

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Connection Services -------------
    try {
        ConnectivityManager connMgr = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
        if (netInfo != null) {
            Map<String, String> netListStr = new LinkedHashMap<String, String>();

            putIf(netListStr, "Available", "Yes", netInfo.isAvailable());
            putIf(netListStr, "Connected", "Yes", netInfo.isConnected());
            putIf(netListStr, "Connecting", "Yes", !netInfo.isConnected() && netInfo.isConnectedOrConnecting());
            putIf(netListStr, "Roaming", "Yes", netInfo.isRoaming());
            putIf(netListStr, "Extra", netInfo.getExtraInfo(), !TextUtils.isEmpty(netInfo.getExtraInfo()));
            putIf(netListStr, "WhyFailed", netInfo.getReason(), !TextUtils.isEmpty(netInfo.getReason()));
            if (Build.VERSION.SDK_INT >= 16) {
                putIf(netListStr, "Metered", "Avoid heavy use", connMgr.isActiveNetworkMetered());
            }

            netListStr.put("NetworkType", netInfo.getTypeName());
            if (connMgr.getAllNetworkInfo().length > 1) {
                netListStr.put("Available Networks:", " ");
                for (NetworkInfo netI : connMgr.getAllNetworkInfo()) {
                    if (netI.isAvailable()) {
                        netListStr.put(" " + netI.getTypeName(), netI.isAvailable() ? "Yes" : "No");
                    }
                }
            }

            if (netInfo.isConnected()) {
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                            .hasMoreElements();) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                .hasMoreElements();) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress()) {
                                if (inetAddress.getHostAddress() != null) {
                                    String ipType = (inetAddress instanceof Inet4Address) ? "IPv4" : "IPv6";
                                    netListStr.put(intf.getName() + " " + ipType, inetAddress.getHostAddress());
                                }
                                // if (!TextUtils.isEmpty(inetAddress.getHostName()))
                                //     listStr.put( "HostName", inetAddress.getHostName());
                            }
                        }
                    }
                } catch (Exception ex) {
                    m_log.e("Network %s", ex.getMessage());
                }
            }

            addBuild("Network...", netListStr);
        }
    } catch (Exception ex) {
        m_log.e("Network %s", ex.getMessage());
    }

    // --------------- Telephony Services -------------
    TelephonyManager telephonyManager = (TelephonyManager) getActivity()
            .getSystemService(Context.TELEPHONY_SERVICE);
    if (telephonyManager != null) {
        Map<String, String> cellListStr = new LinkedHashMap<String, String>();
        try {
            cellListStr.put("Version", telephonyManager.getDeviceSoftwareVersion());
            cellListStr.put("Number", telephonyManager.getLine1Number());
            cellListStr.put("Service", telephonyManager.getNetworkOperatorName());
            cellListStr.put("Roaming", telephonyManager.isNetworkRoaming() ? "Yes" : "No");
            cellListStr.put("Type", getNetworkTypeName(telephonyManager.getNetworkType()));

            if (Build.VERSION.SDK_INT >= 17) {
                if (telephonyManager.getAllCellInfo() != null) {
                    for (CellInfo cellInfo : telephonyManager.getAllCellInfo()) {
                        String cellName = cellInfo.getClass().getSimpleName();
                        int level = 0;
                        if (cellInfo instanceof CellInfoCdma) {
                            level = ((CellInfoCdma) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoGsm) {
                            level = ((CellInfoGsm) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoLte) {
                            level = ((CellInfoLte) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoWcdma) {
                            if (Build.VERSION.SDK_INT >= 18) {
                                level = ((CellInfoWcdma) cellInfo).getCellSignalStrength().getLevel();
                            }
                        }
                        cellListStr.put(cellName, "Level% " + String.valueOf(100 * level / 4));
                    }
                }
            }

            for (NeighboringCellInfo cellInfo : telephonyManager.getNeighboringCellInfo()) {
                int level = cellInfo.getRssi();
                cellListStr.put("Cell level%", String.valueOf(100 * level / 31));
            }

        } catch (Exception ex) {
            m_log.e("Cell %s", ex.getMessage());
        }

        if (!cellListStr.isEmpty()) {
            addBuild("Cell...", cellListStr);
        }
    }

    // --------------- Bluetooth Services (API18) -------------
    if (Build.VERSION.SDK_INT >= 18) {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (bluetoothAdapter != null) {

                Map<String, String> btListStr = new LinkedHashMap<String, String>();

                btListStr.put("Enabled", bluetoothAdapter.isEnabled() ? "yes" : "no");
                btListStr.put("Name", bluetoothAdapter.getName());
                btListStr.put("ScanMode", String.valueOf(bluetoothAdapter.getScanMode()));
                btListStr.put("State", String.valueOf(bluetoothAdapter.getState()));
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                // If there are paired devices
                if (pairedDevices.size() > 0) {
                    // Loop through paired devices
                    for (BluetoothDevice device : pairedDevices) {
                        // Add the name and address to an array adapter to show in a ListView
                        btListStr.put("Paired:" + device.getName(), device.getAddress());
                    }
                }

                BluetoothManager btMgr = (BluetoothManager) getActivity()
                        .getSystemService(Context.BLUETOOTH_SERVICE);
                if (btMgr != null) {
                    // btMgr.getAdapter().
                }
                addBuild("Bluetooth", btListStr);
            }

        } catch (Exception ex) {

        }
    }

    // --------------- Wifi Services -------------
    final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);

    if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {

        if (mSystemBroadcastReceiver == null) {
            mSystemBroadcastReceiver = new SystemBroadcastReceiver(wifiMgr);
            getActivity().registerReceiver(mSystemBroadcastReceiver, INTENT_FILTER_SCAN_AVAILABLE);
        }

        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (wifiMgr.getScanResults() == null || wifiMgr.getScanResults().size() != mLastScanSize) {
                mLastScanSize = wifiMgr.getScanResults().size();
                wifiMgr.startScan();
            }
        }

        Map<String, String> wifiListStr = new LinkedHashMap<String, String>();
        try {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();

            wifiListStr.put("DNS1", Formatter.formatIpAddress(dhcpInfo.dns1));
            wifiListStr.put("DNS2", Formatter.formatIpAddress(dhcpInfo.dns2));
            wifiListStr.put("Default Gateway", Formatter.formatIpAddress(dhcpInfo.gateway));
            wifiListStr.put("IP Address", Formatter.formatIpAddress(dhcpInfo.ipAddress));
            wifiListStr.put("Subnet Mask", Formatter.formatIpAddress(dhcpInfo.netmask));
            wifiListStr.put("Server IP", Formatter.formatIpAddress(dhcpInfo.serverAddress));
            wifiListStr.put("Lease Time(sec)", String.valueOf(dhcpInfo.leaseDuration));

            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            if (wifiInfo != null) {
                wifiListStr.put("LinkSpeed Mbps", String.valueOf(wifiInfo.getLinkSpeed()));
                int numberOfLevels = 10;
                int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
                wifiListStr.put("Signal%", String.valueOf(100 * level / numberOfLevels));
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiListStr.put("MAC", getMacAddr());
                } else {
                    wifiListStr.put("MAC", wifiInfo.getMacAddress());
                }
            }

        } catch (Exception ex) {
            m_log.e("Wifi %s", ex.getMessage());
        }

        if (!wifiListStr.isEmpty()) {
            addBuild("WiFi...", wifiListStr);
        }

        try {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(getContext(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                List<ScanResult> listWifi = wifiMgr.getScanResults();
                if (listWifi != null && !listWifi.isEmpty()) {
                    int idx = 0;

                    for (ScanResult scanResult : listWifi) {
                        Map<String, String> wifiScanListStr = new LinkedHashMap<String, String>();
                        wifiScanListStr.put("SSID", scanResult.SSID);
                        if (Build.VERSION.SDK_INT >= 23) {
                            wifiScanListStr.put("  Name", scanResult.operatorFriendlyName.toString());
                            wifiScanListStr.put("  Venue", scanResult.venueName.toString());
                        }

                        //        wifiScanListStr.put("  BSSID ",scanResult.BSSID);
                        wifiScanListStr.put("  Capabilities", scanResult.capabilities);
                        //       wifiScanListStr.put("  Center Freq", String.valueOf(scanResult.centerFreq0));
                        //       wifiScanListStr.put("  Freq width", String.valueOf(scanResult.channelWidth));
                        wifiScanListStr.put("  Level, Freq",
                                String.format("%d, %d", scanResult.level, scanResult.frequency));
                        if (Build.VERSION.SDK_INT >= 17) {
                            Date wifiTime = new Date(scanResult.timestamp);
                            wifiScanListStr.put("  Time", wifiTime.toLocaleString());
                        }
                        addBuild(String.format("WiFiScan #%d", ++idx), wifiScanListStr);
                    }
                }
            }
        } catch (Exception ex) {
            m_log.e("WifiList %s", ex.getMessage());
        }

        try {
            List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks();

            for (WifiConfiguration wifiCfg : listWifiCfg) {
                Map<String, String> wifiCfgListStr = new LinkedHashMap<String, String>();
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiCfgListStr.put("Name", wifiCfg.providerFriendlyName);
                }
                wifiCfgListStr.put("SSID", wifiCfg.SSID);
                String netStatus = "";
                switch (wifiCfg.status) {
                case WifiConfiguration.Status.CURRENT:
                    netStatus = "Connected";
                    break;
                case WifiConfiguration.Status.DISABLED:
                    netStatus = "Disabled";
                    break;
                case WifiConfiguration.Status.ENABLED:
                    netStatus = "Enabled";
                    break;
                }
                wifiCfgListStr.put(" Status", netStatus);
                wifiCfgListStr.put(" Priority", String.valueOf(wifiCfg.priority));
                if (null != wifiCfg.wepKeys) {
                    //               wifiCfgListStr.put(" wepKeys", TextUtils.join(",", wifiCfg.wepKeys));
                }
                String protocols = "";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.RSN))
                    protocols = "RSN ";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.WPA))
                    protocols = protocols + "WPA ";
                wifiCfgListStr.put(" Protocols", protocols);

                String keyProt = "";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE))
                    keyProt = "none";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP))
                    keyProt = "WPA+EAP ";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK))
                    keyProt = "WPA+PSK ";
                wifiCfgListStr.put(" Keys", keyProt);

                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {
                    // Remove network connections with no Password.
                    // wifiMgr.removeNetwork(wifiCfg.networkId);
                }

                addBuild("WiFiCfg #" + wifiCfg.networkId, wifiCfgListStr);
            }

        } catch (Exception ex) {
            m_log.e("Wifi Cfg List %s", ex.getMessage());
        }
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}

From source file:view.CertificatePropertiesDialog.java

private void setCertificateProperties(X509Certificate x509Certificate) {
    selectedCertificate = x509Certificate;
    jTextField1.setText(null);/*from  w w  w .  ja  v  a2s .co m*/
    jTextField2.setText(null);
    jTextField3.setText(null);
    jTextField4.setText(null);
    jTextField5.setText(null);
    jTextField6.setText(null);
    jTextField7.setText(null);
    jTextField9.setText(null);
    jTextField10.setText(null);
    jTextField11.setText(null);
    jTextField12.setText(null);

    X500Name x500subject = null;
    X500Name x500issuer = null;
    try {
        x500subject = new JcaX509CertificateHolder(x509Certificate).getSubject();
        x500issuer = new JcaX509CertificateHolder(x509Certificate).getIssuer();
    } catch (CertificateEncodingException ex) {
        controller.Logger.getLogger().addEntry(ex);
    }

    RDN subjectCN = null;
    if (x500subject.getRDNs(BCStyle.CN).length > 0) {
        subjectCN = x500subject.getRDNs(BCStyle.CN)[0];
    }
    RDN subjectOU1 = null;
    if (x500subject.getRDNs(BCStyle.OU).length >= 1) {
        subjectOU1 = x500subject.getRDNs(BCStyle.OU)[0];
        jTextField2.setText(IETFUtils.valueToString(subjectOU1.getFirst().getValue()));
        jTextField2.setCaretPosition(0);
    }
    RDN subjectOU2 = null;
    if (x500subject.getRDNs(BCStyle.OU).length >= 2) {
        subjectOU2 = x500subject.getRDNs(BCStyle.OU)[1];
        jTextField3.setText(IETFUtils.valueToString(subjectOU2.getFirst().getValue()));
        jTextField3.setCaretPosition(0);
    }
    RDN subjectO = null;
    if (x500subject.getRDNs(BCStyle.O).length > 0) {
        subjectO = x500subject.getRDNs(BCStyle.O)[0];
    }
    RDN subjectC = null;
    if (x500subject.getRDNs(BCStyle.C).length > 0) {
        subjectC = x500subject.getRDNs(BCStyle.C)[0];
    }
    if (!x500issuer.equals(x500subject)) {
        RDN issuerCN = x500issuer.getRDNs(BCStyle.CN)[0];
        if (1 == x500issuer.getRDNs(BCStyle.OU).length) {
            RDN issuerOU1 = x500issuer.getRDNs(BCStyle.OU)[0];
            jTextField7.setText(IETFUtils.valueToString(issuerOU1.getFirst().getValue()));
            jTextField7.setCaretPosition(0);
        }
        RDN issuerO = x500issuer.getRDNs(BCStyle.O)[0];
        RDN issuerC = x500issuer.getRDNs(BCStyle.C)[0];

        jTextField6.setText(IETFUtils.valueToString(issuerCN.getFirst().getValue()));
        jTextField6.setCaretPosition(0);
        jTextField9.setText(IETFUtils.valueToString(issuerO.getFirst().getValue()));
        jTextField9.setCaretPosition(0);
        jTextField10.setText(IETFUtils.valueToString(issuerC.getFirst().getValue()));
        jTextField10.setCaretPosition(0);
    }

    Date since = x509Certificate.getNotBefore();
    Date until = x509Certificate.getNotAfter();

    jTextField1.setText(
            WordUtils.capitalize(IETFUtils.valueToString(subjectCN.getFirst().getValue()).toLowerCase()));
    jTextField1.setCaretPosition(0);
    if (subjectO != null) {
        jTextField4.setText(IETFUtils.valueToString(subjectO.getFirst().getValue()));
    }
    jTextField4.setCaretPosition(0);
    if (subjectC != null) {
        jTextField5.setText(IETFUtils.valueToString(subjectC.getFirst().getValue()));
    }
    jTextField5.setCaretPosition(0);

    jTextField11.setText(since.toLocaleString());
    jTextField11.setCaretPosition(0);
    jTextField12.setText(until.toLocaleString());
    jTextField12.setCaretPosition(0);

    boolean usage[] = x509Certificate.getKeyUsage();
    if (null != usage) {
        boolean digitalSignature = usage[0];
        boolean nonRepudiation = usage[1];
        boolean keyEncipherment = usage[2];
        boolean dataEncipherment = usage[3];
        boolean keyAgreement = usage[4];
        boolean keyCertSign = usage[5];
        boolean cRLSign = usage[6];
        boolean encipherOnly = usage[7];
        boolean decipherOnly = usage[8];

        String uso = (digitalSignature ? Bundle.getBundle().getString("digitalSignature") + ", " : "")
                + (nonRepudiation ? Bundle.getBundle().getString("nonRepudiation") + ", " : "")
                + (keyEncipherment ? Bundle.getBundle().getString("keyEncipherment") + ", " : "")
                + (dataEncipherment ? Bundle.getBundle().getString("dataEncipherment") + ", " : "")
                + (keyAgreement ? Bundle.getBundle().getString("keyAgreement") + ", " : "")
                + (keyCertSign ? Bundle.getBundle().getString("keyCertSign") + ", " : "")
                + (cRLSign ? Bundle.getBundle().getString("cRLSign") + ", " : "")
                + (encipherOnly ? Bundle.getBundle().getString("encipherOnly") + ", " : "")
                + (decipherOnly ? Bundle.getBundle().getString("decipherOnly") + ", " : "");

        if (uso.length() == 0) {
            lblUso.setText(Bundle.getBundle().getString("label.none"));
        } else if (uso.endsWith(", ")) {
            lblUso.setText(uso.substring(0, uso.length() - 2));
        }
    } else {
        lblUso.setText(Bundle.getBundle().getString("unknown"));
    }

}

From source file:com.ibm.xsp.webdav.resource.DAVResourceDominoDocuments.java

@SuppressWarnings("deprecation")
private void setup(Document curDoc) {
    try {//from   ww w. j av  a2  s .c  o m
        // LOGGER.info(getCallingMethod()+":"+"Start setup...");
        @SuppressWarnings("rawtypes")
        Vector allEmbedded = DominoProxy.evaluate("@AttachmentNames", curDoc);
        // LOGGER.info(getCallingMethod()+":"+"All Embedded computed");
        int numOfAttachments = allEmbedded.isEmpty() ? 0
                : (allEmbedded.get(0).equals("") ? 0 : allEmbedded.size());
        String docID = curDoc.getUniversalID();
        this.setDocumentUniqueID(docID);
        // LOGGER.info("Num of attachments="+new
        // Integer(numOfAttachments).toString());
        boolean readOnly = this.checkReadOnlyAccess(curDoc);
        this.setReadOnly(readOnly);
        LOGGER.info("Creation date for " + curDoc.getUniversalID() + " =" + curDoc.getCreated().toString()
                + "; Time zone=" + curDoc.getCreated().getZoneTime() + "; Local time="
                + curDoc.getCreated().getLocalTime());

        Date curCreationDate = curDoc.getCreated().toJavaDate();
        LOGGER.info("Current date in Java is " + curCreationDate.toString() + "Time zone="
                + new Integer(curCreationDate.getTimezoneOffset()).toString() + "; Locale time is:"
                + curCreationDate.toLocaleString());
        if (curDoc.hasItem("DAVCreated")) {
            // Item davCreated=curDoc.getFirstItem("DAVCreated");
            @SuppressWarnings("rawtypes")
            Vector times = curDoc.getItemValueDateTimeArray("DAVCreated");
            if (times != null) {
                if (times.size() > 0) {
                    Object time = times.elementAt(0);
                    if (time != null) {
                        if (time.getClass().getName().endsWith("DateTime")) {
                            curCreationDate = ((DateTime) time).toJavaDate();
                            if (curCreationDate == null) {
                                curCreationDate = curDoc.getCreated().toJavaDate();
                            }
                        }
                    }
                }
            }
        }
        Date curChangeDate = curDoc.getLastModified().toJavaDate();
        if (curDoc.hasItem("DAVModified")) {
            @SuppressWarnings("rawtypes")
            Vector times = curDoc.getItemValueDateTimeArray("DAVModified");
            if (times != null) {
                if (times.size() > 0) {
                    Object time = times.elementAt(0);
                    if (time != null) {
                        if (time.getClass().getName().endsWith("DateTime")) {
                            curChangeDate = ((DateTime) time).toJavaDate();
                            if (curChangeDate == null) {
                                curChangeDate = curDoc.getLastModified().toJavaDate();
                            }
                        }
                    }
                }
            }
        }
        this.setCreationDate(curCreationDate);
        this.setLastModified(curChangeDate);
        LOGGER.info("Creation date is set to " + this.getCreationDate().toString());
        LOGGER.info("Last modified date is set to " + this.getLastModified().toString());
        String pubHRef = ((IDAVAddressInformation) this.getRepository()).getPublicHref();
        // LOGGER.info("THIS getpublichref="+this.getPublicHref());
        String curAttName = null;
        if (numOfAttachments == 0) {
            // LOGGER.info(getCallingMethod()+":"+"Start setting resource");
            this.setName(docID);
            String name = curDoc.getItemValueString(
                    ((DAVRepositoryDominoDocuments) (this.getRepository())).getDirectoryField());
            this.setName(name);
            if (this.getPublicHref().equals("")) {
                // try{
                this.setPublicHref(pubHRef + "/" + name);
                // URLEncoder.encode(name, "UTF-8"));
                // }catch(UnsupportedEncodingException e){
                // LOGGER.error(e);
                // }
            }
            this.setCollection(true);
            this.setInternalAddress(
                    ((IDAVAddressInformation) this.getRepository()).getInternalAddress() + "/" + docID);

            this.setResourceType("NotesDocument");
            this.setMember(false);
            this.setContentLength(0L);
            // this.fetchChildren();
        } else {
            curAttName = allEmbedded.get(0).toString();
            // LOGGER.info("Attachment name is "+curAttName);
            this.setMember(true);
            this.setResourceType("NotesAttachment");
            if (this.getPublicHref().equals("")) {
                try {
                    this.setPublicHref(pubHRef + "/" + URLEncoder.encode(curAttName, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    LOGGER.error(e);
                }

                // this.setPublicHref( pubHRef+"/"+curAttName);
            }
            this.setInternalAddress(((IDAVAddressInformation) this.getRepository()).getInternalAddress() + "/"
                    + docID + "/$File/" + curAttName);
            this.setCollection(false);
            this.setName(curAttName);
            EmbeddedObject curAtt = curDoc.getAttachment(curAttName);
            if (curAtt == null) {
                // LOGGER.info("Error! Current Embedded is null");
                return;
            } else {
                // LOGGER.info("Embedded is not null. OK! ");
            }
            Long curSize = new Long(curAtt.getFileSize());
            this.setContentLength(curSize);
        }
        // LOGGER.info("Current res realized! pubHREF="+this.getPublicHref()+"; Internal Address="+this.getInternalAddress()+"; ");
    } catch (NotesException ne) {
        LOGGER.error("ERROR! Can not set; " + ne.getMessage());
    }
}

From source file:org.restcomm.app.qoslib.Services.LibPhoneStateListener.java

public void popupDropped(final EventType droptype, final int rating, final int evtId) {
    if (rating == 0)
        return;/*from w  w w  . java 2  s.c  o  m*/
    owner.handler.post(new Runnable() {
        // @Override
        public void run() {
            String message = "";
            int icon;
            icon = R.drawable.ic_stat_dropped;
            String title = "";
            String msg = "";

            // server can specify whether a confirmation can be invoked on a low rated potentially-dropped call
            int allowConfirm = PreferenceManager.getDefaultSharedPreferences(owner)
                    .getInt(PreferenceKeys.Miscellaneous.ALLOW_CONFIRMATION, 5);
            String noConfirm = (owner.getResources().getString(R.string.NO_CONFIRMATION));
            int allowPopup = PreferenceManager.getDefaultSharedPreferences(owner)
                    .getInt(PreferenceKeys.Miscellaneous.ALLOW_DROP_POPUP, 2);
            if (allowPopup == 1 && !owner.getUseRadioLog())
                allowPopup = 0;
            if (allowPopup == 0)
                return;

            if (noConfirm.equals("1"))
                allowConfirm = 0;
            if (allowConfirm > 0 && rating < allowConfirm && rating < 4) // if confirmation allow, must be above threshold or high rating dropped call
                return;
            else if (allowConfirm == 0 && rating < 4) // drop call silently if marginal with no confirmation
                return;
            // allowConfirm>=5 disables the confirmation because rating always <= 5
            // allowConfirm=1 hits the 'else' and invokes confirmation if rating >= 1 and <5
            // allowConfirm=3 hits the 'else' and invokes confirmation if rating >= 3 and <5
            int expiry = 60000 * 2 * 60;
            int customText = (owner.getResources().getInteger(R.integer.CUSTOM_EVENTNAMES));
            message = owner.getString((customText == 1) ? R.string.sharecustom_speedtest_wifi
                    : R.string.sharemessage_speedtest_wifi);

            if (rating >= 5 || allowConfirm == 0) {
                title = Global.getAppName(owner);
                msg = "mmc detected ";
                if (droptype == EventType.EVT_CALLFAIL)
                    message = owner.getString((customText == 1) ? R.string.Custom_Notification_call_failed
                            : R.string.MMC_Notification_call_failed);
                else
                    message = owner.getString((customText == 1) ? R.string.Custom_Notification_call_dropped
                            : R.string.MMC_Notification_call_dropped);
                message += ": " + owner.getString(R.string.MMC_Notification_view_event);
                msg += message;
            } else if (rating >= allowConfirm && rating > 1) {
                if (droptype == EventType.EVT_CALLFAIL) {
                    title = owner.getString((customText == 1) ? R.string.Custom_Notification_did_you_fail
                            : R.string.MMC_Notification_did_you_fail);
                    message = owner.getString((customText == 1) ? R.string.Custom_Notification_did_failed
                            : R.string.MMC_Notification_did_failed);
                } else if (droptype == EventType.EVT_DROP) {
                    title = owner.getString((customText == 1) ? R.string.Custom_Notification_did_you_drop
                            : R.string.Custom_Notification_did_dropped);
                    message = owner.getString((customText == 1) ? R.string.MMC_Notification_did_dropped
                            : R.string.MMC_Notification_did_dropped);
                } else if (droptype == EventType.EVT_DISCONNECT || droptype == EventType.EVT_UNANSWERED) {
                    expiry = 60000;
                    icon = R.drawable.ic_stat_disconnect;
                    title = owner.getString((customText == 1) ? R.string.Custom_Notification_did_you_disconnect
                            : R.string.MMC_Notification_did_you_disconnect);
                    message = owner.getString((customText == 1) ? R.string.Custom_Notification_did_disconnect
                            : R.string.MMC_Notification_did_disconnect);
                }
                msg = message;
            }

            java.util.Date date = new java.util.Date();
            String time = date.toLocaleString();
            msg += " at " + time;
            //Toast toast = Toast.makeText(MainService.this, msg, Toast.LENGTH_LONG);
            //toast.show();

            NotificationManager notificationManager = (NotificationManager) owner
                    .getSystemService(Service.NOTIFICATION_SERVICE);
            Notification notification = new Notification(icon, message, System.currentTimeMillis());
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            //Intent notificationIntent = new Intent(MainService.this, Dashboard.class);
            Intent notificationIntent = new Intent();//, "com.cortxt.app.mmcui.Activities.Dashboard");
            notificationIntent.setClassName(owner, "com.cortxt.app.uilib.Activities.Dashboard");
            notificationIntent.putExtra("eventId", evtId);

            notificationIntent.setData((Uri.parse("foobar://" + SystemClock.elapsedRealtime())));
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(owner, MMC_DROPPED_NOTIFICATION + evtId,
                    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            notification.setLatestEventInfo(owner, title, message, pendingIntent);
            notificationManager.notify(MMC_DROPPED_NOTIFICATION, notification);
            long expirytime = System.currentTimeMillis() + expiry;
            PreferenceManager.getDefaultSharedPreferences(owner).edit()
                    .putLong(PreferenceKeys.Monitoring.NOTIFICATION_EXPIRY, expirytime).commit();

        }
    });

}