Example usage for java.util StringTokenizer hasMoreElements

List of usage examples for java.util StringTokenizer hasMoreElements

Introduction

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

Prototype

public boolean hasMoreElements() 

Source Link

Document

Returns the same value as the hasMoreTokens method.

Usage

From source file:gtu._work.etc.HotnoteMakerUI.java

private void initGUI() {
    try {/*from   w  w w  . j av a 2s. c  o  m*/
        ToolTipManager.sharedInstance().setInitialDelay(0);
        BorderLayout thisLayout = new BorderLayout();
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(thisLayout);
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            {
                jPanel1 = new JPanel();
                BorderLayout jPanel1Layout = new BorderLayout();
                jPanel1.setLayout(jPanel1Layout);
                jTabbedPane1.addTab("hott notes - checklist", null, jPanel1, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
                    jScrollPane1.setPreferredSize(new java.awt.Dimension(612, 348));
                    {
                        checkListArea = new JTextArea();
                        jScrollPane1.setViewportView(checkListArea);
                        checkListArea.addMouseListener(new MouseAdapter() {

                            String randomColor() {
                                StringBuilder sb = new StringBuilder().append("#");
                                for (int ii = 0; ii < 6; ii++) {
                                    sb.append(RandomUtil.randomChar('a', 'b', 'c', 'd', 'f', '0', '1', '2', '3',
                                            '4', '5', '6', '7', '8', '9'));
                                }
                                return sb.toString();
                            }

                            void saveXml(Document document, File file) {
                                OutputFormat format = OutputFormat.createPrettyPrint();
                                format.setEncoding("utf-16");
                                XMLWriter writer = null;
                                try {
                                    writer = new XMLWriter(new FileWriter(file), format);
                                    writer.write(document);
                                } catch (IOException e) {
                                    JCommonUtil.handleException(e);
                                } finally {
                                    if (writer != null) {
                                        try {
                                            writer.close();
                                        } catch (IOException e) {
                                            JCommonUtil.handleException(e);
                                        }
                                    }
                                }
                            }

                            public void mouseClicked(MouseEvent evt) {
                                if (!JMouseEventUtil.buttonLeftClick(2, evt)) {
                                    return;
                                }

                                if (StringUtils.isEmpty(checkListArea.getText())) {
                                    JCommonUtil
                                            ._jOptionPane_showMessageDialog_error("checklist area is empty!");
                                    return;
                                }

                                File file = JCommonUtil._jFileChooser_selectFileOnly_saveFile();
                                if (file == null) {
                                    JCommonUtil._jOptionPane_showMessageDialog_error("file is not correct!");
                                    return;
                                }

                                //XXX
                                StringTokenizer tok = new StringTokenizer(checkListArea.getText(), "\t\n\r\f");
                                List<String> list = new ArrayList<String>();
                                String tmp = null;
                                for (; tok.hasMoreElements();) {
                                    tmp = ((String) tok.nextElement()).trim();
                                    System.out.println(tmp);
                                    list.add(tmp);
                                }
                                //XXX

                                Document document = DocumentHelper.createDocument();
                                Element rootHot = document.addElement("hottnote");
                                rootHot.addAttribute("creationtime",
                                        new Timestamp(System.currentTimeMillis()).toString());
                                rootHot.addAttribute("lastmodified",
                                        new Timestamp(System.currentTimeMillis()).toString());
                                rootHot.addAttribute("type", "checklist");
                                //appearence
                                Element appearenceE = rootHot.addElement("appearence");
                                appearenceE.addAttribute("alpha", "204");
                                Element fontE = appearenceE.addElement("font");
                                fontE.addAttribute("face", "Default");
                                fontE.addAttribute("size", "0");
                                Element styleE = appearenceE.addElement("style");
                                styleE.addElement("bg2color").addAttribute("color", randomColor());
                                styleE.addElement("bgcolor").addAttribute("color", randomColor());
                                styleE.addElement("textcolor").addAttribute("color", randomColor());
                                styleE.addElement("titlecolor").addAttribute("color", randomColor());
                                //behavior
                                rootHot.addElement("behavior");
                                //content
                                Element contentE = rootHot.addElement("content");
                                Element checklistE = contentE.addElement("checklist");
                                for (String val : list) {
                                    checklistE.addElement("item").addCDATA(val);
                                }
                                //desktop
                                Element desktopE = rootHot.addElement("desktop");
                                desktopE.addElement("position").addAttribute("x", RandomUtil.numberStr(3))
                                        .addAttribute("y", RandomUtil.numberStr(3));
                                desktopE.addElement("size").addAttribute("height", "200").addAttribute("width",
                                        "200");
                                //title
                                Element titleE = rootHot.addElement("title");
                                titleE.addCDATA(StringUtils.defaultIfEmpty(checkListTitle.getText(),
                                        DateFormatUtils.format(System.currentTimeMillis(), "dd/MM/yyyy")));

                                if (!file.getName().toLowerCase().endsWith(".hottnote")) {
                                    file = new File(file.getParentFile(), file.getName() + ".hottnote");
                                }

                                saveXml(document, file);
                                JCommonUtil._jOptionPane_showMessageDialog_info("completed!\n" + file);
                            }
                        });
                    }
                }
                {
                    checkListTitle = new JTextField();
                    checkListTitle.setToolTipText("title");
                    jPanel1.add(checkListTitle, BorderLayout.NORTH);
                }
            }
        }
        pack();
        this.setSize(633, 415);
    } catch (Exception e) {
        //add your error handling code here
        e.printStackTrace();
    }
}

From source file:ch.epfl.lsir.xin.algorithm.core.ItemBasedCF.java

@Override
public void readModel(String file) {
    // TODO Auto-generated method stub
    try {//from ww w.ja  v  a 2 s.  c o  m
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = null;
        int u1 = 0;
        while ((line = reader.readLine()) != null) {
            StringTokenizer tokens = new StringTokenizer(line.trim());
            int u2 = 0;
            while (tokens.hasMoreElements()) {
                this.similarityMatrix[u1][u2] = Double.parseDouble(tokens.nextToken());
                u2++;
            }
            u1++;
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:us.mn.state.health.lims.testmanagement.action.TestManagementNewbornCancelTestsAction.java

protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");
    String selectedTestsString = (String) request.getParameter("selectedTests");

    BaseActionForm dynaForm = (BaseActionForm) form;
    String accessionNumber = (String) dynaForm.get("accessionNumber");

    // initialize the form
    dynaForm.initialize(mapping);//from ww  w .  ja v a 2 s. c  o m

    ActionMessages errors = null;
    Map errorMap = new HashMap();
    errorMap.put(HAS_AMENDED_TEST, new ArrayList());
    errorMap.put(INVALID_STATUS_RESULTS_COMPLETE, new ArrayList());
    errorMap.put(INVALID_STATUS_RESULTS_VERIFIED, new ArrayList());

    Transaction tx = HibernateUtil.getSession().beginTransaction();
    try {

        SampleDAO sampleDAO = new SampleDAOImpl();
        SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
        TestDAO testDAO = new TestDAOImpl();
        AnalysisDAO analysisDAO = new AnalysisDAOImpl();
        ResultDAO resultDAO = new ResultDAOImpl();
        NoteDAO noteDAO = new NoteDAOImpl();
        AnalysisQaEventDAO analysisQaEventDAO = new AnalysisQaEventDAOImpl();
        AnalysisQaEventActionDAO analysisQaEventActionDAO = new AnalysisQaEventActionDAOImpl();
        List listOfIds = new ArrayList();

        UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
        String sysUserId = String.valueOf(usd.getSystemUserId());

        if (!StringUtil.isNullorNill(selectedTestsString)) {

            String idSeparator = SystemConfiguration.getInstance().getDefaultIdSeparator();
            StringTokenizer st = new StringTokenizer(selectedTestsString, idSeparator);
            while (st.hasMoreElements()) {
                String id = (String) st.nextElement();
                listOfIds.add(id);
            }

            for (int i = 0; i < listOfIds.size(); i++) {
                String id = (String) listOfIds.get(i);
                Test test = new Test();
                test.setId(id);
                testDAO.getData(test);
                if (test != null && !StringUtil.isNullorNill(test.getId())) {
                    Analysis analysis = new Analysis();
                    analysis.setTest(test);
                    Sample sample = new Sample();
                    sample = sampleDAO.getSampleByAccessionNumber(accessionNumber);
                    SampleItem sampleItem = new SampleItem();
                    sampleItem.setSample(sample);
                    sampleItemDAO.getDataBySample(sampleItem);
                    analysis.setSampleItem(sampleItem);
                    analysisDAO.getMaxRevisionAnalysisBySampleAndTest(analysis);
                    if (analysis != null && !StringUtil.isNullorNill(analysis.getId())) {

                        if (analysis.getStatus()
                                .equals(SystemConfiguration.getInstance().getAnalysisStatusAssigned())) {
                            if (!analysis.getRevision().equals("0")) {
                                List listOfAmendedTests = (ArrayList) errorMap.get(HAS_AMENDED_TEST);
                                listOfAmendedTests.add(analysis);
                                errorMap.put(HAS_AMENDED_TEST, listOfAmendedTests);
                            }

                        } else if (analysis.getStatus()
                                .equals(SystemConfiguration.getInstance().getAnalysisStatusResultCompleted())) {
                            List listOfCompletedTests = (ArrayList) errorMap
                                    .get(INVALID_STATUS_RESULTS_COMPLETE);
                            listOfCompletedTests.add(analysis);
                            errorMap.put(INVALID_STATUS_RESULTS_COMPLETE, listOfCompletedTests);
                            continue;
                        } else if (analysis.getStatus()
                                .equals(SystemConfiguration.getInstance().getAnalysisStatusReleased())) {
                            List listOfVerifiedTests = (ArrayList) errorMap
                                    .get(INVALID_STATUS_RESULTS_VERIFIED);
                            listOfVerifiedTests.add(analysis);
                            errorMap.put(INVALID_STATUS_RESULTS_VERIFIED, listOfVerifiedTests);
                            continue;
                        }

                        analysis.setSysUserId(sysUserId);
                        analysis.setStatus(SystemConfiguration.getInstance().getAnalysisStatusCanceled());
                        analysisDAO.updateData(analysis);
                    }

                }

            }
        }

        PropertyUtils.setProperty(dynaForm, ACCESSION_NUMBER, accessionNumber);
        tx.commit();

        if (errorMap != null && errorMap.size() > 0) {
            List amendedTests = (ArrayList) errorMap.get(HAS_AMENDED_TEST);
            List completedTests = (ArrayList) errorMap.get(INVALID_STATUS_RESULTS_COMPLETE);
            List verifiedTests = (ArrayList) errorMap.get(INVALID_STATUS_RESULTS_VERIFIED);
            if ((amendedTests != null && amendedTests.size() > 0)
                    || (completedTests != null && completedTests.size() > 0)
                    || (verifiedTests != null && verifiedTests.size() > 0)) {
                errors = new ActionMessages();

                if (amendedTests != null && amendedTests.size() > 0) {
                    ActionError error = null;
                    if (amendedTests.size() > 1) {
                        StringBuffer stringOfTests = new StringBuffer();
                        for (int i = 0; i < amendedTests.size(); i++) {
                            Analysis analysis = (Analysis) amendedTests.get(i);
                            stringOfTests.append("\\n    " + analysis.getTest().getTestDisplayValue());
                        }
                        error = new ActionError("testsmanagement.message.multiple.test.not.canceled.amended",
                                stringOfTests.toString(), null);
                    } else {
                        Analysis analysis = (Analysis) amendedTests.get(0);
                        error = new ActionError("testsmanagement.message.one.test.not.canceled.amended",
                                "\\n    " + analysis.getTest().getTestDisplayValue(), null);
                    }
                    errors.add(ActionMessages.GLOBAL_MESSAGE, error);

                }

                if (completedTests != null && completedTests.size() > 0) {
                    ActionError error = null;
                    if (completedTests.size() > 1) {
                        StringBuffer stringOfTests = new StringBuffer();
                        for (int i = 0; i < completedTests.size(); i++) {
                            Analysis analysis = (Analysis) completedTests.get(i);
                            stringOfTests.append("\\n    " + analysis.getTest().getTestDisplayValue());
                        }
                        error = new ActionError("testsmanagement.message.multiple.test.not.canceled.completed",
                                stringOfTests.toString(), null);
                    } else {
                        Analysis analysis = (Analysis) completedTests.get(0);
                        error = new ActionError("testsmanagement.message.one.test.not.canceled.completed",
                                "\\n    " + analysis.getTest().getTestDisplayValue(), null);
                    }
                    errors.add(ActionMessages.GLOBAL_MESSAGE, error);

                }

                if (verifiedTests != null && verifiedTests.size() > 0) {
                    ActionError error = null;
                    if (verifiedTests.size() > 1) {
                        StringBuffer stringOfTests = new StringBuffer();
                        for (int i = 0; i < verifiedTests.size(); i++) {
                            Analysis analysis = (Analysis) verifiedTests.get(i);
                            stringOfTests.append("\\n    " + analysis.getTest().getTestDisplayValue());
                        }
                        error = new ActionError("testsmanagement.message.multiple.test.not.canceled.verified",
                                stringOfTests.toString(), null);
                    } else {
                        Analysis analysis = (Analysis) verifiedTests.get(0);
                        error = new ActionError("testsmanagement.message.one.test.not.canceled.verified",
                                "\\n    " + analysis.getTest().getTestDisplayValue(), null);
                    }
                    errors.add(ActionMessages.GLOBAL_MESSAGE, error);

                }

                saveErrors(request, errors);
                request.setAttribute(Globals.ERROR_KEY, errors);
            }

        }

    } catch (LIMSRuntimeException lre) {
        LogEvent.logError("TestManagementNewbornCancelTests", "performAction()", lre.toString());
        tx.rollback();
        errors = new ActionMessages();
        ActionError error = null;

        if (lre.getException() instanceof org.hibernate.StaleObjectStateException) {
            error = new ActionError("errors.OptimisticLockException", null, null);
        } else {

            error = new ActionError("errors.UpdateException", null, null);
        }

        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        saveErrors(request, errors);
        request.setAttribute(Globals.ERROR_KEY, errors);
        request.setAttribute(ALLOW_EDITS_KEY, "false");
        return mapping.findForward(FWD_FAIL);

    } finally {
        HibernateUtil.closeSession();
    }
    return mapping.findForward(forward);
}

From source file:org.wymiwyg.commons.util.URI.java

public static int str2flags(String pv) {
    StringTokenizer tkn = new StringTokenizer(pv, ", ");
    int rslt = 0;
    while (tkn.hasMoreElements()) {
        String flag = tkn.nextToken();
        if (flag.equals("same-document"))
            rslt |= SAMEDOCUMENT;/* w  w  w .j a v a 2s .  co  m*/
        else if (flag.equals("network"))
            rslt |= NETWORK;
        else if (flag.equals("absolute"))
            rslt |= ABSOLUTE;
        else if (flag.equals("relative"))
            rslt |= RELATIVE;
        else if (flag.equals("parent"))
            rslt |= PARENT;
        else if (flag.equals("grandparent"))
            rslt |= GRANDPARENT;
        else

            logger.warn("Incorrect property value for relativeURIs: " + flag);
    }
    return rslt;
}

From source file:com.netscape.cmscore.util.Debug.java

/**
 * Debug subsystem initialization. This subsystem is usually
 * given the following parameters:/*w ww .  j  av a2  s  . c om*/
 *
 * <pre>
 * debug.enabled   : (true|false) default false
 * debug.filename  : can be a pathname, or STDOUT
 * debug.hashkeytypes: comma-separated list of hashkey types
 *    possible values:  "CS.cfg"
 * debug.showcaller: (true|false) default false  [show caller method name for Debug.trace()]
 * </pre>
 */
public void init(ISubsystem owner, IConfigStore config) {
    mConfig = config;
    String filename = null;
    String hashkeytypes = null;
    boolean append = true;

    try {
        TRACE_ON = mConfig.getBoolean(PROP_ENABLED, false);
        if (TRACE_ON) {
            filename = mConfig.getString(PROP_FILENAME, null);
            if (filename == null) {
                TRACE_ON = false;
            }
            hashkeytypes = mConfig.getString(PROP_HASHKEYS, null);
            mShowCaller = mConfig.getBoolean(PROP_SHOWCALLER, false);
            append = mConfig.getBoolean(PROP_APPEND, true);
        }
        if (TRACE_ON) {
            if (filename.equals("STDOUT")) {
                mOut = System.out;
            } else {
                if (!Utils.isNT()) {
                    // Always insure that a physical file exists!
                    Utils.exec("touch " + filename);
                    Utils.exec("chmod 00640 " + filename);
                }
                OutputStream os = new FileOutputStream(filename, append);
                mOut = new PrintStream(os, true); /* true == autoflush */
            }
            if (hashkeytypes != null) {
                StringTokenizer st = new StringTokenizer(hashkeytypes, ",", false);
                mHK = new Hashtable<String, String>();
                while (st.hasMoreElements()) {
                    String hkr = st.nextToken();
                    mHK.put(hkr, "true");
                }
            }
        }
        outputTraceMessage("============================================");
        outputTraceMessage("=====  DEBUG SUBSYSTEM INITIALIZED   =======");
        outputTraceMessage("============================================");
        int level = mConfig.getInteger(PROP_LEVEL, VERBOSE);
        setLevel(level);
    } catch (Exception e) {
        // Don't do anything. Logging is not set up yet, and
        // we can't write to STDOUT.
    }
}

From source file:com.sshtools.j2ssh.transport.AbstractKnownHostsKeyVerification.java

/**
 * <p>/*from www .j av  a2s.c o m*/
 * Verifies a host key against the list of known_hosts.
 * </p>
 *
 * <p>
 * If the host unknown or the key does not match the currently allowed host
 * key the abstract <code>onUnknownHost</code> or
 * <code>onHostKeyMismatch</code> methods are called so that the caller
 * may identify and allow the host.
 * </p>
 *
 * @param host the name of the host
 * @param pk the host key supplied
 *
 * @return true if the host is accepted, otherwise false
 *
 * @throws TransportProtocolException if an error occurs
 *
 * @since 0.2.0
 */
public boolean verifyHost(String host, SshPublicKey pk) throws TransportProtocolException {
    String fingerprint = pk.getFingerprint();
    log.info("Verifying " + host + " host key");

    if (log.isDebugEnabled()) {
        log.debug("Fingerprint: " + fingerprint);
    }

    Iterator it = allowedHosts.keySet().iterator();

    while (it.hasNext()) {
        // Could be a comma delimited string of names/ip addresses
        String names = (String) it.next();

        if (names.equals(host)) {
            return validateHost(names, pk);
        }

        StringTokenizer tokens = new StringTokenizer(names, ",");

        while (tokens.hasMoreElements()) {
            // Try the allowed hosts by looking at the allowed hosts map
            String name = (String) tokens.nextElement();

            if (name.equalsIgnoreCase(host)) {
                return validateHost(names, pk);
            }
        }
    }

    // The host is unknown os ask the user
    onUnknownHost(host, pk);

    // Recheck ans return the result
    return checkKey(host, pk);
}

From source file:util.IPChecker.java

private void validateIP4(final String ip, final IPForm ranges) {
    // get IP parts
    final List<String> parts = new ArrayList<String>();
    final StringTokenizer tokenizer = new StringTokenizer(ip, ".");

    while (tokenizer.hasMoreElements()) {
        parts.add(tokenizer.nextElement().toString().trim());
    }/*from  w ww . jav a 2 s .c  om*/

    // validate each part...
    if (isValidIP4Parts(parts)) {
        ranges.getIp4().add(ip);
    } else {
        ranges.getInvalidIPs().add(ip);
    }

}

From source file:de.betterform.connector.SchemaValidator.java

/**
 * validate the instance according to the schema specified on the model
 *
 * @return false if the instance is not valid
 *///from   ww w . j  av a2s  .c o m
public boolean validateSchema(Model model, Node instance) throws XFormsException {
    boolean valid = true;
    String message;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.validateSchema: validating instance");

    //needed if we want to load schemas from Model + set it as "schemaLocation" attribute
    String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema");
    if (schemas != null && !schemas.equals("")) {
        //          valid=false;

        //add schemas to element
        //shouldn't it be done on a copy of the doc ?
        Element el = null;
        if (instance.getNodeType() == Node.ELEMENT_NODE)
            el = (Element) instance;
        else if (instance.getNodeType() == Node.DOCUMENT_NODE)
            el = ((Document) instance).getDocumentElement();
        else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("instance node type is: " + instance.getNodeType());
        }

        String prefix = NamespaceResolver.getPrefix(el, NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
        //test if with targetNamespace or not
        //if more than one schema : namespaces are mandatory ! (optional only for 1)
        StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false);
        String schemaLocations = null;
        String noNamespaceSchemaLocation = null;
        while (tokenizer.hasMoreElements()) {
            String token = (String) tokenizer.nextElement();
            //check that it is an URL
            URI uri = null;
            try {
                uri = new java.net.URI(token);
            } catch (java.net.URISyntaxException ex) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(token + " is not an URI");
            }

            if (uri != null) {
                String ns;
                try {
                    ns = this.getSchemaNamespace(uri);

                    if (ns != null && !ns.equals("")) {
                        if (schemaLocations == null)
                            schemaLocations = ns + " " + token;
                        else
                            schemaLocations = schemaLocations + " " + ns + " " + token;

                        ///add the namespace declaration if it is not on the instance?
                        //TODO: how to know with which prefix ?
                        String nsPrefix = NamespaceResolver.getPrefix(el, ns);
                        if (nsPrefix == null) { //namespace not declared !
                            LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token
                                    + " is not declared in instance: declaring it as default...");
                            el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns);
                        }
                    } else if (noNamespaceSchemaLocation == null)
                        noNamespaceSchemaLocation = token;
                    else { //we have more than one schema without namespace
                        LOGGER.warn("SchemaValidator: There is more than one schema without namespace !");
                    }
                } catch (Exception ex) {
                    LOGGER.warn(
                            "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(),
                            ex);
                    //in case there was an exception: do nothing, do not set the schema
                }
            }
        }
        //write schemaLocations found
        if (schemaLocations != null && !schemaLocations.equals(""))
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation",
                    schemaLocations);
        if (noNamespaceSchemaLocation != null)
            el.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation",
                    noNamespaceSchemaLocation);

        //save and parse the doc
        ValidationErrorHandler handler = null;
        File f;
        try {
            //save document
            f = File.createTempFile("instance", ".xml");
            f.deleteOnExit();
            TransformerFactory trFact = TransformerFactory.newInstance();
            Transformer trans = trFact.newTransformer();
            DOMSource source = new DOMSource(el);
            StreamResult result = new StreamResult(f);
            trans.transform(source, result);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath());

            //parse it with error handler to validate it
            handler = new ValidationErrorHandler();
            SAXParserFactory parserFact = SAXParserFactory.newInstance();
            parserFact.setValidating(true);
            parserFact.setNamespaceAware(true);
            SAXParser parser = parserFact.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            //validation activated
            reader.setFeature("http://xml.org/sax/features/validation", true);
            //schema validation activated
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            //used only to validate the schema, not the instance
            //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true);
            //validate only if there is a grammar
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);

            parser.parse(f, handler);
        } catch (Exception ex) {
            LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex);
            //throw new XFormsException("XMLSchema validation failed. "+message);
        }

        //if no exception
        if (handler != null && handler.isValid())
            valid = true;
        else {
            message = handler.getMessage();
            //TODO: find a way to get the error message displayed
            throw new XFormsException("XMLSchema validation failed. " + message);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Validator.validateSchema: result=" + valid);

    }

    return valid;
}

From source file:org.wso2.carbon.identity.provider.AttributeCallbackHandler.java

protected void populateClaimValues(String userIdentifier, SAMLAttributeCallback callback)
        throws IdentityProviderException {
    UserStoreManager connector = null;/*from   www . j a  v a2 s .c om*/
    RahasData rahasData = null;

    if (log.isDebugEnabled()) {
        log.debug("Populating claim values");
    }

    if (requestedClaims.isEmpty()) {
        return;
    }

    // get the column names for the URIs
    Iterator<RequestedClaimData> ite = requestedClaims.values().iterator();
    List<String> claimList = new ArrayList<String>();
    rahasData = callback.getData();

    while (ite.hasNext()) {
        RequestedClaimData claim = ite.next();
        if (claim != null && !claim.getUri().equals(IdentityConstants.CLAIM_PPID)) {
            claimList.add(claim.getUri());
        }
    }

    String[] claimArray = new String[claimList.size()];
    String userId = userIdentifier;
    Map<String, String> mapValues = null;

    try {
        if (MapUtils.isEmpty(requestedClaimValues)) {
            try {
                connector = IdentityTenantUtil.getRealm(null, userIdentifier).getUserStoreManager();
                mapValues = connector.getUserClaimValues(MultitenantUtils.getTenantAwareUsername(userId),
                        claimList.toArray(claimArray), null);
            } catch (UserStoreException e) {
                throw new IdentityProviderException("Error while instantiating IdentityUserStore", e);
            }
        } else {
            mapValues = requestedClaimValues;
        }

        String claimSeparator = mapValues.get(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
        if (StringUtils.isNotBlank(claimSeparator)) {
            userAttributeSeparator = claimSeparator;
            mapValues.remove(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
        }

        ite = requestedClaims.values().iterator();
        while (ite.hasNext()) {
            SAMLAttribute attribute = null;
            Attribute saml2Attribute = null;
            RequestedClaimData claimData = ite.next();
            claimData.setValue(mapValues.get(claimData.getUri()));
            if (claimData.getValue() != null) {
                if (RahasConstants.TOK_TYPE_SAML_20.equals(rahasData.getTokenType())) {
                    saml2Attribute = getSAML2Attribute(claimData.getUri(), claimData.getValue(),
                            claimData.getUri());
                    callback.addAttributes(saml2Attribute);
                } else {
                    String name;
                    String nameSpace;
                    if (supportedClaims.get(claimData.getUri()) != null) {
                        name = supportedClaims.get(claimData.getUri()).getDisplayTag();
                        nameSpace = claimData.getUri();
                    } else {
                        nameSpace = claimData.getUri();
                        if (nameSpace.contains("/") && nameSpace.length() > (nameSpace.lastIndexOf("/") + 1)) {
                            // Custom claim uri should be in a format of http(s)://nameSpace/name 
                            name = nameSpace.substring(nameSpace.lastIndexOf("/") + 1);
                            nameSpace = nameSpace.substring(0, nameSpace.lastIndexOf("/"));
                        } else {
                            name = nameSpace;
                        }
                    }

                    List<String> values = new ArrayList<String>();

                    if (claimData.getValue().contains(userAttributeSeparator)) {
                        StringTokenizer st = new StringTokenizer(claimData.getValue(), userAttributeSeparator);
                        while (st.hasMoreElements()) {
                            String attValue = st.nextElement().toString();
                            if (attValue != null && attValue.trim().length() > 0) {
                                values.add(attValue);
                            }
                        }
                    } else {
                        values.add(claimData.getValue());
                    }

                    attribute = new SAMLAttribute(name, nameSpace, null, -1, values);
                    callback.addAttributes(attribute);
                }
            }
        }
    } catch (Exception e) {
        throw new IdentityProviderException(e.getMessage(), e);
    }
}

From source file:net.wastl.webmail.server.WebMailServer.java

public String getBaseURI(HTTPRequestHeader header) {
    String host = header.getHeader("Host");
    StringTokenizer tok = new StringTokenizer(host, ":");
    String hostname = tok.nextToken();
    int port = 80;
    if (tok.hasMoreElements()) {
        try {//from  w w w  . j a  v a2  s.  c om
            port = Integer.parseInt(tok.nextToken());
        } catch (NumberFormatException e) {
        }
    }
    int ssl_port = 443;
    try {
        ssl_port = Integer.parseInt(storage.getConfig("ssl port"));
    } catch (NumberFormatException e) {
    }
    int http_port = 80;
    try {
        http_port = Integer.parseInt(storage.getConfig("http port"));
    } catch (NumberFormatException e) {
    }
    String protocol = "http";
    if (port == ssl_port)
        protocol = "https";
    else if (port == http_port)
        protocol = "http";
    return protocol + "://" + host;
}