Example usage for java.util StringTokenizer countTokens

List of usage examples for java.util StringTokenizer countTokens

Introduction

In this page you can find the example usage for java.util StringTokenizer countTokens.

Prototype

public int countTokens() 

Source Link

Document

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

Usage

From source file:org.apache.atlas.security.InMemoryJAASConfiguration.java

private void initialize(Properties properties) {
    LOG.debug("==> InMemoryJAASConfiguration.initialize()");

    int prefixLen = JAAS_CONFIG_PREFIX_PARAM.length();

    Map<String, SortedSet<Integer>> jaasClients = new HashMap<>();
    for (String key : properties.stringPropertyNames()) {
        if (key.startsWith(JAAS_CONFIG_PREFIX_PARAM)) {
            String jaasKey = key.substring(prefixLen);
            StringTokenizer tokenizer = new StringTokenizer(jaasKey, ".");
            int tokenCount = tokenizer.countTokens();
            if (tokenCount > 0) {
                String clientId = tokenizer.nextToken();
                SortedSet<Integer> indexList = jaasClients.get(clientId);
                if (indexList == null) {
                    indexList = new TreeSet<>();
                    jaasClients.put(clientId, indexList);
                }//from   w w  w .  j  av a2 s  .  c o m
                String indexStr = tokenizer.nextToken();

                int indexId = isNumeric(indexStr) ? Integer.parseInt(indexStr) : -1;

                Integer clientIdIndex = Integer.valueOf(indexId);

                if (!indexList.contains(clientIdIndex)) {
                    indexList.add(clientIdIndex);
                }

            }
        }
    }
    for (String jaasClient : jaasClients.keySet()) {

        for (Integer index : jaasClients.get(jaasClient)) {

            String keyPrefix = JAAS_CONFIG_PREFIX_PARAM + jaasClient + ".";

            if (index > -1) {
                keyPrefix = keyPrefix + String.valueOf(index) + ".";
            }

            String keyParam = keyPrefix + JAAS_CONFIG_LOGIN_MODULE_NAME_PARAM;
            String loginModuleName = properties.getProperty(keyParam);

            if (loginModuleName == null) {
                LOG.error(
                        "Unable to add JAAS configuration for client [{}] as it is missing param [{}]. Skipping JAAS config for [{}]",
                        jaasClient, keyParam, jaasClient);
                continue;
            } else {
                loginModuleName = loginModuleName.trim();
            }

            keyParam = keyPrefix + JAAS_CONFIG_LOGIN_MODULE_CONTROL_FLAG_PARAM;
            String controlFlag = properties.getProperty(keyParam);

            AppConfigurationEntry.LoginModuleControlFlag loginControlFlag = null;
            if (controlFlag != null) {
                controlFlag = controlFlag.trim().toLowerCase();
                switch (controlFlag) {
                case "optional":
                    loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL;
                    break;
                case "requisite":
                    loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUISITE;
                    break;
                case "sufficient":
                    loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT;
                    break;
                case "required":
                    loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED;
                    break;
                default:
                    String validValues = "optional|requisite|sufficient|required";
                    LOG.warn(
                            "Unknown JAAS configuration value for ({}) = [{}], valid value are [{}] using the default value, REQUIRED",
                            keyParam, controlFlag, validValues);
                    loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED;
                    break;
                }
            } else {
                LOG.warn("Unable to find JAAS configuration ({}); using the default value, REQUIRED", keyParam);
                loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED;
            }

            Map<String, String> options = new HashMap<>();
            String optionPrefix = keyPrefix + JAAS_CONFIG_LOGIN_OPTIONS_PREFIX + ".";
            int optionPrefixLen = optionPrefix.length();
            for (String key : properties.stringPropertyNames()) {
                if (key.startsWith(optionPrefix)) {
                    String optionKey = key.substring(optionPrefixLen);
                    String optionVal = properties.getProperty(key);
                    if (optionVal != null) {
                        optionVal = optionVal.trim();

                        try {
                            if (optionKey.equalsIgnoreCase(JAAS_PRINCIPAL_PROP)) {
                                optionVal = SecurityUtil.getServerPrincipal(optionVal, (String) null);
                            }
                        } catch (IOException e) {
                            LOG.warn("Failed to build serverPrincipal. Using provided value:[{}]", optionVal);
                        }
                    }
                    options.put(optionKey, optionVal);
                }
            }

            AppConfigurationEntry entry = new AppConfigurationEntry(loginModuleName, loginControlFlag, options);

            if (LOG.isDebugEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("Adding client: [").append(jaasClient).append("{").append(index).append("}]\n");
                sb.append("\tloginModule: [").append(loginModuleName).append("]\n");
                sb.append("\tcontrolFlag: [").append(loginControlFlag).append("]\n");
                for (String key : options.keySet()) {
                    String val = options.get(key);
                    sb.append("\tOptions:  [").append(key).append("] => [").append(val).append("]\n");
                }
                LOG.debug(sb.toString());
            }

            List<AppConfigurationEntry> retList = applicationConfigEntryMap.get(jaasClient);
            if (retList == null) {
                retList = new ArrayList<>();
                applicationConfigEntryMap.put(jaasClient, retList);
            }

            retList.add(entry);
        }
    }

    LOG.debug("<== InMemoryJAASConfiguration.initialize({})", applicationConfigEntryMap);
}

From source file:de.tudarmstadt.ukp.clarin.webanno.automation.util.AutomationUtil.java

public static void generateTrainDocument(MiraTemplate aTemplate, RepositoryService aRepository,
        AnnotationService aAnnotationService, AutomationService aAutomationService, UserDao aUserDao,
        boolean aBase) throws IOException, UIMAException, ClassNotFoundException, AutomationException {
    File miraDir = aAutomationService.getMiraDir(aTemplate.getTrainFeature());
    if (!miraDir.exists()) {
        FileUtils.forceMkdir(miraDir);/*ww w.ja  va  2 s  . c o  m*/
    }

    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    User user = aUserDao.get(username);
    AnnotationFeature feature = aTemplate.getTrainFeature();
    boolean documentChanged = false;
    // A. training document for other train layers were changed
    for (AnnotationFeature otherrFeature : aTemplate.getOtherFeatures()) {
        for (SourceDocument document : aRepository
                .listSourceDocuments(aTemplate.getTrainFeature().getProject())) {
            if (!document.isProcessed() && document.getFeature() != null
                    && document.getFeature().equals(otherrFeature)) {
                documentChanged = true;
                break;
            }
        }
    }
    // B. Training document for the main training layer were changed
    for (SourceDocument document : aRepository.listSourceDocuments(feature.getProject())) {
        if (!document.isProcessed()
                && (document.getFeature() != null && document.getFeature().equals(feature))) {
            documentChanged = true;
            break;
        }
    }
    // C. New Curation document arrives
    for (SourceDocument document : aRepository.listSourceDocuments(feature.getProject())) {
        if (!document.isProcessed() && document.getState().equals(SourceDocumentState.CURATION_FINISHED)) {
            documentChanged = true;
            break;
        }
    }
    // D. tab-sep training documents
    for (SourceDocument document : aAutomationService
            .listTabSepDocuments(aTemplate.getTrainFeature().getProject())) {
        if (!document.isProcessed() && document.getFeature() != null && document.getFeature().equals(feature)) {
            documentChanged = true;
            break;
        }
    }
    if (!documentChanged) {
        return;
    }
    File trainFile;
    if (aBase) {
        trainFile = new File(miraDir, feature.getLayer().getId() + "-" + feature.getId() + ".train.ft");
    } else {
        trainFile = new File(miraDir, feature.getLayer().getId() + "-" + feature.getId() + ".train.base");
    }

    AutomationStatus status = aAutomationService.getAutomationStatus(aTemplate);

    BufferedWriter trainOut = new BufferedWriter(new FileWriter(trainFile));
    AutomationTypeAdapter adapter = (AutomationTypeAdapter) TypeUtil.getAdapter(aAnnotationService,
            feature.getLayer());
    // Training documents (Curated or webanno-compatible imported ones - read using UIMA)
    for (SourceDocument sourceDocument : aRepository.listSourceDocuments(feature.getProject())) {
        if ((sourceDocument.isTrainingDocument() && sourceDocument.getFeature() != null
                && sourceDocument.getFeature().equals(feature))) {
            JCas jCas = aRepository.readAnnotationCas(sourceDocument, user);
            for (Sentence sentence : select(jCas, Sentence.class)) {
                if (aBase) {// base training document
                    trainOut.append(getMiraLine(sentence, null, adapter).toString() + "\n");
                } else {// training document with other features
                    trainOut.append(getMiraLine(sentence, feature, adapter).toString() + "\n");
                }
            }
            sourceDocument.setProcessed(!aBase);
            if (!aBase) {
                status.setTrainDocs(status.getTrainDocs() - 1);
            }
        } else if (sourceDocument.getState().equals(SourceDocumentState.CURATION_FINISHED)) {
            JCas jCas = aRepository.readCurationCas(sourceDocument);
            for (Sentence sentence : select(jCas, Sentence.class)) {
                if (aBase) {// base training document
                    trainOut.append(getMiraLine(sentence, null, adapter).toString() + "\n");
                } else {// training document with other features
                    trainOut.append(getMiraLine(sentence, feature, adapter).toString() + "\n");
                }
            }
            sourceDocument.setProcessed(!aBase);
            if (!aBase) {
                status.setTrainDocs(status.getTrainDocs() - 1);
            }
        }
    }
    // Tab-sep documents to be used as a target layer train document
    for (SourceDocument document : aAutomationService.listTabSepDocuments(feature.getProject())) {
        if (document.getFormat().equals(WebAnnoConst.TAB_SEP) && document.getFeature() != null
                && document.getFeature().equals(feature)) {
            File tabSepFile = new File(aRepository.getDocumentFolder(document), document.getName());
            LineIterator it = IOUtils.lineIterator(new FileReader(tabSepFile));
            while (it.hasNext()) {
                String line = it.next();
                if (line.trim().equals("")) {
                    trainOut.append("\n");
                } else {
                    StringTokenizer st = new StringTokenizer(line, "\t");
                    if (st.countTokens() != 2) {
                        trainOut.close();
                        throw new AutomationException("This is not a valid TAB-SEP document");
                    }
                    if (aBase) {
                        trainOut.append(getMiraLineForTabSep(st.nextToken(), ""));
                    } else {
                        trainOut.append(getMiraLineForTabSep(st.nextToken(), st.nextToken()));
                    }
                }
            }
        }
    }
    trainOut.close();
}

From source file:carstore.CarBean.java

/**
 * Tokenizes the passed in String which is a comma separated string of
 * option values that serve as keys into the main resources file.
 * For example, optionStr could be "Disc,Drum", which corresponds to
 * brake options available for the chosen car. This String is tokenized
 * and used as key into the main resource file to get the localized option
 * values and stored in the passed in ArrayList.
 */// w ww .ja  va  2  s  . c o m
public ArrayList parseStringIntoArrayList(FacesContext context, UIComponent component, String value,
        String valueType, Converter converter) {
    ArrayList optionsList = null;
    int i = 0;
    Object optionValue = null;
    String optionKey = null, optionLabel = null;
    Map nonLocalizedOptionValues = null;

    if (value == null) {
        return null;
    }
    StringTokenizer st = new StringTokenizer(value, ",");
    optionsList = new ArrayList((st.countTokens()) + 1);
    while (st.hasMoreTokens()) {
        optionKey = st.nextToken();
        try {
            optionLabel = resources.getString(optionKey);
        } catch (MissingResourceException e) {
            // if we can't find a hit, the key is the label
            optionLabel = optionKey;
        }

        if (null != converter) {
            // PENDING deal with the converter case
        } else {
            optionsList.add(new SelectItem(optionKey, optionLabel));
        }
    }
    return optionsList;
}

From source file:de.tor.tribes.ui.views.DSWorkbenchChurchFrame.java

private void bbCopySelection() {
    try {/* w  w w.  j av  a2 s. c o  m*/
        int[] rows = jChurchTable.getSelectedRows();
        if (rows.length == 0) {
            return;
        }

        boolean extended = (JOptionPaneHelper.showQuestionConfirmBox(this,
                "Erweiterte BB-Codes verwenden (nur fr Forum und Notizen geeignet)?", "Erweiterter BB-Code",
                "Nein", "Ja") == JOptionPane.YES_OPTION);

        StringBuilder buffer = new StringBuilder();
        if (extended) {
            buffer.append("[u][size=12]Kirchendrfer[/size][/u]\n\n");
        } else {
            buffer.append("[u]Kirchendrfer[/u]\n\n");
        }

        buffer.append("[table]\n");
        buffer.append("[**]Spieler[||]Dorf[||]Radius[/**]\n");

        for (int row1 : rows) {
            int row = jChurchTable.convertRowIndexToModel(row1);
            int tribeCol = jChurchTable.convertColumnIndexToModel(0);
            int villageCol = jChurchTable.convertColumnIndexToModel(1);
            int rangeCol = jChurchTable.convertColumnIndexToModel(2);
            buffer.append("[*]").append(((Tribe) jChurchTable.getModel().getValueAt(row, tribeCol)).toBBCode())
                    .append("[|]")
                    .append(((Village) jChurchTable.getModel().getValueAt(row, villageCol)).toBBCode())
                    .append("[|]").append(jChurchTable.getModel().getValueAt(row, rangeCol));
        }

        buffer.append("[/table]");

        if (extended) {
            buffer.append("\n[size=8]Erstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "[/size]\n");
        } else {
            buffer.append("\nErstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "\n");
        }

        String b = buffer.toString();
        StringTokenizer t = new StringTokenizer(b, "[");
        int cnt = t.countTokens();
        if (cnt > 1000) {
            if (JOptionPaneHelper.showQuestionConfirmBox(this,
                    "Die ausgewhlten Kirchen bentigen mehr als 1000 BB-Codes\n"
                            + "und knnen daher im Spiel (Forum/IGM/Notizen) nicht auf einmal dargestellt werden.\n"
                            + "Trotzdem exportieren?",
                    "Zu viele BB-Codes", "Nein", "Ja") == JOptionPane.NO_OPTION) {
                return;
            }
        }

        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(b), null);
        String result = "Daten in Zwischenablage kopiert.";
        showSuccess(result);
    } catch (Exception e) {
        logger.error("Failed to copy data to clipboard", e);
        String result = "Fehler beim Kopieren in die Zwischenablage.";
        showError(result);
    }
}

From source file:com.silverpeas.attachment.servlets.DragAndDrop.java

/**
 * Method declaration//  w w w. j  a  v  a  2 s.  c  o m
 * @param req
 * @param res
 * @throws IOException
 * @throws ServletException
 * @see
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    if (!FileUploadUtil.isRequestMultipart(req)) {
        res.getOutputStream().println("SUCCESS");
        return;
    }
    ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false);
    try {
        req.setCharacterEncoding("UTF-8");
        String componentId = req.getParameter("ComponentId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "componentId = " + componentId);
        String id = req.getParameter("PubId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id);
        String userId = req.getParameter("UserId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "userId = " + userId);
        String context = req.getParameter("Context");
        boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt"));

        List<FileItem> items = FileUploadUtil.parseRequest(req);
        for (FileItem item : items) {
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getFieldName());
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getName() + "; " + item.getString("UTF-8"));

            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName != null) {
                    String physicalName = saveFileOnDisk(item, componentId, context);
                    String mimeType = AttachmentController.getMimeType(fileName);
                    long size = item.getSize();
                    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "item size = " + size);
                    // create AttachmentDetail Object
                    AttachmentDetail attachment = new AttachmentDetail(
                            new AttachmentPK(null, "useless", componentId), physicalName, fileName, null,
                            mimeType, size, context, new Date(), new AttachmentPK(id, "useless", componentId));
                    attachment.setAuthor(userId);
                    try {
                        AttachmentController.createAttachment(attachment, bIndexIt);
                    } catch (Exception e) {
                        // storing data into DB failed, delete file just added on disk
                        deleteFileOnDisk(physicalName, componentId, context);
                        throw e;
                    }
                    // Specific case: 3d file to convert by Actify Publisher
                    if (actifyPublisherEnable) {
                        String extensions = settings.getString("Actify3dFiles");
                        StringTokenizer tokenizer = new StringTokenizer(extensions, ",");
                        // 3d native file ?
                        boolean fileForActify = false;
                        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                                "nb tokenizer =" + tokenizer.countTokens());
                        String type = FileRepositoryManager.getFileExtension(fileName);
                        while (tokenizer.hasMoreTokens() && !fileForActify) {
                            String extension = tokenizer.nextToken();
                            fileForActify = type.equalsIgnoreCase(extension);
                        }
                        if (fileForActify) {
                            String dirDestName = "a_" + componentId + "_" + id;
                            String actifyWorkingPath = settings.getString("ActifyPathSource")
                                    + File.separatorChar + dirDestName;

                            String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath;
                            if (!new File(destPath).exists()) {
                                FileRepositoryManager.createGlobalTempPath(actifyWorkingPath);
                            }
                            String normalizedFileName = FilenameUtils.normalize(fileName);
                            if (normalizedFileName == null) {
                                normalizedFileName = FilenameUtils.getName(fileName);
                            }
                            String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath
                                    + File.separatorChar + normalizedFileName;
                            FileRepositoryManager
                                    .copyFile(AttachmentController.createPath(componentId, "Images")
                                            + File.separatorChar + physicalName, destFile);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        SilverTrace.error("attachment", "DragAndDrop.doPost", "ERREUR", e);
        res.getOutputStream().println("ERROR");
        return;
    }
    res.getOutputStream().println("SUCCESS");
}

From source file:net.sf.l2j.gameserver.model.actor.instance.L2FactionInstance.java

@Override
public void onBypassFeedback(L2PcInstance player, String command) {
    player.sendPacket(ActionFailed.STATIC_PACKET);
    StringTokenizer st = new StringTokenizer(command, " ");
    String actualCommand = st.nextToken();
    String val = "";
    if (st.countTokens() >= 1) {
        val = st.nextToken();
    }//from   w w  w . j ava 2  s.com
    if (actualCommand.equalsIgnoreCase("delevel")) {
        setTarget(player);
        int lvl = player.getLevel();
        if (lvl > 40) {
            if (val.equalsIgnoreCase("1")) {
                long delexp = 0;
                delexp = player.getStat().getExp() - player.getStat().getExpForLevel(lvl - 1);
                player.getStat().addExp(-delexp);
                player.broadcastKarma();
                player.sendMessage("Delevel was Successfull.");
            } else {
                NpcHtmlMessage html = new NpcHtmlMessage(1);
                html.setFile("data/html/mods/Faction/delevel.htm");
                html.replace("%lvl%", String.valueOf(player.getLevel()));
                sendHtmlMessage(player, html);
            }
        } else {
            player.sendMessage("You have to be at least level 40 to use the delevel faction.");
        }
        return;
    } else if (actualCommand.equalsIgnoreCase("levelup")) {
        setTarget(player);
        int lvl = player.getLevel();
        if (val.equalsIgnoreCase("1")) {
            long addexp = 0;
            addexp = player.getStat().getExpForLevel(lvl + 1) - player.getStat().getExp();
            player.getStat().addExp(addexp);
            player.broadcastKarma();
            player.sendMessage("Level Up was Successfull.");
        } else {
            NpcHtmlMessage html = new NpcHtmlMessage(1);
            html.setFile("data/html/mods/Faction/levelup.htm");
            html.replace("%lvl%", String.valueOf(player.getLevel()));
            sendHtmlMessage(player, html);
        }
    } else if (actualCommand.equalsIgnoreCase("setnobless")) {
        setTarget(player);
        if (player.isNoble()) {
            player.sendMessage("You have allready nobless status.");
            player.sendPacket(ActionFailed.STATIC_PACKET);
        } else {
            player.setNoble(true);
            Connection connection = null;
            try {
                connection = L2DatabaseFactory.getInstance().getConnection();
                PreparedStatement statement = connection
                        .prepareStatement("SELECT obj_id FROM characters where char_name=?");
                statement.setString(1, player.getName());
                ResultSet rset = statement.executeQuery();
                int objId = 0;
                if (rset.next()) {
                    objId = rset.getInt(1);
                }
                rset.close();
                statement.close();
                if (objId == 0) {
                    connection.close();
                    return;
                }
                statement = connection.prepareStatement("UPDATE characters SET nobless=1 WHERE obj_id=?");
                statement.setInt(1, objId);
                statement.execute();
                statement.close();
                connection.close();
            } catch (Exception e) {
                _log.warn("Could not set Nobless status of char.");
            } finally {
                try {
                    connection.close();
                } catch (Exception e) {
                }
            }
            System.out.println("##KvN Engine## : Player " + player.getName() + " has gain noble status");
            player.sendMessage("You Gaine Nobless Status.");
        }
    } else if (actualCommand.equalsIgnoreCase("setkoof")) {
        setTarget(player);
        if (player.isKoof()) {
            player.sendMessage("You are allready a " + Config.KOOFS_NAME_TEAM + " faction.");
            player.sendPacket(ActionFailed.STATIC_PACKET);
        } else {
            if (player.isNoob()) {
                player.sendMessage("You Cant Change Faction.");
                player.sendPacket(ActionFailed.STATIC_PACKET);
            } else {
                // int getnoobs = L2World.getInstance().getAllnoobPlayers().size();
                // int getkoofs = L2World.getInstance().getAllkoofPlayers().size();
                // if (getkoofs > getnoobs)
                {
                    // player.sendMessage("It is more " + Config.KOOF_NAME_TEAM + " members online.");
                    // player.sendPacket(ActionFailed.STATIC_PACKET);
                    // } else
                    // {
                    player.setKoof(true);
                    Connection connection = null;
                    try {
                        connection = L2DatabaseFactory.getInstance().getConnection();
                        PreparedStatement statement = connection
                                .prepareStatement("SELECT obj_id FROM characters where char_name=?");
                        statement.setString(1, player.getName());
                        ResultSet rset = statement.executeQuery();
                        int objId = 0;
                        if (rset.next()) {
                            objId = rset.getInt(1);
                        }
                        rset.close();
                        statement.close();
                        if (objId == 0) {
                            connection.close();
                            return;
                        }
                        statement = connection.prepareStatement("UPDATE characters SET koof=1 WHERE obj_id=?");
                        statement.setInt(1, objId);
                        statement.execute();
                        statement.close();
                        connection.close();
                    } catch (Exception e) {
                        _log.warn("Could not set koof status of char:");
                    } finally {
                        try {
                            connection.close();
                        } catch (Exception e) {
                        }
                    }
                    System.out.println("##KvN Engine## : Player " + player.getName() + " has choose "
                            + Config.KOOFS_NAME_TEAM + " faction");
                    if (player.isKoof() == true) {
                        player.broadcastUserInfo();
                        player.sendMessage("You are fighiting now for " + Config.KOOFS_NAME_TEAM + " faction ");
                        player.getAppearance().setNameColor(Config.KOOFS_NAME_COLOR);
                        player.setTitle(Config.KOOFS_NAME_TEAM);
                        player.teleToLocation(146334, 25767, -2013);
                    }
                }
            }
        }
    } else if (actualCommand.equalsIgnoreCase("setnoob")) {
        setTarget(player);
        if (player.isNoob()) {
            player.sendMessage("You are allready a " + Config.NOOBS_NAME_TEAM + " faction.");
            player.sendPacket(ActionFailed.STATIC_PACKET);
        } else {
            if (player.isKoof()) {
                player.sendMessage("You cant change faction.");
                player.sendPacket(ActionFailed.STATIC_PACKET);
            } else {
                @SuppressWarnings("unused")
                int getnoobs = L2World.getInstance().getAllnoobPlayers().size();
                @SuppressWarnings("unused")
                int getkoofs = L2World.getInstance().getAllkoofPlayers().size();
                // if (getnoobs > getkoofs)
                {
                    // player.sendMessage("It is more " + Config.NOOB_NAME_TEAM + " members online.");
                    // player.sendPacket(ActionFailed.STATIC_PACKET);
                    // } else
                    // {
                    player.setNoob(true);
                    Connection connection = null;
                    try {
                        connection = L2DatabaseFactory.getInstance().getConnection();
                        PreparedStatement statement = connection
                                .prepareStatement("SELECT obj_id FROM characters where char_name=?");
                        statement.setString(1, player.getName());
                        ResultSet rset = statement.executeQuery();
                        int objId = 0;
                        if (rset.next()) {
                            objId = rset.getInt(1);
                        }
                        rset.close();
                        statement.close();
                        if (objId == 0) {
                            connection.close();
                            return;
                        }
                        statement = connection.prepareStatement("UPDATE characters SET noob=1 WHERE obj_id=?");
                        statement.setInt(1, objId);
                        statement.execute();
                        statement.close();
                        connection.close();
                    } catch (Exception e) {
                        _log.warn("Could not set noob status of char:");
                    } finally {
                        try {
                            connection.close();
                        } catch (Exception e) {
                        }
                    }
                    System.out.println("##KvN Engine## : player " + player.getName() + " Has choose "
                            + Config.NOOBS_NAME_TEAM + " Faction");
                    if (player.isNoob() == true) {
                        player.broadcastUserInfo();
                        player.sendMessage("You are fighiting now for " + Config.NOOBS_NAME_TEAM + " faction ");
                        player.getAppearance().setNameColor(Config.NOOBS_NAME_COLOR);
                        player.setTitle(Config.NOOBS_NAME_TEAM);
                        player.teleToLocation(59669, -42221, -2992);
                    }
                }
            }
        }
    } else {
        super.onBypassFeedback(player, command);
    }
}

From source file:com.qframework.core.ItemFactory.java

public GameonModel getFromTemplate(String strType, String strData, String strColor) {

    if (mModels.containsKey(strData)) {
        return mModels.get(strData);
    }// w ww . j  a  v a  2s . co m

    int textid = mApp.textures().mTextureDefault;
    GLColor color = null;
    if (strColor == null) {
        color = mApp.colors().white;
    } else {
        color = mApp.colors().getColor(strColor);
    }

    float[] grid = new float[3];
    grid[0] = 1;
    grid[1] = 1;
    grid[2] = 1;

    String template = null;
    StringTokenizer tok = new StringTokenizer(strData, ".");
    if (tok.countTokens() == 1) {
        template = strData;
    } else {
        template = tok.nextToken();
        grid[0] = Float.parseFloat(tok.nextToken());
        grid[1] = Float.parseFloat(tok.nextToken());
        grid[2] = Float.parseFloat(tok.nextToken());
    }

    if (template.equals("sphere")) {
        GameonModel model = createFromType(GameonModelData.Type.SPHERE, color, textid, grid);
        model.mModelTemplate = GameonModelData.Type.SPHERE;
        model.mIsModel = true;
        return model;

    } else if (template.equals("cube")) {
        //GameonModel model = new GameonModel(strData , mApp);
        //model.createObject(8,8);
        GameonModel model = createFromType(GameonModelData.Type.CUBE, color, textid, grid);
        model.mModelTemplate = GameonModelData.Type.CUBE;
        model.mIsModel = true;
        return model;

    }

    GameonModel model = new GameonModel(template, mApp, null);
    if (template.equals("cylinder")) {
        model.createModel(GameonModelData.Type.CYLINDER, textid, color, grid);
        model.mModelTemplate = GameonModelData.Type.CYLINDER;
        model.mIsModel = true;
    } else if (template.equals("plane")) {
        model.createPlane(-0.5f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f, color, grid);
        model.mModelTemplate = GameonModelData.Type.CYLINDER;
        model.mIsModel = true;
    } else if (template.equals("card52")) {
        model.createCard2(-0.5f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f, color);
        model.mModelTemplate = GameonModelData.Type.CARD52;
        model.mForceHalfTexturing = true;
        model.mForcedOwner = 32;
        model.mHasAlpha = true;
        model.mIsModel = true;
    } else if (template.equals("cardbela")) {
        model.createCard(-0.5f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f, mApp.colors().transparent);
        model.mModelTemplate = GameonModelData.Type.CARD52;
        model.mForceHalfTexturing = true;
        model.mForcedOwner = 32;
        model.mHasAlpha = true;
        model.mIsModel = true;
    } else if (template.equals("background")) {
        model.createPlane(-0.5f, -0.5f, 0.0f, 0.5f, 0.5f, 0.0f, color, grid);
        model.mModelTemplate = GameonModelData.Type.BACKGROUND;
        model.mHasAlpha = true;
        model.mIsModel = false;

    } else {
        return null;
    }

    model.setTexture(textid);
    return model;

}

From source file:de.tor.tribes.ui.views.DSWorkbenchWatchtowerFrame.java

private void bbCopySelection() {
    try {/*from   w w w  .j  av a 2  s .c o  m*/
        int[] rows = jWatchtowerTable.getSelectedRows();
        if (rows.length == 0) {
            return;
        }

        boolean extended = (JOptionPaneHelper.showQuestionConfirmBox(this,
                "Erweiterte BB-Codes verwenden (nur fr Forum und Notizen geeignet)?", "Erweiterter BB-Code",
                "Nein", "Ja") == JOptionPane.YES_OPTION);

        StringBuilder buffer = new StringBuilder();
        if (extended) {
            buffer.append("[u][size=12]Watchturmdrfer[/size][/u]\n\n");
        } else {
            buffer.append("[u]Watchturmdrfer[/u]\n\n");
        }

        buffer.append("[table]\n");
        buffer.append("[**]Spieler[||]Dorf[||]Radius[/**]\n");

        for (int row1 : rows) {
            int row = jWatchtowerTable.convertRowIndexToModel(row1);
            int tribeCol = jWatchtowerTable.convertColumnIndexToModel(0);
            int villageCol = jWatchtowerTable.convertColumnIndexToModel(1);
            int rangeCol = jWatchtowerTable.convertColumnIndexToModel(2);
            buffer.append("[*]")
                    .append(((Tribe) jWatchtowerTable.getModel().getValueAt(row, tribeCol)).toBBCode())
                    .append("[|]")
                    .append(((Village) jWatchtowerTable.getModel().getValueAt(row, villageCol)).toBBCode())
                    .append("[|]").append(jWatchtowerTable.getModel().getValueAt(row, rangeCol));
        }

        buffer.append("[/table]");

        if (extended) {
            buffer.append("\n[size=8]Erstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "[/size]\n");
        } else {
            buffer.append("\nErstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "\n");
        }

        String b = buffer.toString();
        StringTokenizer t = new StringTokenizer(b, "[");
        int cnt = t.countTokens();
        if (cnt > 1000) {
            if (JOptionPaneHelper.showQuestionConfirmBox(this,
                    "Die ausgewhlten Wachtrme bentigen mehr als 1000 BB-Codes\n"
                            + "und knnen daher im Spiel (Forum/IGM/Notizen) nicht auf einmal dargestellt werden.\n"
                            + "Trotzdem exportieren?",
                    "Zu viele BB-Codes", "Nein", "Ja") == JOptionPane.NO_OPTION) {
                return;
            }
        }

        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(b), null);
        String result = "Daten in Zwischenablage kopiert.";
        showSuccess(result);
    } catch (Exception e) {
        logger.error("Failed to copy data to clipboard", e);
        String result = "Fehler beim Kopieren in die Zwischenablage.";
        showError(result);
    }
}

From source file:edu.ucla.stat.SOCR.chart.SuperBoxAndWhiskerChart.java

public void setDataTable(String input) {
    hasExample = true;/*from  www.  ja v a  2  s  .c om*/
    StringTokenizer lnTkns = new StringTokenizer(input, "#");
    String line;
    int lineCt = lnTkns.countTokens();
    resetTableRows(lineCt);
    int r = 0;
    while (lnTkns.hasMoreTokens()) {
        line = lnTkns.nextToken();

        //   String tb[] =line.split("\t");
        StringTokenizer cellTkns = new StringTokenizer(line, ";");// IE use "space" Mac use tab as cell separator
        int cellCnt = cellTkns.countTokens();
        String tb[] = new String[cellCnt];
        int r1 = 0;
        while (cellTkns.hasMoreTokens()) {
            tb[r1] = cellTkns.nextToken();
            r1++;
        }
        //System.out.println("tb.length="+tb.length);
        int colCt = tb.length;
        resetTableColumns(colCt);
        for (int i = 0; i < tb.length; i++) {
            //System.out.println(tb[i]);
            if (tb[i].length() == 0)
                tb[i] = "0";
            dataTable.setValueAt(tb[i], r, i);
        }
        r++;
    }

    // this will update the mapping panel     
    resetTableColumns(dataTable.getColumnCount());
}

From source file:org.apache.ctakes.lvg.ae.LvgAnnotator.java

/**
 * Helper method that loads a Lemma cache file.
 * // ww  w .ja v a  2s.co  m
 * @param location
 */
private void loadLemmaCacheFile(String cpLocation) throws FileNotFoundException, IOException {
    try (InputStream inStream = getClass().getResourceAsStream(cpLocation);
            BufferedReader br = new BufferedReader(new InputStreamReader(inStream));) {
        // initialize map
        lemmaCacheMap = new HashMap<>();

        String line = br.readLine();
        while (line != null) {
            StringTokenizer st = new StringTokenizer(line, "|");
            if (st.countTokens() == 4) // JZ: changed from 7 to 4 as used a new
            // dictionary
            {
                int freq = Integer.parseInt(st.nextToken());
                if (freq > lemmaCacheFreqCutoff) {
                    String origWord = st.nextToken();
                    String lemmaWord = st.nextToken();
                    String combinedCategories = st.nextToken();

                    // strip < and > chars
                    combinedCategories = combinedCategories.substring(1, combinedCategories.length() - 1);

                    // construct Lemma object
                    LemmaLocalClass l = new LemmaLocalClass();
                    l.word = lemmaWord;
                    l.posSet = new HashSet<>();
                    long bitVector = Category.ToValue(combinedCategories);
                    long[] bitValues = Category.ToValuesArray(bitVector);
                    for (int i = 0; i < bitValues.length; i++) {
                        String pos = Category.ToName(bitValues[i]);
                        // convert Xerox tag into Treebank
                        String treebankTag = xeroxTreebankMap.get(pos);
                        if (treebankTag != null) {
                            l.posSet.add(treebankTag);
                        }
                    }

                    // add Lemma to cache map
                    Set<LemmaLocalClass> lemmaSet = null;
                    if (!lemmaCacheMap.containsKey(origWord)) {
                        lemmaSet = new HashSet<>();
                    } else {
                        lemmaSet = lemmaCacheMap.get(origWord);
                    }
                    lemmaSet.add(l);
                    lemmaCacheMap.put(origWord, lemmaSet);
                } else {
                    logger.debug("Discarding lemma cache line due to frequency cutoff: " + line);
                }
            } else {
                logger.warn("Invalid LVG lemma cache " + "line: " + line);
            }
            line = br.readLine();
        }
    }
}