Example usage for java.util Hashtable get

List of usage examples for java.util Hashtable get

Introduction

In this page you can find the example usage for java.util Hashtable get.

Prototype

@SuppressWarnings("unchecked")
public synchronized V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:naming.resources.ProxyDirContext.java

/**
 * Builds a proxy directory context using the given environment.
 *///ww w.j  av  a2s.  c  om
public ProxyDirContext(Hashtable env, DirContext dirContext) {
    this.env = env;
    this.dirContext = dirContext;
    if (dirContext instanceof BaseDirContext) {
        // Initialize parameters based on the associated dir context, like
        // the caching policy.
        if (((BaseDirContext) dirContext).isCached()) {
            cache = Collections.synchronizedMap(new LRUMap(cacheSize));
            cacheTTL = ((BaseDirContext) dirContext).getCacheTTL();
            cacheObjectMaxSize = ((BaseDirContext) dirContext).getCacheObjectMaxSize();
        }
    }
    hostName = (String) env.get(HOST);
    contextName = (String) env.get(CONTEXT);
}

From source file:edu.eurac.commul.pepperModules.mmax2.Salt2MMAX2Mapper.java

private SaltExtendedMarkable getSContainerMarkable(Object sElem, String schemeName, String span, String sName,
        String sId, String containedId, String containedScheme) {
    if (!this.sContainerMarkables.containsKey(sElem)) {
        this.sContainerMarkables.put(sElem, new Hashtable<Scheme, SaltExtendedMarkableContainer>());
    }/*from  w ww  . j  av  a2s  . c  o  m*/
    Hashtable<Scheme, SaltExtendedMarkableContainer> associatedMarkables = this.sContainerMarkables.get(sElem);

    SaltExtendedMarkableContainer containerMarkable = null;
    Scheme associatedScheme = getScheme(schemeName);
    if (!associatedMarkables.containsKey(associatedScheme)) {
        SaltExtendedMarkableFactory markableFactory = this.document.getFactory()
                .getMarkableFactory(associatedScheme);
        if (markableFactory == null) {
            markableFactory = new SaltExtendedMarkableFactory(associatedScheme, this.documentBuilder);
            this.document.getFactory().addMarkableFactory(markableFactory);
        }
        containerMarkable = markableFactory.newMarkableContainer(getNewId(), span,
                new ArrayList<MarkableAttribute>(), SaltExtendedMmax2Infos.SALT_INFO_TYPE_SCONTAINER, sName,
                sId, containedId, containedScheme);
        associatedMarkables.put(associatedScheme, containerMarkable);
        document.addMarkable(containerMarkable);
    } else {
        containerMarkable = associatedMarkables.get(associatedScheme);
    }

    return containerMarkable;
}

From source file:hu.sztaki.lpds.pgportal.portlets.workflow.EasyWorkflowPortlet.java

/**
 * Detailed displaying of a worflow instance data
 *//* ww  w  .  ja v  a2s  .  c  o m*/
public void doInstanceDetails(ActionRequest request, ActionResponse response) throws PortletException {
    String workflow = "" + request.getParameter("workflow");
    doDetails(request, response);
    request.getPortletSession().setAttribute("cworkflow", request.getParameter("workflow"));
    request.getPortletSession().setAttribute("detailsruntime", request.getParameter("rtid"));
    //        System.out.println("!!!!doInstanceDetails rtid:"+request.getParameter("rtid")+" workflow:"+workflow);
    request.setAttribute("rtid", PortalCacheService.getInstance().getUser(request.getRemoteUser())
            .getWorkflow(workflow).getRuntime(request.getParameter("rtid")).getText());
    request.setAttribute("workflow",
            PortalCacheService.getInstance().getUser(request.getRemoteUser()).getWorkflow(workflow));

    if (PortalCacheService.getInstance().getUser(request.getRemoteUser())
            .getWorkflow(request.getParameter("workflow")).getRuntime(request.getParameter("rtid"))
            .getJobsStatus().equals(new Hashtable())) {
        Hashtable prp = new Hashtable();
        Vector v = new Vector();
        prp.put("url", PortalCacheService.getInstance().getUser(request.getRemoteUser())
                .getWorkflow(request.getParameter("workflow")).getWfsID());
        ServiceType st = InformationBase.getI().getService("wfs", "portal", prp, new Vector());
        try {
            PortalWfsClient pc = (PortalWfsClient) Class.forName(st.getClientObject()).newInstance();
            pc.setServiceURL(st.getServiceUrl());
            pc.setServiceID(st.getServiceID());
            ComDataBean cmb = new ComDataBean();
            cmb.setPortalID(PropertyLoader.getInstance().getProperty("service.url"));
            cmb.setUserID(request.getRemoteUser());
            cmb.setWorkflowID(request.getParameter("workflow"));
            cmb.setWorkflowRuntimeID(request.getParameter("rtid"));
            v = pc.getWorkflowInstanceJobs(cmb);
            JobStatusBean tmp;
            for (int i = 0; i < v.size(); i++) {
                tmp = (JobStatusBean) v.get(i);
                PortalCacheService.getInstance().getUser(request.getRemoteUser())
                        .getWorkflow(request.getParameter("workflow")).getRuntime(request.getParameter("rtid"))
                        .addJobbStatus(tmp.getJobID(), "" + tmp.getPID(), "" + tmp.getStatus(),
                                tmp.getResource(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    Hashtable jobs = PortalCacheService.getInstance().getUser(request.getRemoteUser())
            .getWorkflow(request.getParameter("workflow")).getRuntime(request.getParameter("rtid"))
            .getCollectionJobsStatus();
    //System.out.println("---doInstanceDetails:"+jobs);
    int sinit = 0;
    int sproc = 0;
    int sfinalok = 0;
    int sfinalerr = 0;
    Enumeration jobskeys = jobs.keys();
    while (jobskeys.hasMoreElements()) {//iterate jobs
        Hashtable job = (Hashtable) jobs.get(jobskeys.nextElement());

        Enumeration jkeys = job.keys();
        while (jkeys.hasMoreElements()) {//paramjobs
            try {
                String jobstatus = "" + jkeys.nextElement();//job statuses from the given gob
                int ijobStatus = Integer.parseInt(jobstatus);
                //System.out.println("jobstatus:"+jobstatus+" job.get(jobstatus):"+job.get(ijobStatus));
                int jobstatusnbr = Integer.parseInt("" + job.get(ijobStatus));//?db

                if (jobstatus.equals("1") || jobstatus.equals("28")) {//init or suspended
                    sinit += jobstatusnbr;
                } else if (jobstatus.equals("6") || jobstatus.equals("21") || jobstatus.equals("25")) {
                    sfinalok += jobstatusnbr;
                } else if (jobstatus.equals("7")) {
                    sfinalerr += jobstatusnbr;
                } else {
                    sproc += jobstatusnbr;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    int sum = sinit + sproc + sfinalok + sfinalerr;
    double psinit = ((double) sinit / sum) * 100;
    java.text.DecimalFormat fmt = new java.text.DecimalFormat("#");
    request.setAttribute("sinit", sinit);
    request.setAttribute("sproc", sproc);
    request.setAttribute("sfinalok", sfinalok);
    request.setAttribute("sfinalerr", sfinalerr);
    request.setAttribute("psinit", fmt.format(((double) sinit / sum) * 100));
    request.setAttribute("psproc", fmt.format(((double) sproc / sum) * 100));
    request.setAttribute("psfinalok", fmt.format(((double) sfinalok / sum) * 100));
    request.setAttribute("psfinalerr", fmt.format(((double) sfinalerr / sum) * 100));
    request.setAttribute("ssum", sum);
    //        System.out.println("---doInstanceDetails:" + sinit + "+" + sproc + "+" + sfinalok+ "+" + sfinalerr+"="+sum+" --- init%:"+psinit+"");

    request.setAttribute("instJobList",
            PortalCacheService.getInstance().getUser(request.getRemoteUser())
                    .getWorkflow(request.getParameter("workflow")).getRuntime(request.getParameter("rtid"))
                    .getCollectionJobsStatus());

}

From source file:com.netscape.admin.certsrv.Console.java

/**
  * initialize the ldap connection according to all the information. If the directory server is
  * not running, try to start the directory server.
  */*from www.  j  a  v a 2  s  . com*/
  * @param info   ConsoleInfo which store the global information.
  * @return   true if successfull. false otherwise.
  */
private final int LDAPinitialization(ConsoleInfo info) {
    // Set DS information;

    Hashtable<String, String> ht = _info.getAuthenticationValues();

    String param;

    // set up configuration data base information

    if ((param = (ht.get("SIE"))) != null)
        _adminServerSIE = param;
    else
        Debug.println("Console:authenticate_user():SIE not found");

    if ((param = (ht.get("ldapHost"))) != null)
        info.setHost(param);
    else
        Debug.println("Console:authenticate_user():ldapHost not found");

    if ((param = (ht.get("ldapPort"))) != null)
        info.setPort(Integer.parseInt(param));
    else
        Debug.println("Console:authenticate_user():ldapPort not found");

    if ((param = (ht.get("ldapBaseDN"))) != null)
        info.setBaseDN(param);
    else
        Debug.println("Console:authenticate_user():ldapBaseDN not found");

    param = (ht.get("ldapSecurity"));
    boolean fLdapSecurity = false;
    if ((param != null) && (param.equals("on"))) {
        info.put("ldapSecurity", "on");
        fLdapSecurity = true;
    } else {
        info.put("ldapSecurity", "off");
    }

    // Need to open an LDAPConnection for the ConsoleInfo object.

    try {
        LDAPConnection ldapConnection = createLDAPConnection(info);
        if (ldapConnection == null) {
            return LDAP_INIT_BIND_FAIL;
        }
        info.setLDAPConnection(ldapConnection);

    } catch (LDAPException le) {

        // DT 5/19/98 Prompt user to restart the registry DS if ldc.connect() failed
        String dsURL = (fLdapSecurity ? "ldaps" : "ldap") + "://" + info.getHost() + ":" + info.getPort();
        String msg = MessageFormat.format(_resource.getString("error", "connectDS"),
                new Object[] { dsURL, le.getMessage() });
        Debug.println("Console:authenticate_user():" + msg);

        if (_dsHasBeenRestarted) {
            // DS has already been restarted, return an error
            JOptionPane.showMessageDialog(com.netscape.management.client.console.SplashScreen.getInstance(),
                    msg, _resource.getString("error", "title"), JOptionPane.ERROR_MESSAGE);
            ModalDialogUtil.sleep();
            return LDAP_INIT_FAILED;
        }

        Object[] choices = { _resource.getString("error", "restartDSButton"),
                _resource.getString("error", "cancelButton") };
        Object[] msgs = { msg, " ", _resource.getString("error", "restartDSMessage"), " " };

        int selection = JOptionPane.showOptionDialog(
                com.netscape.management.client.console.SplashScreen.getInstance(), msgs,
                _resource.getString("error", "inittitle"), JOptionPane.DEFAULT_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);

        if (selection == 1)
            System.exit(1); // cancel

        // Pop a new login dialog, but this is for the Registry DS AS

        /*
                    RestartDialog rd = new RestartDialog(_frame);
                    rd.setDialogLocation(_frame);
                    rd.showModal();
                    if (rd.isCancel())
        System.exit(0);
                    _splashScreen.toFront();
                
                    if (!restartDirectoryServer(rd.getUsername(),
            rd.getPassword(), rd.getURL())) {
        return LDAP_INIT_FAILED;
                    } else {
        msg = _resource.getString("info","restartDS");
        JOptionPane.showMessageDialog(
                com.netscape.management.client.console.SplashScreen.getInstance(), msg,
                _resource.getString("info","restartDSTitle"),
                JOptionPane.INFORMATION_MESSAGE);
        _dsHasBeenRestarted = true;
        return LDAP_INIT_DS_RESTART;
                    }
        */
    }

    // set up user data base information
    // If config DS is unaccessable when authenticate CGI is called, the CGI returns ? for UserDirectory
    if ((param = (ht.get("UserDirectory"))) != null && !param.equals("?")) {
        // this caused I18n problem - param=param.toLowerCase();
        LDAPConnection ldc = null;
        boolean fSSL = false;
        String sHost = info.getHost();
        int iPort = info.getPort();
        String sBaseDN = info.getBaseDN();
        int iStartSearch = 7;
        if (param.startsWith("ldaps://")) {
            fSSL = true;
            iStartSearch = 8;
        }

        int iNextSlash = param.indexOf('/', 8);
        int iNextColon = param.indexOf(':', 8);
        int iNextSpace = param.indexOf(' ', 8); //for failover list

        // if failover list, use the first host and port in the list

        if ((iNextSlash > iNextColon) && (iNextColon != (-1))) {
            // has a port number
            if ((iNextSpace != (-1)) && (iNextSpace < iNextSlash)) {
                // failover list
                iPort = Integer.parseInt(param.substring(iNextColon + 1, iNextSpace));
            } else {
                iPort = Integer.parseInt(param.substring(iNextColon + 1, iNextSlash));
            }
            sHost = param.substring(iStartSearch, iNextColon);
        } else {
            sHost = param.substring(iStartSearch, iNextSlash);
        }

        sBaseDN = param.substring(iNextSlash + 1);
        info.setUserHost(sHost);
        info.setUserPort(iPort);
        info.setUserBaseDN(sBaseDN);

        if (fSSL) {
            ldc = new KingpinLDAPConnection(UtilConsoleGlobals.getLDAPSSLSocketFactory(),
                    info.getAuthenticationDN(), info.getAuthenticationPassword());
        } else {
            ldc = new KingpinLDAPConnection(info.getAuthenticationDN(), info.getAuthenticationPassword());
        }

        try {
            ldc.connect(info.getUserHost(), info.getUserPort());
            ldc.authenticate(LDAPUtil.LDAP_VERSION, info.getAuthenticationDN(),
                    info.getAuthenticationPassword());
        } catch (Exception e) {
            // catch no user exception
            Debug.println("Console: cannot connect to the user database");
        }
        info.setUserLDAPConnection(ldc);
    } else
        Debug.println("Console.authenticate_user():UserDirectory value not found");

    return LDAP_INIT_OK;
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.hl7.HL7MapToLexGrid.java

void loadRelations(CodingScheme csclass, String driver, Hashtable<Integer, Entity> internalId2codeMap) {
    Connection connection = null;
    ResultSet association_results = null;
    try {//from w w w  .j  av a  2s  .c  o m
        connection = DBUtility.connectToDatabase(accessConnectionString, driver, null, null);
        PreparedStatement relationship_ps = connection.prepareStatement(
                "SELECT distinct relationCode, sourceInternalId, targetInternalId FROM VCS_concept_relationship");
        association_results = relationship_ps.executeQuery();

        while (association_results.next()) {
            int source = association_results.getInt("sourceInternalId");
            int target = association_results.getInt("targetInternalId");
            String association = association_results.getString("relationCode");
            AssociationPredicate parent_association = (AssociationPredicate) RelationsUtil
                    .resolveAssociationPredicates(csclass, association).get(0);
            Entity sourceEntity = internalId2codeMap.get(Integer.valueOf(source));
            Entity targetEntity = internalId2codeMap.get(Integer.valueOf(target));

            if (sourceEntity != null && targetEntity != null) {
                AssociationSource ai = new AssociationSource();
                ai.setSourceEntityCode(sourceEntity.getEntityCode());
                ai.setSourceEntityCodeNamespace(csclass.getCodingSchemeName());
                ai = RelationsUtil.subsume(parent_association, ai);

                AssociationTarget at = new AssociationTarget();
                at.setTargetEntityCode(targetEntity.getEntityCode());
                at.setTargetEntityCodeNamespace(csclass.getCodingSchemeName());
                at = RelationsUtil.subsume(ai, at);
            }
        }
    } catch (SQLException e) {
        messages_.error("Failed while getting HL7 relations from the RIM database", e);
        e.printStackTrace();
    } catch (Exception e) {
        messages_.debug(
                "Error occurred while connecting to the RIM database. " + accessConnectionString + driver);
        e.printStackTrace();
    } finally {
        try {
            association_results.close();
            connection.close();
        } catch (SQLException e) {
            messages_.debug("An error occurred while closing the MS Access connections.");
            e.printStackTrace();
        }
    }
}

From source file:com.eleybourn.bookcatalogue.utils.Utils.java

/**
 * Remove series from the list where the names are the same, but one entry has a null or empty position.
 * eg. the followig list should be processed as indicated:
 * //  w w  w . ja  va 2 s  . c  o  m
 * fred(5)
 * fred <-- delete
 * bill <-- delete
 * bill <-- delete
 * bill(1)
 * 
 * @param list
 */
public static boolean pruneSeriesList(ArrayList<Series> list) {
    ArrayList<Series> toDelete = new ArrayList<Series>();
    Hashtable<String, Series> index = new Hashtable<String, Series>();

    for (Series s : list) {
        final boolean emptyNum = s.num == null || s.num.trim().equals("");
        final String lcName = s.name.trim().toLowerCase();
        final boolean inNames = index.containsKey(lcName);
        if (!inNames) {
            // Just add and continue
            index.put(lcName, s);
        } else {
            // See if we can purge either
            if (emptyNum) {
                // Always delete series with empty numbers if an equally or more specific one exists
                toDelete.add(s);
            } else {
                // See if the one in 'index' also has a num
                Series orig = index.get(lcName);
                if (orig.num == null || orig.num.trim().equals("")) {
                    // Replace with this one, and mark orig for delete
                    index.put(lcName, s);
                    toDelete.add(orig);
                } else {
                    // Both have numbers. See if they are the same.
                    if (s.num.trim().toLowerCase().equals(orig.num.trim().toLowerCase())) {
                        // Same exact series, delete this one
                        toDelete.add(s);
                    } else {
                        // Nothing to do: this is a different series position                     
                    }
                }
            }
        }
    }

    for (Series s : toDelete)
        list.remove(s);

    return (toDelete.size() > 0);

}

From source file:edu.ku.brc.specify.tasks.ExpressSearchTask.java

public synchronized void exectionDone(final SQLExecutionProcessor process, final ResultSet resultSet) {
    if (!sqlHasResults) {
        try {//  w w  w  . ja  v  a  2  s  . c o m
            sqlHasResults = resultSet.first();

        } catch (SQLException ex) {
            ex.printStackTrace();
            edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ExpressSearchTask.class, ex);
        }
    }
    sqlProcessorList.remove(process);

    Object[] data = (Object[]) process.getData();
    if (data != null) {
        if (data.length == 3) {
            SearchTableConfig searchTableConfig = (SearchTableConfig) data[0];
            ExpressSearchResultsPaneIFace esrPane = (ExpressSearchResultsPaneIFace) data[1];
            String searchTerm = (String) data[2];

            Hashtable<String, ExpressResultsTableInfo> idToTableInfoHash = ExpressSearchConfigCache
                    .getSearchIdToTableInfoHash();
            Hashtable<String, List<ExpressResultsTableInfo>> joinIdToTableInfohash = ExpressSearchConfigCache
                    .getJoinIdToTableInfoHash();
            Hashtable<String, QueryForIdResultsSQL> resultsForJoinsHash = new Hashtable<String, QueryForIdResultsSQL>();

            try {
                if (resultSet.next()) {
                    String searchIdStr = Integer.toString(searchTableConfig.getTableInfo().getTableId());
                    ExpressResultsTableInfo tblInfo = idToTableInfoHash.get(searchIdStr);
                    if (tblInfo == null) {
                        throw new RuntimeException("Bad id from search[" + searchIdStr + "]");
                    }

                    SearchConfig config = SearchConfigService.getInstance().getSearchConfig();

                    int cnt = 0;
                    do {
                        if (cnt < RESULTS_THRESHOLD) {
                            collectResults(config, tblInfo.getTableId(), searchTerm, resultSet, null,
                                    joinIdToTableInfohash, resultsForJoinsHash);
                        }
                        cnt++;
                    } while (resultSet.next());

                    //System.err.println("SQLExecutionProcessor: "+cnt);

                    if (cnt >= RESULTS_THRESHOLD) {
                        String reason = String.format(
                                getResourceString("ExpressSearchTask.MAX_SEARCH_RESULTS_EXCEEDED"),
                                RESULTS_THRESHOLD, cnt);
                        if (searchWarningsResults == null) {
                            searchWarningsResults = new SIQueryForIdResults();
                            searchWarningsResults.addReason(searchTableConfig, reason);
                            displayResults(esrPane, searchWarningsResults, resultsForJoinsHash);

                        } else {
                            searchWarningsResults.addReason(searchTableConfig, reason);
                        }
                    }

                    if (resultsForJoinsHash.size() > 0) {
                        QueryForIdResultsSQL queryResults = new QueryForIdResultsSQL(searchIdStr, null, tblInfo,
                                searchTableConfig.getDisplayOrder(), searchTerm);
                        displayResults(esrPane, queryResults, resultsForJoinsHash);
                    }
                }
            } catch (SQLException ex) {
                edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ExpressSearchTask.class, ex);
                ex.printStackTrace();
            }

        }
    }
}

From source file:edu.ku.brc.specify.tools.schemalocale.SchemaLocalizerXMLHelper.java

/**
 * @param discipline//from ww  w .j a v a  2s.  c o m
 * @param extFile
 * @param useCurrentLocaleOnly
 * @return
 */
@SuppressWarnings("unchecked")
protected Vector<DisciplineBasedContainer> load(final String discipline, final File extFile,
        final boolean useCurrentLocaleOnly) {
    Vector<DisciplineBasedContainer> containers = null;

    XStream xstream = new XStream();
    configXStream(xstream);

    try {
        String fullPath = (discipline != null ? (discipline + File.separator) : "") + fileName[schemaType];
        File file = extFile != null ? extFile : XMLHelper.getConfigDir(fullPath);
        if (file.exists()) {
            if (discipline == null) {
                inputFile = file;
            }

            InputStreamReader inpStrmReader = new InputStreamReader(new FileInputStream(file), "UTF8");
            containers = (Vector<DisciplineBasedContainer>) xstream.fromXML(inpStrmReader);

            if (discipline != null) {
                return containers;
            }
        }

        if (useCurrentLocaleOnly && containers != null && containers.size() > 0) {
            String language = Locale.getDefault().getLanguage();
            addMissingTranslations(language, containers);
            stripToSingleLocale(language, containers);
        }

        // remove non-english locales
        /*if (false)
        {
        if (discipline == null)
        {
            for (DisciplineBasedContainer dbc : containers)
            {
                for (SpLocaleContainerItem sci : dbc.getItems())
                {
                    for (SpLocaleItemStr n : new Vector<SpLocaleItemStr>(sci.getNames()))
                    {
                        if (!n.getLanguage().equals("en"))
                        {
                            sci.getNames().remove(n);
                            changesMadeDuringStartup = true;
                        }
                    }
                    for (SpLocaleItemStr d : new Vector<SpLocaleItemStr>(sci.getDescs()))
                    {
                        if (!d.getLanguage().equals("en"))
                        {
                            sci.getDescs().remove(d);
                            changesMadeDuringStartup = true;
                        }
                    }
                }
                        
                for (SpLocaleItemStr n : new Vector<SpLocaleItemStr>(dbc.getNames()))
                {
                    if (!n.getLanguage().equals("en"))
                    {
                        dbc.getNames().remove(n);
                        changesMadeDuringStartup = true;
                    }
                }
                for (SpLocaleItemStr d : new Vector<SpLocaleItemStr>(dbc.getDescs()))
                {
                    if (!d.getLanguage().equals("en"))
                    {
                        dbc.getDescs().remove(d);
                        changesMadeDuringStartup = true;
                    }
                }
            }
        }
        }
                
        if (false)
        {
        if (discipline == null)
        {
            Hashtable<String, Boolean> fieldsToHideHash = new Hashtable<String, Boolean>();
            String[] fields = { "version", 
                    "timestampCreated", 
                    "timestampModified", 
                    "createdByAgent", 
                    "modifiedByAgent", 
                    "collectionMemberId", 
                    "visibility", 
                    "visibilitySetBy"};
                
            for (String fieldName : fields)
            {
                fieldsToHideHash.put(fieldName, true);
            }
                    
            for (DisciplineBasedContainer dbc : containers)
            {
                for (SpLocaleContainerItem sci : dbc.getItems())
                {
                    String nm = sci.getName();
                    if (fieldsToHideHash.get(nm) != null)
                    {
                        sci.setIsHidden(true);
                    } else if (nm.startsWith("yesNo"))
                    {
                        sci.setIsHidden(true);
                    } else if (nm.startsWith("text") && StringUtils.isNumeric(nm.substring(nm.length()-1, nm.length())))
                    {
                        //System.out.println(nm);
                        sci.setIsHidden(true);
                    } else if (nm.startsWith("number") && StringUtils.isNumeric(nm.substring(nm.length()-1, nm.length())))
                    {
                        System.out.println(nm);
                        sci.setIsHidden(true);
                    }
                }
            }
        }
        }*/

        if (containers != null) {
            for (SpLocaleContainer ct : containers) {
                Hashtable<String, Boolean> hash = new Hashtable<String, Boolean>();
                for (SpLocaleContainerItem item : new Vector<SpLocaleContainerItem>(ct.getItems())) {
                    if (hash.get(item.getName()) == null) {
                        hash.put(item.getName(), true);
                    } else {
                        log.debug("Removing Duplicate[" + item.getName() + "]");
                        ct.getItems().remove(item);
                    }
                }
            }

            tableDisplayItems = new Vector<LocalizableJListItem>();
            for (SpLocaleContainer cont : containers) {
                LocalizableJListItem item = new LocalizableJListItem(cont.getName(), cont.getId(), null);
                tableDisplayItems.add(item);
                //System.out.println("["+cont.getName()+"]");
                tableDisplayItemsHash.put(cont.getName(), item);

                tableHash.put(cont.getName(), cont);
            }

            Collections.sort(tableDisplayItems);

            log.info("Syncing with Datamodel.... (ignore errors)");
            changesBuffer.append("<Center><table border=\"1\">");

            String lang = SchemaI18NService.getCurrentLocale().getLanguage();

            discoverLocalesFromData(containers);
            if (availLocales.size() == 1) {
                lang = availLocales.get(0).getLanguage();

            } else {
                Vector<DisplayLocale> list = new Vector<DisplayLocale>();
                for (Locale locale : availLocales) {
                    list.add(new DisplayLocale(locale));
                }
                Collections.sort(list);

                boolean cont = false;
                while (cont) {
                    ToggleButtonChooserDlg<DisplayLocale> dlg = new ToggleButtonChooserDlg<DisplayLocale>(
                            (Dialog) null, "CHOOSE_LOCALE", list, ToggleButtonChooserPanel.Type.RadioButton);
                    dlg.setUseScrollPane(true);
                    dlg.setVisible(true);

                    cont = dlg.isCancelled();
                    if (!cont) {
                        lang = dlg.getSelectedObject().getLocale().getLanguage();
                    }
                }
            }

            log.info("Adding New Tables and fields....");
            for (DBTableInfo ti : tableMgr.getTables()) {
                DisciplineBasedContainer container = (DisciplineBasedContainer) tableHash.get(ti.getName());
                if (container == null) {
                    // OK, table has been Localized, so add it.
                    container = new DisciplineBasedContainer();
                    container.initialize();
                    container.setName(ti.getName());
                    SpLocaleItemStr nameStr = new SpLocaleItemStr();
                    nameStr.initialize();
                    nameStr.setText(UIHelper.makeNamePretty(ti.getShortClassName()));
                    nameStr.setLanguage(lang);
                    container.addName(nameStr);
                    log.info("Adding Table [" + ti.getName() + "]");
                    changesMadeDuringStartup = true;

                    changesBuffer.append("<tr><td align=\"center\">Added</td>");
                    changesBuffer.append("<td align=\"center\">");
                    changesBuffer.append(ti.getName());
                    changesBuffer.append("</td><td>&nbsp;</td></tr>");

                    tableHash.put(container.getName(), container);
                    containers.add(container);

                    LocalizableJListItem jItem = new LocalizableJListItem(container.getName(),
                            container.getId(), null);
                    tableDisplayItems.add(jItem);
                    tableDisplayItemsHash.put(container.getName(), jItem);

                    for (DBFieldInfo fi : ti.getFields()) {
                        SpLocaleContainerItem item = new SpLocaleContainerItem();
                        item.initialize();
                        item.setName(fi.getName());
                        item.setWebLinkName(fi.getWebLinkName());
                        item.setIsRequired(fi.isRequired());
                        item.setIsHidden(fi.isHidden());

                        nameStr = new SpLocaleItemStr();
                        nameStr.initialize();
                        //nameStr.setText(UIHelper.makeNamePretty(fi.getDataClass().getSimpleName()));
                        nameStr.setText(UIHelper.makeNamePretty(fi.getName()));
                        nameStr.setLanguage(lang);
                        item.addName(nameStr);
                        log.info("  Adding Field [" + fi.getName() + "]");
                        changesBuffer.append("<tr><td align=\"center\">Added</td>");
                        changesBuffer.append("<td align=\"center\">&nbsp;</td><td align=\"center\">");
                        changesBuffer.append(fi.getName());
                        changesBuffer.append("</td></tr>");

                        item.setIsRequired(fi.isRequired());

                        container.addItem(item);
                    }

                    for (DBRelationshipInfo ri : ti.getRelationships()) {
                        SpLocaleContainerItem item = new SpLocaleContainerItem();
                        item.initialize();
                        item.setName(ri.getName());
                        item.setIsRequired(false);

                        log.info("  Adding Field [" + ri.getName() + "]");
                        changesBuffer.append("<tr><td align=\"center\">Added</td>");
                        changesBuffer.append("<td align=\"center\">&nbsp;</td><td align=\"center\">");
                        changesBuffer.append(ri.getName());
                        changesBuffer.append("</td></tr>");
                        container.addItem(item);
                    }

                } else {
                    // Look for existing Field
                    for (DBFieldInfo fi : ti.getFields()) {
                        SpLocaleContainerItem item = (SpLocaleContainerItem) container
                                .getItemByName(fi.getName());
                        if (item == null) {
                            item = new SpLocaleContainerItem();
                            item.initialize();
                            item.setName(fi.getName());
                            item.setIsRequired(fi.isRequired());
                            item.setIsHidden(fi.isHidden());

                            SpLocaleItemStr nameStr = new SpLocaleItemStr();
                            nameStr.initialize();
                            nameStr.setText(UIHelper.makeNamePretty(fi.getName()));
                            nameStr.setLanguage(lang);
                            item.addName(nameStr);
                            container.addItem(item);
                            log.info("For Table[" + ti.getName() + "] Adding Field [" + fi.getName() + "]");
                            changesMadeDuringStartup = true;
                            changesBuffer.append("<tr><td align=\"center\">Added</td>");
                            changesBuffer.append(
                                    "<td align=\"center\">" + ti.getName() + "</td><td align=\"center\">");
                            changesBuffer.append(fi.getName());
                            changesBuffer.append("</td></tr>");

                        } else if (doFixNames) {
                            Class<?> cls = fi.getDataClass();
                            if (cls != null) {
                                String name = UIHelper.makeNamePretty(fi.getDataClass().getSimpleName());
                                for (SpLocaleItemStr str : item.getNames()) {
                                    if (name.equals(str.getText())) {
                                        str.setText(UIHelper.makeNamePretty(fi.getName()));

                                        changesMadeDuringStartup = true;
                                        changesBuffer.append("<tr><td align=\"center\">Fixed Name</td>");
                                        changesBuffer.append("<td align=\"center\">" + ti.getName()
                                                + "</td><td align=\"center\">");
                                        changesBuffer.append(fi.getName());
                                        changesBuffer.append("</td></tr>");
                                    }
                                }
                            } else {
                                log.error("Data Class is null for field[" + fi.getColumn() + "]");
                            }
                        } else {
                            //item.setIsRequired(fi.isRequired());
                        }
                    }

                    for (DBRelationshipInfo ri : ti.getRelationships()) {
                        SpLocaleContainerItem item = (SpLocaleContainerItem) container
                                .getItemByName(ri.getName());
                        if (item == null) {
                            item = new SpLocaleContainerItem();
                            item.initialize();
                            item.setName(ri.getName());
                            container.addItem(item);
                            SpLocaleItemStr nameStr = new SpLocaleItemStr();
                            nameStr.initialize();
                            nameStr.setText(UIHelper.makeNamePretty(ri.getName()));
                            nameStr.setLanguage(lang);
                            item.addName(nameStr);

                            log.info("For Table[" + ti.getName() + "] Adding Rel [" + ri.getName() + "]");
                            changesMadeDuringStartup = true;
                            changesBuffer.append("<tr><td align=\"center\">Added</td>");
                            changesBuffer.append(
                                    "<td align=\"center\">" + ti.getName() + "</td><td align=\"center\">");
                            changesBuffer.append(ri.getName());
                            changesBuffer.append("</td></tr>");

                        } else {
                            if (item.getNames().size() == 0) {
                                SpLocaleItemStr nameStr = new SpLocaleItemStr();
                                nameStr.initialize();
                                nameStr.setText(UIHelper.makeNamePretty(ri.getName()));
                                nameStr.setLanguage(lang);
                                item.addName(nameStr);

                                changesMadeDuringStartup = true;
                                changesBuffer.append("<tr><td align=\"center\">Added</td>");
                                changesBuffer.append(
                                        "<td align=\"center\">" + ti.getName() + "</td><td align=\"center\">");
                                changesBuffer.append(ri.getName());
                                changesBuffer.append("</td></tr>");
                            }
                        }
                    }
                }
            }

            log.info("Removing Old Tables and fields....");
            for (SpLocaleContainer container : new Vector<DisciplineBasedContainer>(containers)) {
                DBTableInfo ti = tableMgr.getInfoByTableName(container.getName());
                if (ti == null) {
                    log.info("Removing Table [" + container.getName() + "] from Schema");
                    containers.remove(container);
                    tableHash.remove(container.getName());
                    changesMadeDuringStartup = true;
                    changesBuffer.append("<tr><td align=\"center\">Removed</td>");
                    changesBuffer.append("<td align=\"center\">");
                    changesBuffer.append(container.getName());
                    changesBuffer.append("</td><td>&nbsp;</td></tr>");

                } else {
                    for (LocalizableItemIFace itemIF : new Vector<LocalizableItemIFace>(
                            container.getContainerItems())) {
                        SpLocaleContainerItem item = (SpLocaleContainerItem) itemIF;
                        DBTableChildIFace tblChild = ti.getItemByName(item.getName());
                        if (tblChild == null) {
                            container.removeItem(item);
                            //log.info("For Table["+ti.getName()+"] Removing Rel ["+item.getName()+"]");
                            changesMadeDuringStartup = true;
                            changesBuffer.append("<tr><td align=\"center\" color=\"red\">Removed</td>");
                            changesBuffer.append(
                                    "<td align=\"center\">" + ti.getName() + "</td><td align=\"center\">");
                            changesBuffer.append(item.getName());
                            changesBuffer.append("</td></tr>");
                        }
                    }
                }
            }
            changesBuffer.append("</table>");
        } else {
            log.info("There were no containers for [" + file.getAbsolutePath() + "]");
        }

        // Force the hidden of special fields
        /*if (false)
        {
        String[] fieldsToHide = {"timestampCreated","timestampModified",
                                "createdByAgent","modifiedByAgent","version",
                                "collectionMemberId"};
        Hashtable<String, Boolean> hash = new Hashtable<String, Boolean>();
        for (String fName : fieldsToHide)
        {
            hash.put(fName, Boolean.TRUE);
        }
        for (DBTableInfo ti : tableMgr.getTables())
        {
            DisciplineBasedContainer container = (DisciplineBasedContainer)tableHash.get(ti.getName());
            if (container != null)
            {
                for (SpLocaleContainerItem item : container.getItems())
                {
                    if (hash.get(item.getName()) != null)
                    {
                        item.setIsHidden(Boolean.TRUE);
                    }
                }
            }
        }
        }*/
    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerXMLHelper.class, ex);
        ex.printStackTrace();

    } catch (Exception ex) {
        UIRegistry.showError("There was a problem reading the XML in the file."); // I18N
    }

    return containers;
}

From source file:edu.eurac.commul.pepperModules.mmax2.Salt2MMAX2Mapper.java

private SaltExtendedMarkable mapStruct(SStructure struct) throws MMAX2WrapperException {
    ArrayList<SaltExtendedMarkable> sDomRelMarkableList = new ArrayList<SaltExtendedMarkable>();
    Hashtable<SaltExtendedMarkable, SRelationMapping> sDomRelMarkableHash = new Hashtable<SaltExtendedMarkable, SRelationMapping>();
    ArrayList<String> spans = new ArrayList<String>();
    for (SRelation rel : getDocument().getDocumentGraph().getOutRelations(struct.getId())) {
        if (rel instanceof SDominanceRelation) {
            SDominanceRelation sDomRel = (SDominanceRelation) rel;
            SaltExtendedMarkable sDomRelMarkable = getSRelationMarkable(sDomRel);
            spans.add(sDomRelMarkable.getSpan());
            SRelationMapping validated = matchSRelation(sDomRel);
            sDomRelMarkableList.add(sDomRelMarkable);
            if (validated != null) {
                sDomRelMarkableHash.put(sDomRelMarkable, validated);
            }/*from  w  w w.j  a  v a  2 s.c  o  m*/
        }
    }

    SaltExtendedMarkable markable = createMarkableForSNode(getNewId(), makeSpan(spans), struct,
            SaltExtendedMmax2Infos.SALT_INFO_TYPE_SSTRUCT);

    for (SaltExtendedMarkable sDomRelMarkable : sDomRelMarkableList) {
        if (sDomRelMarkableHash.containsKey(sDomRelMarkable)) {
            SRelationMapping validated = sDomRelMarkableHash.get(sDomRelMarkable);

            SaltExtendedMarkable containerSourceMarkable = getSContainerMarkable(markable,
                    validated.getSourceAssociatedSchemeName(), markable.getSpan(), markable.getSName(),
                    markable.getId(), markable.getId(), markable.getFactory().getScheme().getName());

            addPointerAttribute(containerSourceMarkable, validated.getSourceAssociatedSchemeName(),
                    validated.getTargetAssociatedSchemeName(), validated.getPointedAssociatedAttributeName(),
                    sDomRelMarkable.getAttribute("id_target").getValue());
            sDomRelMarkable.removeAttribute(sDomRelMarkable.getAttribute("id_target"));

            addFreetextAttribute(sDomRelMarkable, SaltExtendedMmax2Infos.SALT_INFO_TYPE_SDOMINANCE_REL,
                    "struct_attr", validated.getPointedAssociatedAttributeName());
            addFreetextAttribute(sDomRelMarkable, SaltExtendedMmax2Infos.SALT_INFO_TYPE_SDOMINANCE_REL,
                    "struct_scheme", validated.getSourceAssociatedSchemeName());
            addFreetextAttribute(sDomRelMarkable, SaltExtendedMmax2Infos.SALT_INFO_TYPE_SDOMINANCE_REL,
                    "struct", containerSourceMarkable.getId());
        } else {
            addPointerAttribute(sDomRelMarkable, SaltExtendedMmax2Infos.SALT_INFO_TYPE_SDOMINANCE_REL,
                    SaltExtendedMmax2Infos.SALT_INFO_TYPE_SSTRUCT, "struct", markable.getId());
        }
    }

    return markable;
}

From source file:edu.ku.brc.specify.conversion.ConvertTaxonHelper.java

/**
 * Converts the taxonomy tree definition from the old taxonomicunittype table to the new table
 * pair: TaxonTreeDef & TaxonTreeDefItems.
 * //from   ww  w .j  ava2  s  .  c om
 * @param taxonomyTypeId the tree def id in taxonomicunittype
 * @return the TaxonTreeDef object
 * @throws SQLException
 */
public void convertTaxonTreeDefinition(final CollectionInfo colInfo) {
    if (!colInfo.isInUse()) {
        return;
    }

    TaxonTreeDef taxonTreeDef = newTaxonInfoHash.get(colInfo.getTaxonNameId());
    if (taxonTreeDef != null) {
        colInfo.setTaxonTreeDef(taxonTreeDef);
        return;
    }

    Integer oldTaxonRootId = colInfo.getTaxonNameId();
    Integer taxonomyTypeId = colInfo.getTaxonomyTypeId();

    try {
        Statement st = oldDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

        taxonTreeDef = new TaxonTreeDef();
        taxonTreeDef.initialize();

        String sql = "SELECT TaxonomyTypeName, KingdomID FROM taxonomytype WHERE TaxonomyTypeID = "
                + taxonomyTypeId;
        log.debug(sql);
        ResultSet rs = st.executeQuery(sql);
        rs.next();
        String taxonomyTypeName = rs.getString(1);
        int kingdomID = rs.getInt(2);
        rs.close();

        taxonTreeDef.setName(taxonomyTypeName + " taxonomy tree");
        taxonTreeDef.setRemarks("Tree converted from " + oldDBName);
        taxonTreeDef.setFullNameDirection(TreeDefIface.FORWARD);

        sql = String.format(
                "SELECT RankID, RankName, RequiredParentRankID, TaxonomicUnitTypeID FROM taxonomicunittype "
                        + "WHERE TaxonomyTypeID = %d AND (Kingdom = %d  OR RankID = 0) ORDER BY RankID",
                taxonomyTypeId, kingdomID);
        log.debug(sql);
        rs = st.executeQuery(sql);

        Hashtable<Integer, Integer> rankId2TxnUntTypId = new Hashtable<Integer, Integer>();
        int rank;
        String name;
        int requiredRank;

        Vector<TaxonTreeDefItem> items = new Vector<TaxonTreeDefItem>();
        Vector<Integer> enforcedRanks = new Vector<Integer>();

        while (rs.next()) {
            rank = rs.getInt(1);
            name = rs.getString(2);
            requiredRank = rs.getInt(3);

            int taxUnitTypeId = rs.getInt(4);

            if (StringUtils.isEmpty(name) || (rank > 0 && requiredRank == 0)) {
                continue;
            }

            if (rankId2TxnUntTypId.get(rank) != null) {
                String msg = String.format(
                        "Old TreeDef has two of the same Rank %d, throwing it out.\n\nYou must fix this before proceeding.",
                        rank);
                tblWriter.logError(msg);
                log.debug(msg);
                UIRegistry.displayErrorDlg(msg);
                System.exit(0);
            }
            rankId2TxnUntTypId.put(rank, taxUnitTypeId);

            log.debug(rank + "  " + name + "  TaxonomicUnitTypeID: " + taxUnitTypeId);

            TaxonTreeDefItem ttdi = new TaxonTreeDefItem();
            ttdi.initialize();
            ttdi.setName(name);
            ttdi.setFullNameSeparator(" ");
            ttdi.setRankId(rank);
            ttdi.setTreeDef(taxonTreeDef);
            taxonTreeDef.getTreeDefItems().add(ttdi);

            ttdi.setIsInFullName(rank >= TaxonTreeDef.GENUS);

            // setup the parent/child relationship
            if (items.isEmpty()) {
                ttdi.setParent(null);
            } else {
                ttdi.setParent(items.lastElement());
            }
            items.add(ttdi);
            enforcedRanks.add(requiredRank);
        }
        rs.close();

        for (TaxonTreeDefItem i : items) {
            i.setIsEnforced(enforcedRanks.contains(i.getRankId()));
        }

        try {
            Session session = HibernateUtil.getNewSession();
            Transaction trans = session.beginTransaction();
            session.save(taxonTreeDef);
            trans.commit();
            session.close();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }

        IdMapperMgr idMapperMgr = IdMapperMgr.getInstance();
        IdMapperIFace tutMapper = idMapperMgr.get("TaxonomicUnitType", "TaxonomicUnitTypeID");
        IdMapperIFace taxonomyTypeMapper = idMapperMgr.get("TaxonomyType", "TaxonomyTypeID");

        //tutMapper.reset();

        //if (taxonomyTypeMapper.get(taxonomyTypeId) == null)
        //{
        taxonomyTypeMapper.put(taxonomyTypeId, taxonTreeDef.getId());
        //}

        for (TaxonTreeDefItem ttdi : taxonTreeDef.getTreeDefItems()) {
            int ttdiId = rankId2TxnUntTypId.get(ttdi.getRankId());
            log.debug("Mapping " + ttdiId + " -> " + ttdi.getId() + "  RankId: " + ttdi.getRankId());
            tutMapper.put(ttdiId, ttdi.getId());
        }

        newTaxonInfoHash.put(oldTaxonRootId, taxonTreeDef);

        CollectionInfo ci = getCIByTaxonTypeId(taxonomyTypeId);
        ci.setTaxonTreeDef(taxonTreeDef);

        taxonTreeDefHash.put(taxonomyTypeId, taxonTreeDef);
        log.debug("Hashing taxonomyTypeId: " + taxonomyTypeId + " ->  taxonTreeDefId:" + taxonTreeDef.getId());

    } catch (SQLException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}