Example usage for java.util ArrayList clear

List of usage examples for java.util ArrayList clear

Introduction

In this page you can find the example usage for java.util ArrayList clear.

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this list.

Usage

From source file:com.amaze.filemanager.activities.MainActivity.java

/**
 * Returns all available SD-Cards in the system (include emulated)
 * <p>//w ww .j  a  v  a 2 s  .  c o  m
 * Warning: Hack! Based on Android source code of version 4.3 (API 18)
 * Because there is no standard way to get it.
 * TODO: Test on future Android versions 4.4+
 *
 * @return paths to all available SD-Cards in the system (include emulated)
 */

public List<String> getStorageDirectories() {
    // Final set of paths
    final ArrayList<String> rv = new ArrayList<>();
    // Primary physical SD-CARD (not emulated)
    final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
    // All Secondary SD-CARDs (all exclude primary) separated by ":"
    final String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
    // Primary emulated SD-CARD
    final String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
    if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
        // Device has physical external storage; use plain paths.
        if (TextUtils.isEmpty(rawExternalStorage)) {
            // EXTERNAL_STORAGE undefined; falling back to default.
            rv.add("/storage/sdcard0");
        } else {
            rv.add(rawExternalStorage);
        }
    } else {
        // Device has emulated storage; external storage paths should have
        // userId burned into them.
        final String rawUserId;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            rawUserId = "";
        } else {
            final String path = Environment.getExternalStorageDirectory().getAbsolutePath();
            final String[] folders = DIR_SEPARATOR.split(path);
            final String lastFolder = folders[folders.length - 1];
            boolean isDigit = false;
            try {
                Integer.valueOf(lastFolder);
                isDigit = true;
            } catch (NumberFormatException ignored) {
            }
            rawUserId = isDigit ? lastFolder : "";
        }
        // /storage/emulated/0[1,2,...]
        if (TextUtils.isEmpty(rawUserId)) {
            rv.add(rawEmulatedStorageTarget);
        } else {
            rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
        }
    }
    // Add all secondary storages
    if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
        // All Secondary SD-CARDs splited into array
        final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
        Collections.addAll(rv, rawSecondaryStorages);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkStoragePermission())
        rv.clear();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        String strings[] = FileUtil.getExtSdCardPathsForActivity(this);
        for (String s : strings) {
            File f = new File(s);
            if (!rv.contains(s) && utils.canListFiles(f))
                rv.add(s);
        }
    }
    rootmode = Sp.getBoolean("rootmode", false);
    if (rootmode)
        rv.add("/");
    File usb = getUsbDrive();
    if (usb != null && !rv.contains(usb.getPath()))
        rv.add(usb.getPath());
    return rv;
}

From source file:be.ibridge.kettle.trans.TransMeta.java

/**
     * Checks all the steps and fills a List of (CheckResult) remarks.
     */*  w w w  .j  av  a 2 s. co  m*/
     * @param remarks The remarks list to add to.
     * @param only_selected Check only the selected steps.
     * @param monitor The progress monitor to use, null if not used
     */
    public void checkSteps(ArrayList remarks, boolean only_selected, IProgressMonitor monitor) {
        try {
            remarks.clear(); // Start with a clean slate...

            Hashtable values = new Hashtable();
            String stepnames[];
            StepMeta steps[];
            if (!only_selected || nrSelectedSteps() == 0) {
                stepnames = getStepNames();
                steps = getStepsArray();
            } else {
                stepnames = getSelectedStepNames();
                steps = getSelectedSteps();
            }

            boolean stop_checking = false;

            if (monitor != null)
                monitor.beginTask(Messages.getString("TransMeta.Monitor.VerifyingThisTransformationTask.Title"), //$NON-NLS-1$
                        steps.length + 2);

            for (int i = 0; i < steps.length && !stop_checking; i++) {
                if (monitor != null)
                    monitor.subTask(Messages.getString("TransMeta.Monitor.VerifyingStepTask.Title", stepnames[i])); //$NON-NLS-1$ //$NON-NLS-2$

                StepMeta stepMeta = steps[i];

                int nrinfo = findNrInfoSteps(stepMeta);
                StepMeta[] infostep = null;
                if (nrinfo > 0) {
                    infostep = getInfoStep(stepMeta);
                }

                Row info = null;
                if (infostep != null) {
                    try {
                        info = getStepFields(infostep);
                    } catch (KettleStepException kse) {
                        info = null;
                        CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                                "TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingStepInfoFields.Description", //$NON-NLS-1$
                                "" + stepMeta, Const.CR + kse.getMessage()), stepMeta);
                        remarks.add(cr);
                    }
                }

                // The previous fields from non-informative steps:
                Row prev = null;
                try {
                    prev = getPrevStepFields(stepMeta);
                } catch (KettleStepException kse) {
                    CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                            "TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingInputFields.Description",
                            "" + stepMeta, Const.CR + kse.getMessage()), stepMeta); //$NON-NLS-1$
                    remarks.add(cr);
                    // This is a severe error: stop checking...
                    // Otherwise we wind up checking time & time again because nothing gets put in the database
                    // cache, the timeout of certain databases is very long... (Oracle)
                    stop_checking = true;
                }

                if (isStepUsedInTransHops(stepMeta)) {
                    // Get the input & output steps!
                    // Copy to arrays:
                    String input[] = getPrevStepNames(stepMeta);
                    String output[] = getPrevStepNames(stepMeta);

                    // Check step specific info...
                    stepMeta.check(remarks, prev, input, output, info);

                    // See if illegal characters etc. were used in field-names...
                    if (prev != null) {
                        for (int x = 0; x < prev.size(); x++) {
                            Value v = prev.getValue(x);
                            String name = v.getName();
                            if (name == null)
                                values.put(v, Messages.getString(
                                        "TransMeta.Value.CheckingFieldName.FieldNameIsEmpty.Description")); //$NON-NLS-1$
                            else if (name.indexOf(' ') >= 0)
                                values.put(v, Messages.getString(
                                        "TransMeta.Value.CheckingFieldName.FieldNameContainsSpaces.Description")); //$NON-NLS-1$
                            else {
                                char list[] = new char[] { '.', ',', '-', '/', '+', '*', '\'', '\t', '"', '|', '@',
                                        '(', ')', '{', '}', '!', '^' };
                                for (int c = 0; c < list.length; c++) {
                                    if (name.indexOf(list[c]) >= 0)
                                        values.put(v, Messages.getString(
                                                "TransMeta.Value.CheckingFieldName.FieldNameContainsUnfriendlyCodes.Description", //$NON-NLS-1$
                                                String.valueOf(list[c]))); //$NON-NLS-2$
                                }
                            }
                        }

                        // Check if 2 steps with the same name are entering the step...
                        if (prev.size() > 1) {
                            String fieldNames[] = prev.getFieldNames();
                            String sortedNames[] = Const.sortStrings(fieldNames);

                            String prevName = sortedNames[0];
                            for (int x = 1; x < sortedNames.length; x++) {
                                // Checking for doubles
                                if (prevName.equalsIgnoreCase(sortedNames[x])) {
                                    // Give a warning!!
                                    CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING,
                                            Messages.getString(
                                                    "TransMeta.CheckResult.TypeResultWarning.HaveTheSameNameField.Description", //$NON-NLS-1$
                                                    prevName),
                                            stepMeta); //$NON-NLS-2$
                                    remarks.add(cr);
                                } else {
                                    prevName = sortedNames[x];
                                }
                            }
                        }
                    } else {
                        CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                                "TransMeta.CheckResult.TypeResultError.CannotFindPreviousFields.Description") //$NON-NLS-1$
                                + stepMeta.getName(), stepMeta);
                        remarks.add(cr);
                    }
                } else {
                    CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING,
                            Messages.getString("TransMeta.CheckResult.TypeResultWarning.StepIsNotUsed.Description"), //$NON-NLS-1$
                            stepMeta);
                    remarks.add(cr);
                }

                if (monitor != null) {
                    monitor.worked(1); // progress bar...
                    if (monitor.isCanceled())
                        stop_checking = true;
                }
            }

            // Also, check the logging table of the transformation...
            if (monitor == null || !monitor.isCanceled()) {
                if (monitor != null)
                    monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingTheLoggingTableTask.Title")); //$NON-NLS-1$
                if (getLogConnection() != null) {
                    Database logdb = new Database(getLogConnection());
                    try {
                        logdb.connect();
                        CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK,
                                Messages.getString(
                                        "TransMeta.CheckResult.TypeResultOK.ConnectingWorks.Description"), //$NON-NLS-1$
                                null);
                        remarks.add(cr);

                        if (getLogTable() != null) {
                            if (logdb.checkTableExists(getLogTable())) {
                                cr = new CheckResult(CheckResult.TYPE_RESULT_OK,
                                        Messages.getString(
                                                "TransMeta.CheckResult.TypeResultOK.LoggingTableExists.Description", //$NON-NLS-1$
                                                getLogTable()),
                                        null); //$NON-NLS-2$
                                remarks.add(cr);

                                Row fields = Database.getTransLogrecordFields(isBatchIdUsed(), isLogfieldUsed());
                                String sql = logdb.getDDL(getLogTable(), fields);
                                if (sql == null || sql.length() == 0) {
                                    cr = new CheckResult(CheckResult.TYPE_RESULT_OK,
                                            Messages.getString(
                                                    "TransMeta.CheckResult.TypeResultOK.CorrectLayout.Description"), //$NON-NLS-1$
                                            null);
                                    remarks.add(cr);
                                } else {
                                    cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                                            "TransMeta.CheckResult.TypeResultError.LoggingTableNeedsAdjustments.Description") //$NON-NLS-1$
                                            + Const.CR + sql, null);
                                    remarks.add(cr);
                                }

                            } else {
                                cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                                        "TransMeta.CheckResult.TypeResultError.LoggingTableDoesNotExist.Description"), //$NON-NLS-1$
                                        null);
                                remarks.add(cr);
                            }
                        } else {
                            cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString(
                                    "TransMeta.CheckResult.TypeResultError.LogTableNotSpecified.Description"), //$NON-NLS-1$
                                    null);
                            remarks.add(cr);
                        }
                    } catch (KettleDatabaseException dbe) {

                    } finally {
                        logdb.disconnect();
                    }
                }
                if (monitor != null)
                    monitor.worked(1);

            }

            if (monitor != null)
                monitor.subTask(Messages.getString(
                        "TransMeta.Monitor.CheckingForDatabaseUnfriendlyCharactersInFieldNamesTask.Title")); //$NON-NLS-1$
            if (values.size() > 0) {
                Enumeration keys = values.keys();
                while (keys.hasMoreElements()) {
                    Value v = (Value) keys.nextElement();
                    String message = (String) values.get(v);
                    CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING,
                            Messages.getString("TransMeta.CheckResult.TypeResultWarning.Description", v.getName(), //$NON-NLS-1$
                                    message, v.getOrigin()),
                            findStep(v.getOrigin()));
                    remarks.add(cr);
                }
            } else {
                CheckResult cr = new CheckResult(CheckResult.TYPE_RESULT_OK,
                        Messages.getString("TransMeta.CheckResult.TypeResultOK.Description"), null); //$NON-NLS-1$
                remarks.add(cr);
            }
            if (monitor != null)
                monitor.worked(1);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobController.java

public ModelAndView DeleteInternalJobs(HttpServletRequest request, HttpServletResponse response) {
    List tabledata = null;//from  w  ww  . j  a va 2 s .  c  o  m
    JSONObject jobj = new JSONObject();
    JSONObject jobj1 = new JSONObject();
    String hql = null;
    boolean flag = true;
    ArrayList<String> name = new ArrayList<String>();
    ArrayList<Object> value = new ArrayList<Object>();
    KwlReturnObject result = null;
    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    String title = "Success";
    try {
        String delids[] = request.getParameterValues("delid");
        for (int i = 0; i < delids.length; i++) {
            name.clear();
            value.clear();
            //                hql = "from Allapplications where position.positionid=? and company.companyID=? and delflag=0";
            //                tabledata = HibernateUtil.executeQuery(session, hql, new Object[]{delids[i], AuthHandler.getCompanyid(request)});
            name.add("position.positionid");
            value.add(delids[i]);
            name.add("company.companyID");
            value.add(sessionHandlerImplObj.getCompanyid(request));
            name.add("delflag");
            value.add(0);
            result = hrmsRecJobDAOObj.getPositionstatus(name, value);
            tabledata = result.getEntityList();
            if (tabledata.isEmpty()) {
                HashMap<String, Object> requestParams = new HashMap<String, Object>();

                requestParams.put("filter_names", Arrays.asList("applypos"));
                requestParams.put("filter_values", Arrays.asList((Positionmain) kwlCommonTablesDAOObj
                        .getObject("com.krawler.hrms.recruitment.Positionmain", delids[i])));
                result = hrmsRecAgencyDAOObj.getApplyagency(requestParams);
                if (result.getEntityList().isEmpty()) {
                    name.clear();
                    value.clear();
                    name.add("positionid");
                    value.add(delids[i]);

                    //                    hql = "from Positionmain where positionid=?";
                    //                    tabledata = HibernateUtil.executeQuery(session, hql, delids[i]);
                    requestParams.clear();
                    requestParams.put("filter_names", name);
                    requestParams.put("filter_values", value);
                    result = hrmsRecJobDAOObj.getPositionmain(requestParams);
                    tabledata = result.getEntityList();
                    if (!tabledata.isEmpty()) {
                        requestParams = new HashMap<String, Object>();
                        requestParams.put("delflag", 1);
                        requestParams.put("positionid", delids[i]);
                        result = hrmsRecJobDAOObj.updatePositionmain(requestParams);
                        //                        Positionmain log = (Positionmain) tabledata.get(0);
                        //                        log.setDelflag(1);
                        //                        session.update(log);

                    }
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
        if (flag) {
            jobj.put("message",
                    messageSource.getMessage("hrms.recruitment.SelectedJobPositionsuccessfullydeleted", null,
                            "Selected Job Position(s) successfully deleted.",
                            RequestContextUtils.getLocale(request)));
        } else {
            jobj.put("message", messageSource.getMessage("hrms.recruitment.SomejobscannotbedeletedBeacause",
                    null,
                    "Some jobs have assigned applicants or are assigned to agencies and hence cannot be deleted.",
                    RequestContextUtils.getLocale(request)));
        }
        jobj1.put("valid", true);
        jobj.put("title", title);
        jobj1.put("data", jobj.toString());
        txnManager.commit(status);
    } catch (Exception ex) {
        ex.printStackTrace();
        txnManager.rollback(status);
    } finally {
        return new ModelAndView("jsonView", "model", jobj1.toString());
    }
}

From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobController.java

public ModelAndView addRecruitersFunction(HttpServletRequest request, HttpServletResponse response) {
    //Status 0=pending,1=accepted,2=rejected,3=Not sent
    List tabledata = null;//from ww  w . j a  v a  2  s.c o  m
    String hql = null;
    Recruiter pos = null;
    JSONObject jobj = new JSONObject();
    JSONObject jobj1 = new JSONObject();
    KwlReturnObject result = null;

    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {

        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        ArrayList filter_names = new ArrayList(), filter_values = new ArrayList();

        String[] recids = null;
        String auditmsg = "";
        Company cmpid = (Company) kwlCommonTablesDAOObj.getObject("com.krawler.common.admin.Company",
                sessionHandlerImplObj.getCompanyid(request));
        User u = (User) kwlCommonTablesDAOObj.getObject("com.krawler.common.admin.User",
                sessionHandlerImplObj.getUserid(request));
        if (StringUtil.isNullOrEmpty(request.getParameter("delrec"))) {
            recids = request.getParameterValues("jobids");
            for (int i = 0; i < recids.length; i++) {

                requestParams.clear();
                filter_names.clear();
                filter_values.clear();

                filter_names.add("recruit.userID");
                filter_values.add(recids[i]);

                requestParams.put("filter_names", filter_names);
                requestParams.put("filter_values", filter_values);

                result = hrmsRecJobDAOObj.getRecruiter(requestParams);
                tabledata = result.getEntityList();
                requestParams.clear();
                if (!tabledata.isEmpty()) {
                    pos = (Recruiter) tabledata.get(0);

                    requestParams.put("Rid", pos.getRid());
                    requestParams.put("Delflag", 0);

                    auditmsg = "User  "
                            + profileHandlerDAOObj.getUserFullName(sessionHandlerImplObj.getUserid(request))
                            + " has set " + StringUtil.getFullName(pos.getRecruit()) + " as interviewer";
                } else {
                    User md = (User) kwlCommonTablesDAOObj.getObject("com.krawler.common.admin.User",
                            recids[i]);
                    requestParams.put("Delflag", 0);
                    //requestParams.put("Recruit",md);
                    requestParams.put("Recruit", recids[i]);

                    auditmsg = "User  "
                            + profileHandlerDAOObj.getUserFullName(sessionHandlerImplObj.getUserid(request))
                            + " has set " + StringUtil.getFullName(md) + " as interviewer";
                }

                result = hrmsRecJobDAOObj.setRecruiters(requestParams);
                if (result.isSuccessFlag()) {
                    auditTrailDAOObj.insertAuditLog(AuditAction.SET_AS_INTERVIEWER, auditmsg, request, "0");
                }
            }
        } else {
            String[] delrecids = request.getParameterValues("appid");
            for (int i = 0; i < delrecids.length; i++) {

                requestParams.clear();
                filter_names.clear();
                filter_values.clear();

                filter_names.add("recruit.userID");
                filter_values.add(delrecids[i]);

                requestParams.put("filter_names", filter_names);
                requestParams.put("filter_values", filter_values);

                result = hrmsRecJobDAOObj.getRecruiter(requestParams);
                tabledata = result.getEntityList();
                requestParams.clear();
                if (!tabledata.isEmpty()) {
                    pos = (Recruiter) tabledata.get(0);

                    requestParams.put("Rid", pos.getRid());
                    requestParams.put("Delflag", 3);

                    auditmsg = "User  " + StringUtil.getFullName(pos.getRecruit())
                            + " has been unassigned  as interviewer by "
                            + profileHandlerDAOObj.getUserFullName(sessionHandlerImplObj.getUserid(request));
                }

                result = hrmsRecJobDAOObj.setRecruiters(requestParams);
                if (result.isSuccessFlag()) {
                    auditTrailDAOObj.insertAuditLog(AuditAction.SET_AS_INTERVIEWER, auditmsg, request, "0");
                }
            }
        }
        if (StringUtil.isNullOrEmpty(request.getParameter("delrec"))) {
            for (int i = 0; i < recids.length; i++) {
                User r = (User) kwlCommonTablesDAOObj.getObject("com.krawler.common.admin.User", recids[i]);
                Useraccount ua = (Useraccount) kwlCommonTablesDAOObj
                        .getObject("com.krawler.common.admin.Useraccount", r.getUserID());
                String fullname = StringUtil.getFullName(r);
                String uri = URLUtil.getPageURL(request, Links.loginpagewthFull, cmpid.getSubDomain())
                        + "jspfiles/Confirmation.jsp?c=" + cmpid.getCompanyID() + "&u=" + r.getUserID()
                        + "&acpt=";
                String pmsg = String.format(HrmsMsgs.interviewerSelectionpln, fullname);
                String htmlmsg = String.format(HrmsMsgs.interviewerSelectionHTML, fullname, uri + "1",
                        uri + "0", StringUtil.getFullName(u), cmpid.getCompanyName());
                try {
                    SendMailHandler.postMail(new String[] { r.getEmailID() }, HrmsMsgs.interviewerSubject,
                            htmlmsg, pmsg, u.getEmailID());
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
        jobj.put("success", true);
        jobj1.put("data", jobj.toString());
        jobj1.put("valid", true);
        txnManager.commit(status);
    } catch (Exception e) {
        e.printStackTrace();
        txnManager.rollback(status);
    }

    return new ModelAndView("jsonView", "model", jobj1.toString());
}

From source file:com.irccloud.android.data.collection.NotificationsList.java

private void showMessageNotifications(String ticker) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
    String text = "";
    final List<Notification> notifications = getMessageNotifications();

    int notify_type = Integer.parseInt(prefs.getString("notify_type", "1"));
    boolean notify = false;
    if (notify_type == 1 || (notify_type == 2 && NetworkConnection.getInstance().isVisible()))
        notify = true;//from ww  w .  ja v a2 s  . c o m

    if (notifications.size() > 0 && notify) {
        int lastbid = notifications.get(0).bid;
        int count = 0;
        long[] eids = new long[notifications.size()];
        ArrayList<Notification> messages = new ArrayList<>(notifications.size());
        Notification last = notifications.get(0);
        boolean show = false;
        for (Notification n : notifications) {
            if (n.bid != lastbid) {
                if (show) {
                    String title = last.chan;
                    if (title == null || title.length() == 0)
                        title = last.nick;
                    if (title == null || title.length() == 0)
                        title = last.network;

                    Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
                    replyIntent.putExtra("bid", last.bid);
                    replyIntent.putExtra("cid", last.cid);
                    replyIntent.putExtra("eids", eids);
                    replyIntent.putExtra("network", last.network);
                    replyIntent.putExtra("chan", last.chan);
                    replyIntent.putExtra("buffer_type", last.buffer_type);
                    replyIntent.putExtra("to", last.chan);

                    String body;
                    if (last.buffer_type.equals("channel")) {
                        if (last.message_type.equals("buffer_me_msg"))
                            body = "<b> " + ((last.nick != null) ? last.nick : getServerNick(last.cid))
                                    + "</b> " + last.message;
                        else
                            body = "<b>&lt;" + ((last.nick != null) ? last.nick : getServerNick(last.cid))
                                    + "&gt;</b> " + last.message;
                    } else {
                        if (last.message_type.equals("buffer_me_msg"))
                            body = " " + ((last.nick != null) ? last.nick : getServerNick(last.cid)) + " "
                                    + last.message;
                        else
                            body = last.message;
                    }

                    ArrayList<String> lines = new ArrayList<>(Arrays.asList(text.split("<br/>")));
                    while (lines.size() > 3)
                        lines.remove(0);

                    try {
                        Crashlytics.log(Log.DEBUG, "IRCCloud",
                                "Posting notification for type " + last.message_type);
                        NotificationManagerCompat
                                .from(IRCCloudApplication.getInstance().getApplicationContext())
                                .notify(lastbid, buildNotification(ticker, last.cid, lastbid, eids, title, body,
                                        count, replyIntent, last.network, messages, null,
                                        AvatarsList.getInstance().getAvatar(last.cid, last.nick).getBitmap(
                                                false,
                                                (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 64,
                                                        IRCCloudApplication.getInstance()
                                                                .getApplicationContext().getResources()
                                                                .getDisplayMetrics()),
                                                false, Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP),
                                        AvatarsList.getInstance().getAvatar(last.cid, last.nick)
                                                .getBitmap(false, 400, false, false)));
                    } catch (Exception e) {
                        Crashlytics.logException(e);
                    }
                }
                lastbid = n.bid;
                text = "";
                count = 0;
                eids = new long[notifications.size()];
                show = false;
                messages.clear();
            }

            if (text.length() > 0)
                text += "<br/>";
            if (n.buffer_type.equals("conversation") && n.message_type.equals("buffer_me_msg"))
                text += " " + n.message;
            else if (n.buffer_type.equals("conversation"))
                text += n.message;
            else if (n.message_type.equals("buffer_me_msg"))
                text += "<b> " + ((n.nick != null) ? n.nick : getServerNick(n.cid)) + "</b> " + n.message;
            else
                text += "<b>" + ((n.nick != null) ? n.nick : getServerNick(n.cid)) + "</b> " + n.message;

            if (!n.shown) {
                n.shown = true;
                show = true;

                if (n.nick != null && prefs.getBoolean("notify_sony", false)) {
                    long time = System.currentTimeMillis();
                    long sourceId = NotificationUtil.getSourceId(
                            IRCCloudApplication.getInstance().getApplicationContext(),
                            SonyExtensionService.EXTENSION_SPECIFIC_ID);
                    if (sourceId == NotificationUtil.INVALID_ID) {
                        Crashlytics.log(Log.ERROR, "IRCCloud",
                                "Sony LiveWare Manager not configured, disabling Sony notifications");
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putBoolean("notify_sony", false);
                        editor.commit();
                    } else {
                        ContentValues eventValues = new ContentValues();
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.EVENT_READ_STATUS,
                                false);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.DISPLAY_NAME,
                                n.nick);

                        if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE,
                                    n.chan);
                        else
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE,
                                    n.network);

                        if (n.message_type.equals("buffer_me_msg"))
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE,
                                    " " + Html.fromHtml(n.message).toString());
                        else
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE,
                                    Html.fromHtml(n.message).toString());

                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PERSONAL,
                                1);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PUBLISHED_TIME,
                                time);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.SOURCE_ID,
                                sourceId);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY,
                                String.valueOf(n.bid));

                        try {
                            IRCCloudApplication.getInstance().getApplicationContext().getContentResolver()
                                    .insert(com.sonyericsson.extras.liveware.aef.notification.Notification.Event.URI,
                                            eventValues);
                        } catch (IllegalArgumentException e) {
                            Log.e("IRCCloud", "Failed to insert event", e);
                        } catch (SecurityException e) {
                            Log.e("IRCCloud", "Failed to insert event, is Live Ware Manager installed?", e);
                        } catch (SQLException e) {
                            Log.e("IRCCloud", "Failed to insert event", e);
                        }
                    }
                }

                if (prefs.getBoolean("notify_pebble", false) && n.nick != null) {
                    String pebbleTitle = n.network + ":\n";
                    String pebbleBody = "";
                    if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
                        pebbleTitle = n.chan + ":\n";

                    if (n.message_type.equals("buffer_me_msg"))
                        pebbleBody = " " + n.message;
                    else
                        pebbleBody = n.message;

                    if (n.chan != null && n.nick != null && n.nick.length() > 0)
                        notifyPebble(n.nick, pebbleTitle + Html.fromHtml(pebbleBody).toString());
                    else
                        notifyPebble(n.network, pebbleTitle + Html.fromHtml(pebbleBody).toString());
                }
            }
            messages.add(n);
            eids[count++] = n.eid;
            if (n.nick != null)
                last = n;
        }

        if (show) {
            String title = last.chan;
            if (title == null || title.length() == 0)
                title = last.network;

            Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
            replyIntent.putExtra("bid", last.bid);
            replyIntent.putExtra("cid", last.cid);
            replyIntent.putExtra("network", last.network);
            replyIntent.putExtra("eids", eids);
            replyIntent.putExtra("chan", last.chan);
            replyIntent.putExtra("buffer_type", last.buffer_type);
            replyIntent.putExtra("to", last.chan);

            String body = "";
            if (last.buffer_type.equals("channel")) {
                if (last.message_type.equals("buffer_me_msg"))
                    body = "<b> " + ((last.nick != null) ? last.nick : getServerNick(last.cid)) + "</b> "
                            + last.message;
                else
                    body = "<b>&lt;" + ((last.nick != null) ? last.nick : getServerNick(last.cid)) + "&gt;</b> "
                            + last.message;
            } else {
                if (last.message_type.equals("buffer_me_msg"))
                    body = " " + ((last.nick != null) ? last.nick : getServerNick(last.cid)) + " "
                            + last.message;
                else
                    body = last.message;
            }

            ArrayList<String> lines = new ArrayList<>(Arrays.asList(text.split("<br/>")));
            while (lines.size() > 3)
                lines.remove(0);

            try {
                Crashlytics.log(Log.DEBUG, "IRCCloud", "Posting notification for type " + last.message_type);
                NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext())
                        .notify(last.bid, buildNotification(ticker, last.cid, last.bid, eids, title, body,
                                count, replyIntent, last.network, messages, null,
                                AvatarsList.getInstance().getAvatar(last.cid, last.nick).getBitmap(false,
                                        (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 64,
                                                IRCCloudApplication.getInstance().getApplicationContext()
                                                        .getResources().getDisplayMetrics()),
                                        false, Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP),
                                AvatarsList.getInstance().getAvatar(last.cid, last.nick).getBitmap(false, 400,
                                        false, false)));
            } catch (Exception e) {
                Crashlytics.logException(e);
            }
        }

        TransactionManager.transact(IRCCloudDatabase.NAME, new Runnable() {
            @Override
            public void run() {
                for (Notification n : notifications) {
                    n.save();
                }
            }
        });
    }
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void clearDirHist(ArrayList<String> hl) {
    sendDebugLogMsg(1, "I", "clearDirHist history cleared");
    //      Log.v("","history cleared");
    hl.clear();
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void replaceDirHist(ArrayList<String> to, ArrayList<String> from) {
    //      Log.v("","history replaced ");
    sendDebugLogMsg(1, "I", "replaceDirHist history replaced");
    to.clear();
    to.addAll(from);//from ww  w  .j  ava2s.co m
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void checkRemoteFileExists(String url, String user, String pass, ArrayList<String> d_list,
        final NotifyEvent n_event) {
    final ArrayList<FileListItem> remoteFileList = new ArrayList<FileListItem>();

    final ThreadCtrl tc = new ThreadCtrl();
    remoteFileList.clear();
    tc.setEnabled();/*from w w  w . j  a v a  2 s . c om*/

    showRemoteProgressView();

    mRemoteProgressMsg.setText(R.string.msgs_progress_spin_dlg_title3);

    mRemoteProgressMsg.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            tc.setDisabled();//disableAsyncTask();
            sendDebugLogMsg(1, "W", "Filelist is cancelled.");
        }
    });

    NotifyEvent ne = new NotifyEvent(this);
    ne.setListener(new NotifyEventListener() {
        @Override
        public void positiveResponse(Context c, Object[] o) {
            hideRemoteProgressView();
            if (tc.isThreadResultSuccess()) {
                n_event.notifyToListener(true, o);
            } else {
                String err = "";
                if (tc.isThreadResultCancelled())
                    err = "Filelist was cancelled";
                else
                    err = tc.getThreadMessage();
                n_event.notifyToListener(false, new Object[] { err });
            }
        }

        @Override
        public void negativeResponse(Context c, Object[] o) {
            hideRemoteProgressView();
        }
    });

    Thread th = new Thread(new RetrieveFileList(mGp, tc, url, d_list, user, pass, ne));
    th.start();
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void readRemoteFileList(String url, String user, String pass, final NotifyEvent n_event) {
    final ArrayList<FileListItem> remoteFileList = new ArrayList<FileListItem>();

    final ThreadCtrl tc = new ThreadCtrl();
    remoteFileList.clear();
    tc.setEnabled();/*from  w w w  .  j a  va 2s  .c om*/

    showRemoteProgressView();

    mRemoteProgressMsg.setText(R.string.msgs_progress_spin_dlg_title3);

    mRemoteProgressMsg.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            tc.setDisabled();//disableAsyncTask();
            sendDebugLogMsg(1, "W", "Filelist is cancelled.");
        }
    });

    NotifyEvent ne = new NotifyEvent(this);
    ne.setListener(new NotifyEventListener() {
        @Override
        public void positiveResponse(Context c, Object[] o) {
            hideRemoteProgressView();
            if (tc.isThreadResultSuccess()) {
                n_event.notifyToListener(true, new Object[] { remoteFileList });
            } else {
                String err = "";
                if (tc.isThreadResultCancelled())
                    err = "Filelist was cancelled";
                else
                    err = tc.getThreadMessage();
                n_event.notifyToListener(false, new Object[] { err });
            }
            saveTaskData();
        }

        @Override
        public void negativeResponse(Context c, Object[] o) {
            hideRemoteProgressView();
            saveTaskData();
        }
    });

    Thread th = new Thread(new RetrieveFileList(mGp, tc, RetrieveFileList.OPCD_FILE_LIST, url, remoteFileList,
            user, pass, ne));
    th.start();
}

From source file:dbseer.comp.process.transaction.TransactionLogWriter.java

public void writeLog(long timestamp, Collection<Transaction> transactions) throws Exception {
    if (!this.isInitialized) {
        throw new Exception("TransactionLogWriter not initialized.");
    }// www  .  ja v  a2  s. com

    double totalCount = 0;
    double[][] count = new double[numServer][DBSeerConstants.MAX_NUM_TABLE];
    double[][] latencySum = new double[numServer][DBSeerConstants.MAX_NUM_TABLE];
    String gap = "   ";

    if (!dbscan.isInitialized() && !dbscan.isInitializing()) {
        initialTransactions.addAll(transactions);

        if (initialTransactions.size() > dbscan.getInitPts() && !dbscan.isInitializing()) {
            dbscanInitializer = Executors.newSingleThreadExecutor();
            dbscanInitializer.submit(new Runnable() {
                @Override
                public void run() {
                    dbscan.initialDBSCAN(initialTransactions);
                }
            });
        }
    }

    for (Transaction t : transactions) {
        if (dbscan != null && dbscan.isInitialized()) {
            if (liveLogProcessor.getTxStartTime() == 0) {
                liveLogProcessor.setTxStartTime(timestamp);
            }
            dbscan.train(t);
        }

        int type;
        if (t.getCluster() == null) {
            type = 0;
        } else {
            type = t.getCluster().getId();
        }

        if (type > maxType) {
            maxType = type;
        }

        // if not outlier;
        if (type >= 0) {
            String server = t.getServerName();
            int index = serverIndex.get(server);
            latencySum[index][type] += t.getLatency();
            count[index][type]++;
            totalCount++;

            ArrayList<Double> latencyList = writers.get(server).getLatencyMap().get(type);
            if (latencyList == null) {
                latencyList = new ArrayList<Double>();
                writers.get(server).getLatencyMap().put(type, latencyList);
            }
            latencyList.add((double) t.getLatency());

            // write sample
            HashMap<Integer, Integer> countMap = writers.get(server).getTransactionSampleCountMap();
            Integer sampleCount = countMap.get(type);
            if (sampleCount == null) {
                countMap.put(type, 1);
            } else {
                int countVal = sampleCount.intValue();
                if (countVal < DBSeerConstants.MAX_TRANSACTION_SAMPLE) {
                    HashMap<Integer, PrintWriter> sampleWriters = writers.get(server)
                            .getTransactionSampleWriter();
                    PrintWriter sampleWriter = sampleWriters.get(type);
                    if (sampleWriter == null) {
                        sampleWriter = new PrintWriter(new FileOutputStream(String.format("%s%d",
                                this.dir + File.separator + server + File.separator + "tx_sample_", type),
                                false));
                        sampleWriters.put(type, sampleWriter);
                    }
                    sampleWriter.print(t.getEntireStatement());
                    sampleWriter.println("---");
                    sampleWriter.flush();
                    countVal++;
                    countMap.put(type, countVal);
                }
            }
        }
    }

    // update live monitor
    if (monitor != null) {
        monitor.setCurrentTimestamp(timestamp);
        monitor.setNumTransactionTypes(maxType + 1);
        monitor.setGlobalTransactionCount(totalCount);

        for (int i = 0; i <= maxType; ++i) {
            double countSum = 0;
            double latencySumSum = 0;
            for (int j = 0; j < numServer; ++j) {
                countSum += count[j][i];
                latencySumSum += latencySum[j][i];
            }
            monitor.setCurrentTPS(i, countSum);
            if (countSum == 0) {
                monitor.setCurrentAverageLatency(i, 0.0);
            } else {
                monitor.setCurrentAverageLatency(i, latencySumSum / countSum);
            }
        }
    }

    if (timestamp < liveLogProcessor.getSysStartTime() || liveLogProcessor.getSysStartTime() == 0) {
        return;
    }

    for (String server : servers) {
        TransactionWriter writer = writers.get(server);
        PrintWriter tpsWriter = writer.getTpsWriter();
        PrintWriter latencyWriter = writer.getLatencyWriter();

        HashMap<Integer, PrintWriter> prctileLatencyWriter = writer.getPrctileLatencyWriter();
        HashMap<Integer, ArrayList<Double>> latencyMap = writer.getLatencyMap();

        tpsWriter.print(gap);
        latencyWriter.print(gap);

        tpsWriter.printf("%.16e", (double) timestamp);
        latencyWriter.printf("%.16e", (double) timestamp);

        int index = serverIndex.get(server);

        for (int i = 0; i <= maxType; ++i) {
            tpsWriter.print(gap);
            tpsWriter.printf("%.16e", count[index][i]);

            latencyWriter.print(gap);
            if (count[index][i] == 0.0) {
                latencyWriter.printf("%.16e", 0.0);
            } else {
                latencyWriter.printf("%.16e", (latencySum[index][i] / count[index][i]) / 1000.0);
            }

            // write percentile
            PrintWriter prctileWriter = prctileLatencyWriter.get(i);
            ArrayList<Double> latencyList = latencyMap.get(i);
            if (latencyList == null) {
                latencyList = new ArrayList<Double>();
                latencyMap.put(i, latencyList);
            }
            if (prctileWriter == null) {
                prctileWriter = new PrintWriter(new FileOutputStream(
                        String.format("%s%03d",
                                this.dir + File.separator + server + File.separator + "prctile_latency_", i),
                        false));
                prctileLatencyWriter.put(i, prctileWriter);
            }
            double[] latencies = Doubles.toArray(latencyList);
            prctileWriter.printf("%d,", timestamp);
            for (double p : percentiles) {
                Percentile percentile = new Percentile(p);
                percentile.setData(latencies);
                double val = percentile.evaluate();
                if (Double.isNaN(val))
                    val = 0.0;
                prctileWriter.printf("%f,", val / 1000.0);
            }
            prctileWriter.println();
            prctileWriter.flush();
            latencyList.clear();
        }

        tpsWriter.println();
        latencyWriter.println();
        tpsWriter.flush();
        latencyWriter.flush();
        isWritingStarted = true;
    }
}