Example usage for java.util StringTokenizer nextElement

List of usage examples for java.util StringTokenizer nextElement

Introduction

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

Prototype

public Object nextElement() 

Source Link

Document

Returns the same value as the nextToken method, except that its declared return value is Object rather than String .

Usage

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  .  jav a2s .co 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:com.sshtools.j2ssh.transport.AbstractKnownHostsKeyVerification.java

/**
 * <p>/*from  w  ww .j  a v  a  2 s . c  om*/
 * Constructs a host key verification instance reading the specified
 * known_hosts file.
 * </p>
 *
 * @param knownhosts the path of the known_hosts file
 *
 * @throws InvalidHostFileException if the known_hosts file is invalid
 *
 * @since 0.2.0
 */
public AbstractKnownHostsKeyVerification(String knownhosts) throws InvalidHostFileException {
    InputStream in = null;

    try {
        //  If no host file is supplied, or there is not enough permission to load
        //  the file, then just create an empty list.
        if (knownhosts != null) {
            if (System.getSecurityManager() != null) {
                AccessController.checkPermission(new FilePermission(knownhosts, "read"));
            }

            //  Load the hosts file. Do not worry if fle doesnt exist, just disable
            //  save of
            File f = new File(knownhosts);

            if (f.exists()) {
                in = new FileInputStream(f);

                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;

                while ((line = reader.readLine()) != null) {
                    StringTokenizer tokens = new StringTokenizer(line, " ");
                    String host = (String) tokens.nextElement();
                    String algorithm = (String) tokens.nextElement();
                    String key = (String) tokens.nextElement();

                    SshPublicKey pk = SshKeyPairFactory.decodePublicKey(Base64.decode(key));

                    /*if (host.indexOf(",") > -1) {
                       host = host.substring(0, host.indexOf(","));
                     }*/
                    putAllowedKey(host, pk);

                    //allowedHosts.put(host + "#" + pk.getAlgorithmName(), pk);
                }

                reader.close();

                hostFileWriteable = f.canWrite();
            } else {
                // Try to create the file and its parents if necersary
                f.getParentFile().mkdirs();

                if (f.createNewFile()) {
                    FileOutputStream out = new FileOutputStream(f);
                    out.write(toString().getBytes());
                    out.close();
                    hostFileWriteable = true;
                } else {
                    hostFileWriteable = false;
                }
            }

            if (!hostFileWriteable) {
                log.warn("Host file is not writeable.");
            }

            this.knownhosts = knownhosts;
        }
    } catch (AccessControlException ace) {
        hostFileWriteable = false;
        log.warn("Not enough permission to load a hosts file, so just creating an empty list");
    } catch (IOException ioe) {
        hostFileWriteable = false;
        log.info("Could not open or read " + knownhosts + ": " + ioe.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
            }
        }
    }
}

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

private void initGUI() {
    try {/*w  w  w  .j  a  v a  2s.  c om*/
        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:org.programmatori.domotica.own.plugin.system.System.java

private Value devideString(String str, char devideKey) {
    StringTokenizer st = new StringTokenizer(str, "" + devideKey);

    Value v = null;//from  w  w  w .j a v  a2 s .co  m
    boolean first = true;

    while (st.hasMoreElements()) {
        String val = (String) st.nextElement();

        if (first) {
            v = new Value(val);
            first = false;
        } else {
            v.addValue(val);
        }
    }

    return v;
}

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  www. j  a  v a 2 s .  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.apache.cayenne.modeler.dialog.pref.DataSourcePreferences.java

/**
 * Tries to establish a DB connection, reporting the status of this
 * operation./*w ww.  j av  a  2 s.  co m*/
 */
public void testDataSourceAction() {
    DBConnectionInfo currentDataSource = getConnectionInfo();
    if (currentDataSource == null) {
        return;
    }

    if (currentDataSource.getJdbcDriver() == null) {
        JOptionPane.showMessageDialog(null, "No JDBC Driver specified", "Warning", JOptionPane.WARNING_MESSAGE);
        return;
    }

    if (currentDataSource.getUrl() == null) {
        JOptionPane.showMessageDialog(null, "No Database URL specified", "Warning",
                JOptionPane.WARNING_MESSAGE);
        return;
    }

    try {

        FileClassLoadingService classLoader = new FileClassLoadingService();

        List<File> oldPathFiles = ((FileClassLoadingService) getApplication().getClassLoadingService())
                .getPathFiles();

        Collection<String> details = new ArrayList<>();
        for (File oldPathFile : oldPathFiles) {
            details.add(oldPathFile.getAbsolutePath());
        }

        Preferences classPathPreferences = getApplication().getPreferencesNode(ClasspathPreferences.class, "");
        if (editor.getChangedPreferences().containsKey(classPathPreferences)) {
            Map<String, String> map = editor.getChangedPreferences().get(classPathPreferences);

            for (Map.Entry<String, String> en : map.entrySet()) {
                String key = en.getKey();
                if (!details.contains(key)) {
                    details.add(key);
                }
            }
        }

        if (editor.getRemovedPreferences().containsKey(classPathPreferences)) {
            Map<String, String> map = editor.getRemovedPreferences().get(classPathPreferences);

            for (Map.Entry<String, String> en : map.entrySet()) {
                String key = en.getKey();
                if (details.contains(key)) {
                    details.remove(key);
                }
            }
        }

        if (details.size() > 0) {

            // transform preference to file...
            Transformer transformer = new Transformer() {

                public Object transform(Object object) {
                    String pref = (String) object;
                    return new File(pref);
                }
            };

            classLoader.setPathFiles(CollectionUtils.collect(details, transformer));
        }

        Class<Driver> driverClass = classLoader.loadClass(Driver.class, currentDataSource.getJdbcDriver());
        Driver driver = driverClass.newInstance();

        // connect via Cayenne DriverDataSource - it addresses some driver
        // issues...
        // can't use try with resource here as we can loose meaningful exception
        Connection c = new DriverDataSource(driver, currentDataSource.getUrl(), currentDataSource.getUserName(),
                currentDataSource.getPassword()).getConnection();
        try {
            c.close();
        } catch (SQLException ignored) {
            // i guess we can ignore this...
        }

        JOptionPane.showMessageDialog(null, "Connected Successfully", "Success",
                JOptionPane.INFORMATION_MESSAGE);
    } catch (Throwable th) {
        th = Util.unwindException(th);
        String message = "Error connecting to DB: " + th.getLocalizedMessage();

        StringTokenizer st = new StringTokenizer(message);
        StringBuilder sbMessage = new StringBuilder();
        int len = 0;

        String tempString;
        while (st.hasMoreTokens()) {
            tempString = st.nextElement().toString();
            if (len < 110) {
                len = len + tempString.length() + 1;
            } else {
                sbMessage.append("\n");
                len = 0;
            }
            sbMessage.append(tempString).append(" ");
        }

        JOptionPane.showMessageDialog(null, sbMessage.toString(), "Warning", JOptionPane.WARNING_MESSAGE);
    }
}

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

protected void populateClaimValues(String userIdentifier, SAMLAttributeCallback callback)
        throws IdentityProviderException {
    UserStoreManager connector = null;/*from w  w  w . j a  v a  2 s .  c  o  m*/
    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:util.IPChecker.java

private boolean isInvalidSubpartsIP4(final String part) {

    if (part.contains("-")) {

        final List<String> subparts = new ArrayList<String>();
        final StringTokenizer tokenizer = new StringTokenizer(part, "-");
        while (tokenizer.hasMoreElements()) {
            subparts.add(tokenizer.nextElement().toString().trim());
        }/*from  w w  w . ja v a2  s .  co  m*/
        // we need exact two subparts
        if (subparts.size() != 2) {
            return true;
        }
        final String validChars = "0123456789";
        for (final String subpart : subparts) {
            // ...and only contain digits and dash
            if (!org.apache.commons.lang.StringUtils.containsOnly(subpart, validChars)
                    || isInvalidIP4PartRange(subpart)) {
                return true;
            }
        }
        // make sure subpart 1 is smaller than subpart 2
        final int sp1 = Integer.valueOf(subparts.get(0));
        final int sp2 = Integer.valueOf(subparts.get(1));
        if (sp2 == sp1 || sp2 < sp1) {
            return true;
        }

    } else {
        // validate single part for 1-255
        if (isInvalidIP4PartRange(part)) {
            return true;
        }
    }
    return false;
}

From source file:com.eviware.soapui.support.log.JLogList.java

public synchronized void addLine(Object line) {
    if (!isEnabled())
        return;/*from  w w  w  .  j  a  v a 2 s  .  c  om*/

    synchronized (model.lines) {
        if (line instanceof LoggingEvent) {
            LoggingEvent ev = (LoggingEvent) line;
            linesToAdd.push(new LoggingEventWrapper(ev));

            if (ev.getThrowableInformation() != null) {
                Throwable t = ev.getThrowableInformation().getThrowable();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                t.printStackTrace(pw);
                StringTokenizer st = new StringTokenizer(sw.toString(), "\r\n");
                while (st.hasMoreElements())
                    linesToAdd.push("   " + st.nextElement());
            }
        } else {
            linesToAdd.push(line);
        }
    }
    if (future == null) {
        released = false;
        future = SoapUI.getThreadPool().submit(model);
    }
}

From source file:org.kuali.ole.select.service.OLEInvoiceSearchService.java

public OLEInvoiceSearchDocument convertToOleInvoiceDocument(DocumentSearchResult documentSearchResult) {
    OLEInvoiceSearchDocument invoiceDocument = new OLEInvoiceSearchDocument();
    Document document = documentSearchResult.getDocument();
    List<DocumentAttribute> documentAttributes = documentSearchResult.getDocumentAttributes();
    for (DocumentAttribute docAttribute : documentAttributes) {
        String name = docAttribute.getName();

        if (name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.INV_DATE)) {
            if (docAttribute.getValue() != null) {
                DateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy");
                String stringDateObj = (String) docAttribute.getValue().toString();
                Method getMethod;
                try {
                    java.util.Date date = sourceFormat.parse(stringDateObj);
                    invoiceDocument.setInvoiceDate(date);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }// w  w w . java 2 s . c om
            }
        }
        if (name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.INV_PAY_DATE)) {
            if (docAttribute.getValue() != null) {
                DateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy");
                String stringDateObj = (String) docAttribute.getValue().toString();
                Method getMethod;
                try {
                    java.util.Date date = sourceFormat.parse(stringDateObj);
                    invoiceDocument.setInvoicePayDate(date);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        }
        if (name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.INV_SUB_TYP_ID)) {
            if (docAttribute.getValue() != null) {
                String stringDateObj = (String) docAttribute.getValue().toString();
                invoiceDocument.setInvoiceSubTypeId(Integer.parseInt(stringDateObj));
            }
        }
        if (name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.PURAP_ID)) {
            if (invoiceDocument.getPurapDocumentIdentifier() != null
                    && (!invoiceDocument.getPurapDocumentIdentifier().equalsIgnoreCase(""))) {
                Set<String> hashSet = new HashSet<String>();
                String purarIdList = "";
                StringTokenizer stringTokenizer = new StringTokenizer(
                        invoiceDocument.getPurapDocumentIdentifier(), ",");
                while (stringTokenizer.hasMoreElements()) {
                    hashSet.add(stringTokenizer.nextElement().toString());
                }
                hashSet.add(((String) docAttribute.getValue().toString()).toString());
                for (String s : hashSet) {
                    if (purarIdList.equalsIgnoreCase("")) {
                        purarIdList = s;
                    } else {
                        purarIdList = s + "," + purarIdList;
                    }
                }
                invoiceDocument.setPurapDocumentIdentifier(purarIdList);
            } else {
                invoiceDocument
                        .setPurapDocumentIdentifier(((String) docAttribute.getValue().toString()).toString());
            }

        }
        if (name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.INV_TYP_ID)) {
            invoiceDocument.setInvoiceTypeId(((String) docAttribute.getValue().toString()));
        }
        if (name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.INV_VND_NM)) {
            invoiceDocument.setVendorName((String) docAttribute.getValue().toString());
        }
        if (name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.INV_VND_NUM)) {
            invoiceDocument.setVendorNumber((String) docAttribute.getValue().toString());
        }
        if (name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.INV_NUMBER)) {
            invoiceDocument.setInvoiceNumber((String) docAttribute.getValue().toString());
            invoiceDocument.setInvoiceNbr((String) docAttribute.getValue().toString());
        }

        if (name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.INV_DOC_NUM)
                || name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.INV_TYP)
                || name.equalsIgnoreCase(OleSelectConstant.InvoiceSearch.INV_SUB_TYP)) {
            Method getMethod;
            try {
                getMethod = getSetMethod(OLEInvoiceSearchDocument.class, name, new Class[] { String.class });
                getMethod.invoke(invoiceDocument, docAttribute.getValue().toString());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }
    return invoiceDocument;
}