Example usage for java.lang StringBuffer deleteCharAt

List of usage examples for java.lang StringBuffer deleteCharAt

Introduction

In this page you can find the example usage for java.lang StringBuffer deleteCharAt.

Prototype

@Override
public synchronized StringBuffer deleteCharAt(int index) 

Source Link

Usage

From source file:cn.jsprun.struts.action.BasicSettingsAction.java

public ActionForward permissions(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {//from  w  w  w.  j  a va 2s. c o m
    try {
        if (submitCheck(request, "settingsubmit")) {
            String variables[] = { "memliststatus", "reportpost", "minpostsize", "maxpostsize", "maxfavorites",
                    "maxsubscriptions", "maxavatarsize", "maxavatarpixel", "maxpolloptions", "edittimelimit",
                    "editedby", "karmaratelimit", "modratelimit", "dupkarmarate" };
            Map<String, String> oldSettings = ForumInit.settings;
            Map<String, String> settings = new HashMap<String, String>();
            for (String variable : variables) {
                String value = request.getParameter(variable);
                if (Common.matches(variable, "^(edittimelimit|karmaratelimit)$")) {
                    if (value != null) {
                        value = Double.valueOf(FormDataCheck.getDoubleString(value)).toString();
                        if (value.contains(".")) {
                            StringBuffer buffer = new StringBuffer(value);
                            while (true) {
                                if (buffer.charAt(buffer.length() - 1) == '.') {
                                    buffer.deleteCharAt(buffer.length() - 1);
                                    break;
                                } else if (buffer.charAt(buffer.length() - 1) == '0') {
                                    buffer.deleteCharAt(buffer.length() - 1);
                                } else {
                                    break;
                                }
                            }
                            value = buffer.toString();
                        }
                    }
                } else if ("|minpostsize|maxpostsize|maxavatarsize|maxavatarpixel|maxpolloptions|maxfavorites|maxsubscriptions|"
                        .contains(variable)) {
                    value = Common.toDigit(value) + "";
                }
                this.putValue(variable, value, oldSettings, settings);
            }
            this.updateSettings(settings, oldSettings);
            return this.getForward(mapping, request);
        }
    } catch (Exception e) {
        request.setAttribute("message", e.getMessage());
        return mapping.findForward("message");
    }
    return mapping.findForward("setting_permissions");
}

From source file:org.LexGrid.util.sql.lgTables.SQLTableUtilities.java

/**
 * Runs SQL Statement "UPDATE" on the given tableName with attribute values
 * and where clause.//  ww  w .  j av  a2  s .c  o m
 * 
 * @param tableName
 * @param attributeNameValue
 * @param whereClause
 * @return
 * @throws SQLException
 */
public int updateRow(String tableName, Map attributeNameValue, String whereClause, String dbType)
        throws SQLException {

    StringBuffer stmt = new StringBuffer();
    PreparedStatement prepStmt = null;
    int rowsUpdated = 0;
    Object attribute = null;
    Iterator itr = null;
    String[] key = new String[attributeNameValue.size()];
    int count = 0;

    stmt.append("UPDATE " + tablePrefix_ + tableName.trim() + " SET ");

    itr = attributeNameValue.keySet().iterator();

    while (itr.hasNext()) {
        key[count] = (String) itr.next();
        stmt.append(key[count++] + " = ?,");
    }

    /*
     * for (int i = 0; i < attributeNames.size(); i++) {
     * stmt.append(attributeNames.get(i) + " = ?,"); }
     */

    stmt = stmt.deleteCharAt(stmt.length() - 1);

    if (whereClause != null && !"".equals(whereClause)) {
        stmt.append(" WHERE ");
        stmt.append(whereClause);
    }

    // stmt = stmt.deleteCharAt(stmt.length());

    log.debug("************ UPDATE QUERY ************");
    log.debug(stmt.toString());
    log.debug("**************************************");
    try {

        String statement = new GenericSQLModifier(dbType, false).modifySQL(stmt.toString());

        prepStmt = sqlConnection_.prepareStatement(statement);

        itr = attributeNameValue.keySet().iterator();

        for (count = 0; count < key.length; count++) {

            attribute = attributeNameValue.get(key[count]);

            if (attribute instanceof String) {
                prepStmt.setString(count + 1, (String) attribute);
            } else if (attribute instanceof Blob) {
                prepStmt.setBlob(count + 1, (Blob) attribute);
            } else if (attribute instanceof Boolean) {
                prepStmt.setBoolean(count + 1, ((Boolean) attribute).booleanValue());
            } else if (attribute instanceof Byte) {
                prepStmt.setByte(count + 1, ((Byte) attribute).byteValue());
            } else if (attribute instanceof byte[]) {
                prepStmt.setBytes(count + 1, (byte[]) attribute);
            } else if (attribute instanceof Date) {
                prepStmt.setDate(count + 1, (Date) attribute);
            } else if (attribute instanceof Double) {
                prepStmt.setDouble(count + 1, ((Double) attribute).doubleValue());
            } else if (attribute instanceof Float) {
                prepStmt.setFloat(count + 1, ((Float) attribute).floatValue());
            } else if (attribute instanceof Integer) {
                prepStmt.setInt(count + 1, ((Integer) attribute).intValue());
            } else if (attribute instanceof Long) {
                prepStmt.setLong(count + 1, ((Long) attribute).longValue());
            } else if (attribute instanceof Short) {
                prepStmt.setShort(count + 1, ((Short) attribute).shortValue());
            } else if (attribute instanceof Timestamp) {
                prepStmt.setTimestamp(count + 1, (Timestamp) attribute);
            }
        }

        rowsUpdated = prepStmt.executeUpdate();
    } catch (Exception e) {
        log.error("Exception @ updateRow: " + e.getMessage());
    } finally {
        prepStmt.close();
    }

    return rowsUpdated;

}

From source file:cn.jsprun.struts.action.BasicSettingsAction.java

private void updateSettings(Map<String, String> settings, Map<String, String> oldSettings) {
    if (settings != null && settings.size() > 0) {
        Set<String> variables = settings.keySet();
        StringBuffer sql = new StringBuffer();
        sql.append("REPLACE INTO jrun_settings (variable, value) VALUES ");
        for (String variable : variables) {
            sql.append("('" + variable + "', '" + Common.addslashes(settings.get(variable)) + "'),");
        }//from   w  w  w.  ja v  a  2s. co m
        sql.deleteCharAt(sql.length() - 1);
        dataBaseService.runQuery(sql.toString(), true);
        oldSettings.putAll(settings);
        ForumInit.setSettings(this.getServlet().getServletContext(), oldSettings);
    }
}

From source file:net.creativeparkour.GameManager.java

/**
 * <em>Third-party plugins cannot use this method through CreativeParkour's API (it will throw an {@code InvalidQueryResponseException}).</em><br>
 * Method called when <a href="https://creativeparkour.net" target="_blank">creativeparkour.net</a> responds to a query.
 * @param json//from  w w  w .j a  va  2s.  c  om
 * @param rep
 * @param sender
 * @throws InvalidQueryResponseException If the {@code Request} has not been registered before.
 */
public static void reponseListe(JsonObject json, String rep, CommandSender sender)
        throws InvalidQueryResponseException {
    if (CPRequest.verifMethode("reponseListe") && !CreativeParkour.erreurRequete(json, sender)
            && json.get("data") != null) {
        Bukkit.getScheduler().runTaskAsynchronously(CreativeParkour.getPlugin(), new Runnable() {
            public void run() {
                mapsTelechargeables.clear();
                // Liste des maps tlchargeables
                if (json.get("data").isJsonObject()) {
                    JsonElement o = json.get("data").getAsJsonObject().get("maps");
                    if (o != null && o.isJsonArray()) {
                        JsonArray liste = o.getAsJsonArray();
                        for (JsonElement m : liste) {
                            JsonObject map = m.getAsJsonObject();
                            if (map.get("verConversion").getAsInt() <= CreativeParkour.getServVersion()) // We only want compatible maps
                                mapsTelechargeables.add(new CPMap(map.get("id").getAsString(),
                                        map.get("createur").getAsString(), map.get("nom").getAsString(),
                                        map.get("difficulte").getAsFloat(), map.get("qualite").getAsFloat(),
                                        map.get("versionMin").getAsInt(), map.get("verConversion").getAsInt()));
                        }

                        // Mise  jour des inventaires de slection de maps des joueurs qui l'ont ouvert
                        if (!mapsTelechargeables.isEmpty()) {
                            Bukkit.getScheduler().scheduleSyncDelayedTask(CreativeParkour.getPlugin(),
                                    new Runnable() {
                                        public void run() {
                                            for (Joueur j : joueurs) {
                                                if (j.invSelection != null && j.getPlayer()
                                                        .hasPermission("creativeparkour.download"))
                                                    j.invSelection.mettreAJourTelechargeables();
                                            }
                                        }
                                    });
                        }
                    }

                    // Liste des maps partages par le serveur, pour la suite...
                    o = json.get("data").getAsJsonObject().get("mapsPartagees");
                    List<String> mapsPartagees = new ArrayList<String>();
                    if (o != null && o.isJsonArray()) {
                        Type listType = new TypeToken<List<String>>() {
                        }.getType();
                        mapsPartagees = new Gson().fromJson(o, listType);
                    }

                    // Mise  jour des votes, et remplissage d'une liste pour envoyer les votes locaux
                    StringBuffer notesAEnvoyer = new StringBuffer();
                    o = json.get("data").getAsJsonObject().get("notes");
                    if (o != null && o.isJsonArray()) {
                        JsonArray liste = o.getAsJsonArray();
                        for (JsonElement e : liste) {
                            JsonObject obj = e.getAsJsonObject();
                            CPMap m = getMap(UUID.fromString(obj.get("uuidMap").getAsString()));
                            if (m != null && (m.getState() == CPMapState.DOWNLOADED
                                    || mapsPartagees.contains(m.getUUID().toString()))) {
                                m.setDifficulty(obj.get("d").getAsFloat());
                                m.setQuality(obj.get("q").getAsFloat());
                                m.sauvegarder();

                                // Votes  envoyer
                                for (Entry<String, Vote> entry : m.getVotes().entrySet()) {
                                    if (entry.getValue().getDifficulty() > 0
                                            || entry.getValue().getQuality() > 0)
                                        notesAEnvoyer.append(m.getUUID().toString()).append('_')
                                                .append(entry.getKey()).append(':')
                                                .append(entry.getValue().toConfigString()).append(";");
                                }
                            }
                        }
                    }
                    if (notesAEnvoyer.length() > 0)
                        notesAEnvoyer.deleteCharAt(notesAEnvoyer.length() - 1);

                    // Mise  jour des noms des joueurs
                    o = json.get("data").getAsJsonObject().get("nomsChanges");
                    if (o != null && o.isJsonArray()) {
                        JsonArray liste = o.getAsJsonArray();
                        for (JsonElement e : liste) {
                            JsonObject obj = e.getAsJsonObject();
                            String uuid = obj.get("uuid").getAsString();
                            String nom = obj.get("nom").getAsString();
                            String nom2 = Bukkit.getOfflinePlayer(UUID.fromString(uuid)).getName();
                            if (nom2 == null || nom2.isEmpty()) // Il ne faut pas mettre  jour les joueurs qui sont sur ce serveur
                            {
                                NameManager.enregistrerNomJoueur(uuid, nom);
                            }
                        }
                    }

                    Set<CPMap> mapsAMettreAJour = new HashSet<CPMap>();
                    // Suppression des fantmes  supprimer
                    o = json.get("data").getAsJsonObject().get("fantomesASupprimer");
                    if (o != null && o.isJsonArray()) {
                        JsonArray liste = o.getAsJsonArray();
                        for (JsonElement e : liste) {
                            String nomFantome = e.getAsString();
                            UUID uuidMap = UUID.fromString(nomFantome.split("_")[0]);
                            CPMap map = getMap(uuidMap);
                            if (map != null) {
                                File f = getFichierTemps(nomFantome);
                                if (f != null) {
                                    CPTime t = map.getTempsAvecFichier(f);
                                    if (t != null && t.etat != EtatTemps.LOCAL) {
                                        supprimerFichiersTemps(t.playerUUID, uuidMap, false);
                                        mapsAMettreAJour.add(map);
                                    }
                                }
                            }
                        }
                    }

                    // Enregistrement des fantmes envoys (en partie) par le site
                    if (Config.getConfig().getBoolean("online.download ghosts")) {
                        o = json.get("data").getAsJsonObject().get("fantomesATelecharger");
                        if (o != null && o.isJsonArray()) {
                            JsonArray liste = o.getAsJsonArray();
                            for (JsonElement e : liste) {
                                JsonObject obj = e.getAsJsonObject();
                                CPMap m = getMap(UUID.fromString(obj.get("uuidMap").getAsString()));
                                if (m != null && m.isPlayable()) {
                                    CPTime t = new CPTime(UUID.fromString(obj.get("uuidJoueur").getAsString()),
                                            m, obj.get("ticks").getAsInt());
                                    t.etat = EtatTemps.TO_DOWNLOAD;
                                    t.realMilliseconds = obj.get("millisecondes").getAsLong();
                                    t.sauvegarder(new Date(obj.get("date").getAsLong()));
                                    mapsAMettreAJour.add(m);

                                    NameManager.enregistrerNomJoueur(obj.get("uuidJoueur").getAsString(),
                                            obj.get("nomJoueur").getAsString());
                                }
                            }
                        }
                    }

                    // Mise  jour des temps dans les maps
                    Set<CPMap> mapsAvecPanneau = Panneau.getMapsAvecPanneauClassement();
                    for (CPMap m : mapsAMettreAJour) {
                        List<Joueur> joueursMap = getJoueurs(m.getUUID());
                        if (!joueursMap.isEmpty() || mapsAvecPanneau.contains(m)) {
                            m.getListeTemps(true);
                            Bukkit.getScheduler().scheduleSyncDelayedTask(CreativeParkour.getPlugin(),
                                    new Runnable() {
                                        public void run() {
                                            if (mapsAvecPanneau.contains(m))
                                                Panneau.majClassements(m);
                                            // Mise  jour des leaderboard des joueurs
                                            for (Joueur j : joueursMap) {
                                                j.calculerScoreboard();
                                                j.choixFantomesPreferes();
                                                j.majTeteFantomes();
                                            }
                                        }
                                    });
                        }
                    }

                    // Enregistrement du nombre de tricheurs
                    o = json.get("data").getAsJsonObject().get("nbTricheurs");
                    if (o != null) {
                        nbTricheurs = o.getAsInt();

                        // Enregistrement des joueurs qui peuvent recevoir des notifications de triche
                        o = json.get("data").getAsJsonObject().get("receveursNotifsTriche");
                        receveursNotifsTriche = new ArrayList<UUID>();
                        if (o != null && o.isJsonArray()) {
                            JsonArray liste = o.getAsJsonArray();
                            for (JsonElement e : liste) {
                                receveursNotifsTriche.add(UUID.fromString(e.getAsString()));
                            }
                        }
                    }

                    /*
                    // Envoi des notes et des fantmes
                    Map<String, String> paramsPost = new HashMap<String, String>();
                    if (notesAEnvoyer.length() > 0)
                       paramsPost.put("notes", notesAEnvoyer.toString());
                            
                    // Traitement des fantmes  envoyer
                    Map<String, Boolean> autorisationsJoueurs = new HashMap<String, Boolean>();
                    o = json.get("data").getAsJsonObject().get("fantomesAEnvoyer");
                    if (o != null && o.isJsonArray() && Config.getConfig().getBoolean("online.upload ghosts"))
                    {
                       JsonArray liste = o.getAsJsonArray();
                       int i = 0;
                       for (JsonElement e : liste)
                       {
                          String nomFantome = e.getAsString();
                          CPMap m = getMap(CPUtils.timeFileUUIDs(nomFantome).get("map"));
                          if (m != null)
                          {
                             CPTime t = m.getTempsAvecFichier(getFichierTemps(nomFantome));
                             String uuidJoueur = t.playerUUID.toString();
                             if (!autorisationsJoueurs.containsKey(uuidJoueur))
                      autorisationsJoueurs.put(uuidJoueur, Config.getConfJoueur(uuidJoueur).getBoolean(PlayerSetting.ENVOYER_FANTOMES.path()));
                             if (autorisationsJoueurs.get(uuidJoueur)) // Si le joueur a autoris l'envoi de fantmes
                      paramsPost.put("fantome-" + i, t.getJson().toString());
                             i++;
                          }
                       }
                    }
                            
                    if (paramsPost.size() > 0)
                    {
                       try {
                          CPRequest.effectuerRequete("data.php", paramsPost, null, null, null);
                       } catch (SecurityException e) {
                          CreativeParkour.erreur("DATA", e, true);
                       }
                    }
                    */

                    vidangeMemoire();
                }

                if (sender != null)
                    sender.sendMessage(
                            Config.prefix() + ChatColor.GREEN + Langues.getMessage("commands.sync done"));
            }
        });
    }
}

From source file:org.talend.designer.runprocess.java.JavaProcessor.java

protected String getNeededModulesJarStr() {
    final String classPathSeparator = extractClassPathSeparator();
    final String libPrefixPath = getRootWorkingDir(true);

    Set<ModuleNeeded> neededModules = getNeededModules();
    JavaProcessorUtilities.checkJavaProjectLib(neededModules);

    StringBuffer libPath = new StringBuffer();
    if (isExportConfig() || isRunAsExport()) {
        boolean hasLibPrefix = libPrefixPath.length() > 0;
        for (ModuleNeeded neededModule : neededModules) {
            if (hasLibPrefix) {
                libPath.append(libPrefixPath);
            }//from   w  w w.j  a v a 2  s  .co  m
            libPath.append(getBaseLibPath());
            libPath.append(JavaUtils.PATH_SEPARATOR);
            libPath.append(neededModule.getModuleName());
            libPath.append(classPathSeparator);
        }
    } else {
        Set<String> neededLibraries = new HashSet<String>();
        for (ModuleNeeded neededModule : neededModules) {
            neededLibraries.add(neededModule.getModuleName());
        }

        final File libDir = JavaProcessorUtilities.getJavaProjectLibFolder();
        if (libDir == null) {
            return ""; //$NON-NLS-1$
        }
        File[] jarFiles = libDir.listFiles(FilesUtils.getAcceptJARFilesFilter());

        if (jarFiles != null && jarFiles.length > 0) {
            for (File jarFile : jarFiles) {
                if (jarFile.isFile() && neededLibraries.contains(jarFile.getName())) {
                    String singleLibPath = new Path(jarFile.getAbsolutePath()).toPortableString();
                    libPath.append(singleLibPath).append(classPathSeparator);
                }
            }
        }
    }

    final int lastSep = libPath.length() - 1;
    if (libPath.length() != 0 && classPathSeparator.equals(String.valueOf(libPath.charAt(lastSep)))) {
        libPath.deleteCharAt(lastSep);
    }
    return libPath.toString();
}

From source file:edu.mit.isda.permitws.permit.java

/**
 *
 * @param UserName/*  w w  w  . ja va2s .  c o  m*/
 * @return
 * @throws edu.mit.isda.permitws.permitException
 */
@SuppressWarnings("unchecked")
public String getSelectionList(String UserName) throws permitException {
    Collection sl = null;
    Iterator iter;
    String Message;
    String ApplicationID = "";
    StringBuffer json = new StringBuffer("\r\n{\"selectionList\": [");
    String value = "";

    AuthenticateRemoteClient AuthenticateClient = new AuthenticateRemoteClient();
    utils u = new utils();

    try {
        UserName = u.validateUser(UserName);
        if (UserName == null) {
            Message = "invalid user name";
            throw new Exception(Message);
        }
        if (UserName.length() == 0) {
            Message = "user name not specified";
            throw new Exception(Message);
        }

        ApplicationID = AuthenticateClient.authenticateClient("permitws");
        GeneralSelectionManager instance = GeneralSelectionFactory.getManager();
        sl = instance.getSelectionList(UserName);
        if (null == sl || sl.isEmpty()) {
            System.out.println(" Empty Selection Set");
        }
        iter = sl.iterator();

        while (iter.hasNext()) {
            SelectionList s = (SelectionList) iter.next();

            json.append("\r\n{\"id\":\"" + s.getId().toString().trim().replace("'", "&apos;") + "\",");
            json.append("\"selectionName\":\"" + s.getSelectionName().trim().replace("'", "&apos;") + "\",");
            json.append("\"flag\":\"" + s.getFlag().trim().replace("'", "&apos;") + "\"},");
        }
        int lastCharIndex = json.length();
        json.deleteCharAt(lastCharIndex - 1);
        json.append("\r\n]}");
    } catch (Exception e) {
        Message = "permitws Web Service: " + e.getMessage();
        e.printStackTrace();
        log.error(Message);
        System.out.print("ERROR: " + e.getMessage());
        throw new permitException(e);
    }
    return (json.toString());
}

From source file:cx.fbn.nevernote.gui.BrowserWindow.java

private String removeTags(String text) {
    StringBuffer buffer = new StringBuffer(text);
    boolean inTag = false;
    int bodyPosition = text.indexOf("<body");
    for (int i = buffer.length() - 1; i >= 0; i--) {
        if (buffer.charAt(i) == '>')
            inTag = true;//from ww  w . j a  v  a2s .co  m
        if (buffer.charAt(i) == '<')
            inTag = false;
        if (inTag || buffer.charAt(i) == '<' || i < bodyPosition)
            buffer.deleteCharAt(i);
    }

    return buffer.toString();
}

From source file:cn.jsprun.struts.action.BasicSettingsAction.java

@SuppressWarnings("unchecked")
public ActionForward secqaa(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/*from ww w .j  ava 2  s . co m*/
    try {
        if (submitCheck(request, "settingsubmit")) {
            String variables[] = { "status", "minposts" };
            Map<String, String> oldSettings = ForumInit.settings;
            Map<String, String> settings = new HashMap<String, String>();
            Map<String, Object> hm = new HashMap<String, Object>();
            for (String variable : variables) {
                if ("status".equals(variable)) {
                    int sum = 0;
                    for (int j = 0; j < 3; j++) {
                        String par = request.getParameter(variable + j);
                        if (par != null)
                            sum = sum + Integer.parseInt(par);
                    }
                    hm.put(variable, sum);
                } else {
                    hm.put(variable, request.getParameter(variable));
                }
            }
            this.putValue("secqaa", dataParse.combinationChar(hm), oldSettings, settings);
            this.updateSettings(settings, oldSettings);
            String[] delete = request.getParameterValues("delete");
            if (delete != null) {
                dataBaseService.runQuery(
                        "DELETE FROM jrun_itempool WHERE id IN (" + Common.implodeids(delete) + ")", true);
            }
            String[] ids = request.getParameterValues("ids");
            if (ids != null) {
                for (String id : ids) {
                    String question = request.getParameter("question[" + id + "]").trim();
                    String answer = Common.htmlspecialchars(request.getParameter("answer[" + id + "]").trim());
                    if (!"".equals(question) && !"".equals(answer)) {
                        dataBaseService.runQuery("UPDATE jrun_itempool SET question='"
                                + Common.addslashes(question) + "', answer='"
                                + Common.addslashes((answer.length() > 50 ? answer.substring(0, 50) : answer))
                                + "' WHERE id='" + id + "'", true);
                    }
                }
            }
            String[] newquestions = request.getParameterValues("newquestions");
            String[] newanswers = request.getParameterValues("newanswers");
            if (newquestions != null && newanswers != null) {
                StringBuffer sql = new StringBuffer();
                sql.append("INSERT INTO   jrun_itempool (type,question, answer) VALUES ");
                boolean sign = false;
                int length = newquestions.length - 1;
                for (int i = 0; i < length; i++) {
                    if (!"".equals(newquestions[i]) && !"".equals(newanswers[i])) {
                        sql.append("('0','" + Common.addslashes(newquestions[i]) + "', '" + Common.addslashes(
                                (newanswers[i].length() > 50 ? newanswers[i].substring(0, 50) : newanswers[i]))
                                + "'),");
                        sign = true;
                    }
                }
                if (sign) {
                    sql.deleteCharAt(sql.length() - 1);
                    dataBaseService.runQuery(sql.toString(), true);
                }
            }
            Cache.updateCache("secqaa");
            return this.getForward(mapping, request);
        }
    } catch (Exception e) {
        request.setAttribute("message", e.getMessage());
        return mapping.findForward("message");
    }
    Map<String, String> settings = ForumInit.settings;
    Map<String, Object> secqaa = dataParse.characterParse(settings.get("secqaa"), false);
    Common.setChecked(request, "status", 3, (Integer) secqaa.get("status"));
    request.setAttribute("secqaa", secqaa);
    List<Map<String, String>> count = dataBaseService.executeQuery("SELECT COUNT(*) count FROM jrun_itempool");
    int secqaanums = Integer.valueOf(count.get(0).get("count"));
    int perpage = 10;
    int page = Math.max(Common.intval(request.getParameter("page")), 1);
    Map<String, Integer> multiInfo = Common.getMultiInfo(secqaanums, perpage, page);
    page = multiInfo.get("curpage");
    int start_limit = multiInfo.get("start_limit");
    Map<String, Object> multi = Common.multi(secqaanums, perpage, page, "admincp.jsp?action=settings&do=secqaa",
            0, 10, true, false, null);
    request.setAttribute("multi", multi);
    List<Map<String, String>> itempools = dataBaseService
            .executeQuery("SELECT * FROM jrun_itempool LIMIT " + start_limit + "," + perpage);
    request.setAttribute("itempools", itempools);
    return mapping.findForward("setting_secqaa");
}

From source file:edu.mit.isda.permitws.permit.java

/**
 *
 * @param proxyUserName/*  ww w. j av a 2  s  .  c  o  m*/
 * @param name
 * @param search
 * @param sort
 * @param filter1
 * @param filter2
 * @param filter3
 * @return
 * @throws edu.mit.isda.permitws.permitException
 */
@SuppressWarnings("unchecked")
public String listPersonJSON(String proxyUserName, String name, String search, String sort, String filter1,
        String filter2, String filter3) throws permitException {
    Collection people = null;
    Iterator iter;
    String Message;
    String ApplicationID = "";
    StringBuffer xml = new StringBuffer("\r\n{\"people\": [");

    AuthenticateRemoteClient AuthenticateClient = new AuthenticateRemoteClient();
    utils u = new utils();

    try {
        ApplicationID = AuthenticateClient.authenticateClient("permitws");

        if (proxyUserName == null) {
            Message = "Invalid certificate";
            throw new Exception(Message);
        }

        if (proxyUserName.length() == 0) {
            Message = "No certificate user detected";
            throw new Exception(Message);
        }

        GeneralSelectionManager instance = GeneralSelectionFactory.getManager();
        people = instance.listPersonRaw(name, search, sort, filter1, filter2, filter3);

        if (null == people) {
            xml = new StringBuffer(EMPTY_PERSONLIST_MESSAGE);
        } else if (people.isEmpty()) {
            xml = new StringBuffer(EMPTY_PERSONLIST_MESSAGE);
        }

        else {
            iter = people.iterator();

            while (iter.hasNext()) {
                PersonRaw p = (PersonRaw) iter.next();
                xml.append("\r\n{\"firstName\":\"" + p.getFirstName().trim() + "\",");
                xml.append("\"lastName\":\"" + p.getLastName().trim() + "\",");
                xml.append("\"email\":\"" + p.getEmailAddress().trim() + "\",");
                xml.append("\"mitId\":\"" + p.getMitId().trim() + "\",");
                xml.append("\"type\":\"" + p.getMitId().trim() + "\",");
                xml.append("\"kerberosName\":\"" + p.getKerberosName().trim() + "\",");
            }
            int lastCharIndex = xml.length();
            xml.deleteCharAt(lastCharIndex - 1);
            xml.append("\r\n]}");
        }

    } catch (Exception e) {
        Message = "permitws Web Service: " + e.getMessage();
        log.error(Message);
        e.printStackTrace();
        throw new permitException(e);
    }
    //System.out.println(xml.toString());
    try {
        return (URLEncoder.encode(xml.toString(), "UTF-8"));
    } catch (Exception e) {
        throw new permitException(e.getLocalizedMessage());
    }
}

From source file:Leitura.Jxr.java

public ArrayList<DadosTeste> leTxt(String classe, String path, FileInputStream reader) throws IOException {
    StringBuffer sbaux = new StringBuffer();
    char corrente;
    int bloco = 0;
    char[] aux;/* www.  j a  va 2  s .co m*/
    boolean met = false;
    boolean obj = false;
    boolean cod = false;
    boolean ponto = false;
    boolean bClasse = false;
    boolean achei = false;
    boolean statment = false;
    boolean clas = false;
    ArrayList<String> object = new ArrayList<String>();
    ArrayList<String> mChamado = new ArrayList<String>();
    ArrayList<DadosTeste> dados = new ArrayList<>();
    String metodoTeste = null;
    String classeTeste = null;
    String classeObj = null;
    String objeto = null;
    String auxiliar = null;
    DadosTeste dadosTeste = null;

    // System.out.println(reader.available()+"->"+classe);
    while (reader.available() > 0) {
        corrente = (char) reader.read();
        if ((corrente == '\t') || (corrente == '\r')) {
            continue;
        }

        sbaux.append(corrente);
        // verifica abertura de blocos

        if (corrente != '=') {
            auxiliar = sbaux.toString(); // guarda o nome do objeto
        }

        if ((corrente == ' ') && (auxiliar.equals("do") || auxiliar.equals("if") || auxiliar.equals("else")
                || auxiliar.equals("for") || auxiliar.equals("while") || auxiliar.equals("switch")
                || auxiliar.equals("try") || auxiliar.equals("catch"))) {
            statment = true;

        }

        if ((corrente == '{') && (statment == false)) {
            bloco++;
        }

        if ((corrente == '}') && (statment == false)) {
            bloco--;
        } else if ((corrente == '}') && (statment == true)) {
            statment = false;
        }

        //ler os caracteres at formar uma palavra reservada do java
        if ((sbaux.toString().equals("public")) || (sbaux.toString().equals("protected"))
                || (sbaux.toString().equals("private")) || (sbaux.toString().equals("static"))
                || (sbaux.toString().equals("final")) || (sbaux.toString().equals("native"))
                || (sbaux.toString().equals("synchronized")) || (sbaux.toString().equals("abstract"))
                || (sbaux.toString().equals("threadsafe")) || (sbaux.toString().equals("transient"))) {
            met = true; // encontrei palavra reservada
            sbaux.delete(0, sbaux.length());
        }

        if (sbaux.toString().equals("class ") && classeTeste == null) {
            met = false;
            clas = true;
            sbaux.delete(0, sbaux.length());
        }
        if (clas == true && !auxiliar.toString().equals("class ") && corrente == ' ') {
            classeTeste = sbaux.toString();
            clas = false;
            sbaux.delete(0, sbaux.length());
        }

        //verificar se a palavra reservada eh de um mtodo
        if (met == true && corrente == '.') {
            met = false;

            sbaux.delete(0, sbaux.length());
        }
        if (auxiliar.equals("new")) {
            met = false;
        }
        if (met == true && ((corrente == ')') || (corrente == '='))) {
            met = false;
        }
        if ((met == true) && ((corrente == ' ') || (corrente == '('))) {

            aux = sbaux.toString().toCharArray(); // verifica se eh um metoo ou declarao de varivel
            for (int i = 0; i < aux.length; i++) {
                if (aux[i] == '(') {
                    sbaux.deleteCharAt(i);
                    metodoTeste = sbaux.toString(); //encontrei metodo do teste
                    sbaux.delete(0, sbaux.length());
                    met = false;
                    //System.out.println("metodo ->" + metodoTeste);
                    break;
                }
            }
        }
        if (sbaux.toString().equals(classe + " ")) {
            bClasse = true;
        }

        if ((corrente == '{') && (bClasse == true)) {
            bClasse = false;
            obj = false;
        }

        if ((bClasse == true) && (corrente == ' ')) {
            classeObj = classe;
            //System.out.println(classeObj);
            bClasse = false;
            obj = true; // encontrou um objeto
            sbaux.delete(0, sbaux.length());
        }
        if ((corrente == '(') || (corrente == '.') || (corrente == ')')) {
            obj = false; // torna obj falso para no pegar a instanciao do objeto ex: Calculadora calc = new Calculadora()
        }

        if ((obj == true) && ((corrente == '=') || (corrente == ';'))) {
            objeto = auxiliar.replace(';', ' ').trim();
            object.add(objeto);
            obj = false;
            //System.out.println(object);
        }

        // verifica os mtodos do cdigo
        for (int i = 0; i < object.size(); i++) {
            if ((sbaux.toString()).equals(object.get(i))) {
                cod = true; // verifica se encontrou um objeto
            }
        }

        if ((corrente == '.') && (cod == true)) {
            ponto = true; // verifica se o objeto vai chamar um metodo
            sbaux.delete(0, sbaux.length());
        }
        if ((cod == true) && (ponto == true)) {
            if ((corrente == '(') || (corrente == ' ')) {
                if (sbaux.length() != 0) {
                    sbaux.deleteCharAt(sbaux.length() - 1);
                    for (int i = 0; i < mChamado.size(); i++) {
                        if (mChamado.get(i).equals(sbaux.toString()))
                            achei = true;
                    }
                    if (achei != true) {
                        mChamado.add(sbaux.toString()); // metodo do codigo encontrado
                        achei = false;
                    }
                }
                cod = false;
                ponto = false;

            }
        }

        if (StringUtils.isNotBlank(metodoTeste) && StringUtils.isNotBlank(classeObj) && !object.isEmpty()
                && !mChamado.isEmpty() && (bloco % 2 != 0)) {
            // System.out.println("ClasseOBj: "+classeObj+" Objeto: "+object+" MChamado: "+mChamado+" Metodo Teste:"+metodoTeste+" ClasseTeste: "+classeTeste);
            dadosTeste = new DadosTeste(classeObj, object, mChamado, metodoTeste, classeTeste.trim());
            //infJxr.put(metodoTeste + "_" + classeObj, dadosTeste);
            dados.add(dadosTeste);
            classeObj = null;
            object = new ArrayList<>();
            mChamado = new ArrayList<>();
            metodoTeste = null;
            objeto = null;

            met = false;
            obj = false;
            cod = false;
            ponto = false;
            bClasse = false;
            achei = false;
        }
        if ((corrente == '\n') || (corrente == ' ') || (corrente == ',') || auxiliar.equals("")
                || (corrente == '(')) {
            sbaux.delete(0, sbaux.length());
        }
    }

    clas = false;
    classeTeste = null;
    return dados;
}