Example usage for java.util Vector remove

List of usage examples for java.util Vector remove

Introduction

In this page you can find the example usage for java.util Vector remove.

Prototype

public synchronized E remove(int index) 

Source Link

Document

Removes the element at the specified position in this Vector.

Usage

From source file:com.concursive.connect.web.modules.wiki.jobs.WikiExporterJob.java

public void execute(JobExecutionContext context) throws JobExecutionException {
    LOG.debug("Starting job...");
    SchedulerContext schedulerContext = null;
    Connection db = null;//from   w  w w. jav  a 2s  . com
    try {
        schedulerContext = context.getScheduler().getContext();
        ApplicationPrefs prefs = (ApplicationPrefs) schedulerContext.get("ApplicationPrefs");
        String fs = System.getProperty("file.separator");
        db = SchedulerUtils.getConnection(schedulerContext);
        Vector exportList = (Vector) schedulerContext.get(WIKI_EXPORT_ARRAY);
        Vector availableList = (Vector) schedulerContext.get(WIKI_AVAILABLE_ARRAY);
        while (exportList.size() > 0) {
            WikiExportBean bean = (WikiExportBean) exportList.get(0);
            LOG.debug("Exporting a wiki (" + bean.getWikiId() + ")...");
            User user = UserUtils.loadUser(bean.getUserId());
            if (user == null) {
                user = UserUtils.createGuestUser();
            }
            // Load the project
            Project thisProject = new Project(db, bean.getProjectId());
            // Load the wiki
            Wiki wiki = new Wiki(db, bean.getWikiId(), thisProject.getId());
            // See if a recent export is already available
            long currentDate = System.currentTimeMillis();
            String destDir = prefs.get("FILELIBRARY") + user.getGroupId() + fs + "wiki" + fs
                    + DateUtils.getDatePath(new Date(currentDate));
            File destPath = new File(destDir);
            destPath.mkdirs();
            String filename = "wiki-" + bean.getWikiId() + "-" + bean.getIncludeTitle() + "-"
                    + bean.getFollowLinks() + "-"
                    + WikiUtils.getLatestModifiedDate(wiki, bean.getFollowLinks(), db).getTime();
            File exportFile = new File(destDir + filename);
            WikiExportBean existingBean = getExisting(exportFile, availableList);
            if (existingBean != null) {
                if (existingBean.getUserId() == bean.getUserId()) {
                    // This user already has a valid file ready so a new record isn't needed
                    LOG.debug("Exported file already exists (" + existingBean.getWikiId()
                            + ") and was requested by this user");
                } else {
                    // Tell the new bean the existing bean's details which another user ran
                    LOG.debug("Exported file already exists (" + existingBean.getWikiId()
                            + ") and will be reused for this user");
                    bean.setExportedFile(existingBean.getExportedFile());
                    availableList.add(bean);
                }
            } else {
                // No existing PDF exists so export to PDF
                if (exportFile.exists()) {
                    LOG.debug("Found the requested file in the FileLibrary (" + wiki.getId() + ")...");
                } else {
                    LOG.debug("Generating a new file for wiki (" + wiki.getId() + ")...");
                    // Load wiki image library dimensions (cache in future)
                    HashMap<String, ImageInfo> imageList = WikiUtils.buildImageInfo(db, wiki.getProjectId());
                    // Use a context to hold a bunch of stuff
                    WikiPDFContext pdfContext = new WikiPDFContext(thisProject, wiki, exportFile, imageList,
                            prefs.get("FILELIBRARY"), bean);
                    // Execute the export
                    WikiPDFUtils.exportToFile(pdfContext, db);
                }
                bean.setExportedFile(exportFile);
                bean.setFileSize(exportFile.length());
                availableList.add(bean);
            }
            exportList.remove(0);
        }
    } catch (Exception e) {
        LOG.error("WikiExporterJob Exception", e);
        throw new JobExecutionException(e.getMessage());
    } finally {
        SchedulerUtils.freeConnection(schedulerContext, db);
    }
}

From source file:oscar.oscarEncounter.oscarMeasurements.util.WriteNewMeasurements.java

static private ActionMessages validate(Vector measures, String demographicNo) {
    ActionMessages errors = new ActionMessages();
    try {//from   w  w  w.j  av a2s .c  o m

        EctValidation ectValidation = new EctValidation();
        ResultSet rs;
        boolean valid = true;
        for (int i = 0; i < measures.size(); i++) {
            Hashtable measure = (Hashtable) measures.get(i);
            String inputType = (String) measure.get("type");
            String inputValue = (String) measure.get("value");
            String dateObserved = (String) measure.get("dateObserved");
            String comments = (String) measure.get("comments");
            String mInstrc, regCharExp;
            String regExp = null;
            double dMax = 0;
            double dMin = 0;
            int iMax = 0;
            int iMin = 0;
            org.apache.commons.validator.GenericValidator gValidator = new org.apache.commons.validator.GenericValidator();
            if (GenericValidator.isBlankOrNull(inputValue)) {
                measures.removeElementAt(i);
                i--;
                continue;
            }
            mInstrc = (String) measure.get("measuringInstruction");
            rs = ectValidation.getValidationType(inputType, mInstrc);
            regCharExp = ectValidation.getRegCharacterExp();
            if (rs.next()) {
                dMax = rs.getDouble("maxValue");
                dMin = rs.getDouble("minValue");
                iMax = rs.getInt("maxLength");
                iMin = rs.getInt("minLength");
                regExp = oscar.Misc.getString(rs, "regularExp");
            } else {
                //if type with instruction does not exist
                errors.add(inputType, new ActionMessage("errors.oscarEncounter.Measurements.cannotFindType",
                        inputType, mInstrc));
                valid = false;
                continue;
            }
            rs.close();

            if (!ectValidation.isInRange(dMax, dMin, inputValue)) {
                errors.add(inputType, new ActionMessage("errors.range", inputType, Double.toString(dMin),
                        Double.toString(dMax)));
                valid = false;
            }
            if (!ectValidation.maxLength(iMax, inputValue)) {
                errors.add(inputType, new ActionMessage("errors.maxlength", inputType, Integer.toString(iMax)));
                valid = false;
            }
            if (!ectValidation.minLength(iMin, inputValue)) {
                errors.add(inputType, new ActionMessage("errors.minlength", inputType, Integer.toString(iMin)));
                valid = false;
            }
            if (!ectValidation.matchRegExp(regExp, inputValue)) {
                errors.add(inputType, new ActionMessage("errors.invalid", inputType));
                valid = false;
            }
            if (!ectValidation.isValidBloodPressure(regExp, inputValue)) {
                errors.add(inputType, new ActionMessage("error.bloodPressure"));
                valid = false;
            }
            if (!ectValidation.isDate(dateObserved) && inputValue.compareTo("") != 0) {
                errors.add(inputType, new ActionMessage("errors.invalidDate", inputType));
                valid = false;
            }

            if (!valid)
                continue;
            inputValue = org.apache.commons.lang.StringEscapeUtils.escapeSql(inputValue);
            inputType = org.apache.commons.lang.StringEscapeUtils.escapeSql(inputType);
            mInstrc = org.apache.commons.lang.StringEscapeUtils.escapeSql(mInstrc);
            comments = org.apache.commons.lang.StringEscapeUtils.escapeSql(comments);

            //Find if the same data has already been entered into the system
            String sql = "SELECT * FROM measurements WHERE demographicNo='" + demographicNo
                    + "' AND dataField='" + inputValue + "' AND measuringInstruction='" + mInstrc
                    + "' AND comments='" + comments + "' AND dateObserved='" + dateObserved + "'";
            rs = DBHandler.GetSQL(sql);
            if (rs.next()) {
                measures.remove(i);
                i--;
                continue;
            }
        }
    } catch (SQLException sqe) {
        MiscUtils.getLogger().error("Error", sqe);
    }
    return errors;
}

From source file:org.kepler.kar.KARFile.java

/**
 * Here we go through all the KAREntries and call the open method of the
 * appropriate KAREntryHandlers. It is assumed that cacheKARContents() has
 * been called at some point before openKAR() In other words everything in
 * the kar is already cached when calling the open() method of the
 * KAREntryHandlers./*from   w  w  w  .  j  a  v  a2  s  .co  m*/
 * 
 * Note: There is some issue with having this method here, since it is
 * really a gui specific function it probably does not belong here in the
 * core module.
 * 
 * @param tableauFrame
 * @param forceOpen
 * @throws Exception
 * @returns true if at least one of the entries in the KAR was opened
 */
public boolean openKARContents(TableauFrame tableauFrame, boolean forceOpen) throws Exception {
    if (isDebugging)
        log.debug("openKAR: " + this.toString());

    if (!forceOpen && !isOpenable()) {
        return false;
    }

    try {

        /**
         * Loop through the kar entries and call the open method of the
         * appropriate KAREntryHandler
         */
        Vector<KAREntry> unopenedEntries = (Vector<KAREntry>) karEntries();
        Hashtable<KeplerLSID, KAREntry> openedEntries = new Hashtable<KeplerLSID, KAREntry>();

        // keep cycling through the unopened entries until the list is empty
        while (unopenedEntries.size() > 0) {

            // keep track of the entries that were opened during this pass
            Vector<KAREntry> openedThisPass = new Vector<KAREntry>(unopenedEntries.size());

            // cycle through all of the remaining, unopened entries
            for (KAREntry entry : unopenedEntries) {
                if (isDebugging) {
                    log.debug(entry.getName());
                }

                // get the dependency list for this entry
                List<KeplerLSID> depList = entry.getLsidDependencies();

                if (depList.size() == 0) {
                    // if there are no dependencies we just open it up
                    boolean success = open(entry, tableauFrame);
                    if (success) {
                        openedEntries.put(entry.getLSID(), entry);
                        openedThisPass.add(entry);
                        break;
                    }
                    if (isDebugging)
                        log.debug(success);
                } else {
                    // if there are dependencies then we check to make sure
                    // that all of the dependencies have already been opened
                    boolean allDependenciesHaveBeenOpened = true;
                    for (KeplerLSID lsid : depList) {
                        // if any of the dependencies have not been opened,
                        // set false
                        if (!openedEntries.containsKey(lsid)) {
                            allDependenciesHaveBeenOpened = false;
                        }
                    }
                    if (allDependenciesHaveBeenOpened) {
                        // dependencies have been opened so OK to open this
                        // one
                        boolean success = open(entry, tableauFrame);
                        if (success) {
                            openedEntries.put(entry.getLSID(), entry);
                            openedThisPass.add(entry);
                            break;
                        }
                        if (isDebugging)
                            log.debug(success);
                    }
                }
            }

            if (openedThisPass.size() == 0) {
                // Bad news, nothing is getting opened
                // break out to avoid infinite loop
                break;
            }

            // remove the entries that were opened during this pass
            for (KAREntry entry : openedThisPass) {
                unopenedEntries.remove(entry);
            }
        }

        if (openedEntries.size() == 0) {
            return false;
        }
    } catch (Exception e) {
        throw new Exception("Error on Open: " + e.getMessage());
    }
    return true;
}

From source file:edu.umn.cs.sthadoop.operations.STRangeQuery.java

public static void rangeQueryOperation(OperationsParams parameters) throws Exception {
    final OperationsParams params = parameters;

    final Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();/*from ww w.j  a  v  a2  s  . c o  m*/
        System.exit(1);
    }
    if (paths.length >= 2 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }
    if (params.get("rect") == null) {
        String x1 = "-" + Double.toString(Double.MAX_VALUE);
        String y1 = "-" + Double.toString(Double.MAX_VALUE);
        String x2 = Double.toString(Double.MAX_VALUE);
        String y2 = Double.toString(Double.MAX_VALUE);
        System.out.println(x1 + "," + y1 + "," + x2 + "," + y2);
        params.set("rect", x1 + "," + y1 + "," + x2 + "," + y2);
        //         System.err.println("You must provide a query range");
        //         printUsage();
        //         System.exit(1);
    }

    if (params.get("interval") == null) {
        System.err.println("Temporal range missing");
        printUsage();
        System.exit(1);
    }

    TextSerializable inObj = params.getShape("shape");
    if (!(inObj instanceof STPoint) && !(inObj instanceof STRectangle)) {
        LOG.error("Shape is not instance of STPoint or STRectangle");
        printUsage();
        System.exit(1);
    }

    // Get spatio-temporal slices.
    List<Path> STPaths = getIndexedSlices(params);
    final Path outPath = params.getOutputPath();
    final Rectangle[] queryRanges = params.getShapes("rect", new Rectangle());

    // All running jobs
    final Vector<Long> resultsCounts = new Vector<Long>();
    Vector<Job> jobs = new Vector<Job>();
    Vector<Thread> threads = new Vector<Thread>();

    long t1 = System.currentTimeMillis();
    for (Path stPath : STPaths) {
        final Path inPath = stPath;
        for (int i = 0; i < queryRanges.length; i++) {
            final OperationsParams queryParams = new OperationsParams(params);
            OperationsParams.setShape(queryParams, "rect", queryRanges[i]);
            if (OperationsParams.isLocal(new JobConf(queryParams), inPath)) {
                // Run in local mode
                final Rectangle queryRange = queryRanges[i];
                final Shape shape = queryParams.getShape("shape");
                final Path output = outPath == null ? null
                        : (queryRanges.length == 1 ? outPath : new Path(outPath, String.format("%05d", i)));
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        FSDataOutputStream outFile = null;
                        final byte[] newLine = System.getProperty("line.separator", "\n").getBytes();
                        try {
                            ResultCollector<Shape> collector = null;
                            if (output != null) {
                                FileSystem outFS = output.getFileSystem(queryParams);
                                final FSDataOutputStream foutFile = outFile = outFS.create(output);
                                collector = new ResultCollector<Shape>() {
                                    final Text tempText = new Text2();

                                    @Override
                                    public synchronized void collect(Shape r) {
                                        try {
                                            tempText.clear();
                                            r.toText(tempText);
                                            foutFile.write(tempText.getBytes(), 0, tempText.getLength());
                                            foutFile.write(newLine);
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                };
                            } else {
                                outFile = null;
                            }
                            long resultCount = rangeQueryLocal(inPath, queryRange, shape, queryParams,
                                    collector);
                            resultsCounts.add(resultCount);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                if (outFile != null)
                                    outFile.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
                thread.start();
                threads.add(thread);
            } else {
                // Run in MapReduce mode
                Path outTempPath = outPath == null ? null
                        : new Path(outPath, String.format("%05d", i) + "-" + inPath.getName());
                queryParams.setBoolean("background", true);
                Job job = rangeQueryMapReduce(inPath, outTempPath, queryParams);
                jobs.add(job);
            }
        }
    }

    while (!jobs.isEmpty()) {
        Job firstJob = jobs.firstElement();
        firstJob.waitForCompletion(false);
        if (!firstJob.isSuccessful()) {
            System.err.println("Error running job " + firstJob);
            System.err.println("Killing all remaining jobs");
            for (int j = 1; j < jobs.size(); j++)
                jobs.get(j).killJob();
            System.exit(1);
        }
        Counters counters = firstJob.getCounters();
        Counter outputRecordCounter = counters.findCounter(Task.Counter.MAP_OUTPUT_RECORDS);
        resultsCounts.add(outputRecordCounter.getValue());
        jobs.remove(0);
    }
    while (!threads.isEmpty()) {
        try {
            Thread thread = threads.firstElement();
            thread.join();
            threads.remove(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    long t2 = System.currentTimeMillis();
    System.out.println("QueryPlan:");
    for (Path stPath : STPaths) {
        System.out.println(stPath.getName());
    }
    System.out.println("Time for " + queryRanges.length + " jobs is " + (t2 - t1) + " millis");
    System.out.println("Results counts: " + resultsCounts);
}

From source file:at.gv.egovernment.moa.id.proxy.servlet.ProxyServlet.java

/**
 * Tunnels a request to the online application using given URL mapping and SSLSocketFactory.
 * This method returns the ResponseCode of the request to the online application. 
 * @param req HTTP request/*from  w w w . j  a  va  2  s. co m*/
 * @param resp HTTP response
 * @param loginHeaders header field/values to be inserted for purposes of authentication; 
 *         may be <code>null</code>
 * @param loginParameters parameter name/values to be inserted for purposes of authentication; 
 *         may be <code>null</code>
 * @param publicURLPrefix prefix of request URL to be substituted for the <code>realURLPrefix</code>
 * @param realURLPrefix prefix of online application URL to substitute the <code>publicURLPrefix</code>
 * @param ssf SSLSocketFactory to use
 * @throws IOException if an I/O error occurs
 */
private int tunnelRequest(HttpServletRequest req, HttpServletResponse resp, Map loginHeaders,
        Map loginParameters, String publicURLPrefix, String realURLPrefix, SSLSocketFactory ssf, String binding)
        throws IOException {

    String originBinding = binding;
    String browserUserID = "";
    String browserPassword = "";
    //URL url = new URL(realURLPrefix); 
    //String realURLHost = url.getHost(); 
    if (INTERNAL_DEBUG && !binding.equals(""))
        Logger.debug("Binding: " + binding);

    // collect headers from request
    Map headers = new HashMap();
    for (Enumeration enu = req.getHeaderNames(); enu.hasMoreElements();) {
        String headerKey = (String) enu.nextElement();
        String headerKeyValue = req.getHeader(headerKey);
        if (INTERNAL_DEBUG)
            Logger.debug("Incoming:" + headerKey + "=" + headerKeyValue);
        //Analyze Basic-Auth-Headers from the client
        if (headerKey.equalsIgnoreCase("Authorization")) {
            if (headerKeyValue.substring(0, 6).equalsIgnoreCase("Basic ")) {
                String credentials = headerKeyValue.substring(6);
                byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
                String plaintextcredentials = new String(bplaintextcredentials);
                browserUserID = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
                browserPassword = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
                //deactivate following line for security
                //if (INTERNAL_DEBUG) Logger.debug("Analyzing authorization-header from browser: " + headerKeyValue + "gives UN:PW=" + browserUserID + ":" + browserPassword );
            }
            if (headerKeyValue.substring(0, 9).equalsIgnoreCase("Negotiate")) {
                //deactivate following line for security
                //if (INTERNAL_DEBUG) Logger.debug("Analyzing authorization-header from browser: Found NTLM Aut.: " + headerKeyValue + "gives UN:PW=" + browserUserID + ":" + browserPassword );
            }
        } else {
            /* Headers MUST NOT be repaced according to our Spec.
            if (headerKey.equalsIgnoreCase("Host")) {
               headerKeyValue = realURLHost; 
                 //headerKeyValue= realURLPrefix.substring(hoststartpos);
              if (INTERNAL_DEBUG) Logger.debug("replaced:" + headerKey + "=" + headerKeyValue);           
            }
            */
            headers.put(headerKey, headerKeyValue);
        }
    }

    // collect login headers, possibly overwriting headers from request
    String authorizationvalue = "";
    if (req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER) == null) {

        if (OAConfiguration.BINDUNG_NOMATCH.equals(binding)) {
            int loginTry = getLoginTry(req);
            Logger.debug("Binding: mode = " + OAConfiguration.BINDUNG_NOMATCH + "(try #"
                    + Integer.toString(loginTry) + ")");
            if (loginTry == 1) {
                binding = OAConfiguration.BINDUNG_FULL;
            } else {
                binding = OAConfiguration.BINDUNG_USERNAME;
            }
        }

        /* Soll auch bei anderen bindings zuerst ein passwort probiert werden knnen:
        //if we have the first Login-Try and we have Binding to Username and a predefined Password we try this one first
         // full binding will be covered by next block
         if (loginTry==1 && !OAConfiguration.BINDUNG_FULL.equals(binding)) {
           //1st try: if we have a password, try this one first
            for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
              String headerKey = (String) iter.next();
              String headerKeyValue = (String) loginHeaders.get(headerKey);
              if (isBasicAuthenticationHeader(headerKey, headerKeyValue)) {
               String credentials = headerKeyValue.substring(6);
               byte [] bplaintextcredentials = Base64Utils.decode(credentials, true);
              String plaintextcredentials = new String(bplaintextcredentials);
              String password = plaintextcredentials.substring(plaintextcredentials.indexOf(":")+1);
              if (password!=null && !password.equals("")) {
                  Logger.debug("Binding: found predefined password. Trying full binding first");
                 binding = OAConfiguration.BINDUNG_FULL;
                 break;
                }
              }
            }
         }
         */

        //we have a connection with not having logged on
        if (loginHeaders != null && (browserPassword.length() != 0 || browserUserID.length() != 0
                || OAConfiguration.BINDUNG_FULL.equals(binding))) {
            for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
                String headerKey = (String) iter.next();
                String headerKeyValue = (String) loginHeaders.get(headerKey);
                //customize loginheaders if necessary
                if (isBasicAuthenticationHeader(headerKey, headerKeyValue)) {
                    if (OAConfiguration.BINDUNG_FULL.equals(binding)) {
                        authorizationvalue = headerKeyValue;
                        Logger.debug("Binding: full binding to user established");
                    } else {
                        String credentials = headerKeyValue.substring(6);
                        byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
                        String plaintextcredentials = new String(bplaintextcredentials);
                        String userID = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
                        String password = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
                        String userIDPassword = ":";
                        if (OAConfiguration.BINDUNG_USERNAME.equals(binding)) {
                            Logger.debug("Binding: Access with necessary binding to user");
                            userIDPassword = userID + ":" + browserPassword;
                        } else if (OAConfiguration.BINDUNG_NONE.equals(binding)) {
                            Logger.debug("Binding: Access without binding to user");
                            //If first time
                            if (browserUserID.length() == 0)
                                browserUserID = userID;
                            if (browserPassword.length() == 0)
                                browserPassword = password;
                            userIDPassword = browserUserID + ":" + browserPassword;
                        } else {
                            userIDPassword = userID + ":" + password;
                        }
                        credentials = Base64Utils.encode(userIDPassword.getBytes());
                        authorizationvalue = "Basic " + credentials;
                        headerKeyValue = authorizationvalue;
                    }
                }
                headers.put(headerKey, headerKeyValue);
            }
        }
    } else {
        //if OA needs Authorization header in each further request
        authorizationvalue = (String) req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER);
        if (loginHeaders != null)
            headers.put("Authorization", authorizationvalue);
    }

    Vector parameters = new Vector();
    for (Enumeration enu = req.getParameterNames(); enu.hasMoreElements();) {
        String paramName = (String) enu.nextElement();
        if (!(paramName.equals(PARAM_SAMLARTIFACT) || paramName.equals(PARAM_TARGET))) {
            if (INTERNAL_DEBUG)
                Logger.debug("Req Parameter-put: " + paramName + ":" + req.getParameter(paramName));
            String parameter[] = new String[2];
            parameter[0] = paramName;
            parameter[1] = req.getParameter(paramName);
            parameters.add(parameter);
        }
    }
    // collect login parameters, possibly overwriting parameters from request
    if (loginParameters != null) {
        for (Iterator iter = loginParameters.keySet().iterator(); iter.hasNext();) {
            String paramName = (String) iter.next();
            if (!(paramName.equals(PARAM_SAMLARTIFACT) || paramName.equals(PARAM_TARGET))) {
                if (INTERNAL_DEBUG)
                    Logger.debug(
                            "Req Login-Parameter-put: " + paramName + ":" + loginParameters.get(paramName));
                String parameter[] = new String[2];
                parameter[0] = paramName;
                parameter[1] = (String) loginParameters.get(paramName);
                parameters.add(parameter);
            }
        }
    }

    ConnectionBuilder cb = ConnectionBuilderFactory.getConnectionBuilder(publicURLPrefix);
    HttpURLConnection conn = cb.buildConnection(req, publicURLPrefix, realURLPrefix, ssf, parameters);

    // set headers as request properties of URLConnection
    for (Iterator iter = headers.keySet().iterator(); iter.hasNext();) {
        String headerKey = (String) iter.next();
        String headerValue = (String) headers.get(headerKey);
        String LogStr = "Req header " + headerKey + ": " + headers.get(headerKey);
        if (isBasicAuthenticationHeader(headerKey, headerValue)) {
            String credentials = headerValue.substring(6);
            byte[] bplaintextcredentials = Base64Utils.decode(credentials, true);
            String plaintextcredentials = new String(bplaintextcredentials);
            String uid = plaintextcredentials.substring(0, plaintextcredentials.indexOf(":"));
            String pwd = plaintextcredentials.substring(plaintextcredentials.indexOf(":") + 1);
            //Sollte AuthorizationInfo vom HTTPClient benutzt werden:  cb.addBasicAuthorization(publicURLPrefix, uid, pwd);
            //deactivate following line for security
            //if (INTERNAL_DEBUG && Logger.isDebugEnabled()) LogStr = LogStr + "  >UserID:Password< >" + uid + ":" + pwd + "<";
        }
        conn.setRequestProperty(headerKey, headerValue);
        if (INTERNAL_DEBUG)
            Logger.debug(LogStr);
    }

    StringWriter sb = new StringWriter();

    // Write out parameters into output stream of URLConnection.
    // On GET request, do not send parameters in any case,
    // otherwise HttpURLConnection would send a POST.
    if (!"get".equalsIgnoreCase(req.getMethod()) && !parameters.isEmpty()) {
        boolean firstParam = true;
        String parameter[] = new String[2];
        for (Iterator iter = parameters.iterator(); iter.hasNext();) {
            parameter = (String[]) iter.next();
            String paramName = parameter[0];
            String paramValue = parameter[1];
            if (firstParam)
                firstParam = false;
            else
                sb.write("&");
            sb.write(paramName);
            sb.write("=");
            sb.write(paramValue);
            if (INTERNAL_DEBUG)
                Logger.debug("Req param " + paramName + ": " + paramValue);
        }
    }

    // For WebDAV and POST: copy content
    if (!"get".equalsIgnoreCase(req.getMethod())) {
        if (INTERNAL_DEBUG && !"post".equalsIgnoreCase(req.getMethod()))
            Logger.debug("---- WEBDAV ----  copying content");
        try {
            OutputStream out = conn.getOutputStream();
            InputStream in = req.getInputStream();
            if (!parameters.isEmpty())
                out.write(sb.toString().getBytes()); //Parameter nicht mehr mittels Printwriter schreiben 
            copyStream(in, out, null, req.getMethod());
            out.flush();
            out.close();
        } catch (IOException e) {
            if (!"post".equalsIgnoreCase(req.getMethod()))
                Logger.debug("---- WEBDAV ----  streamcopy problem");
            else
                Logger.debug("---- POST ----  streamcopy problem");
        }
    }

    // connect
    if (INTERNAL_DEBUG)
        Logger.debug("Connect Request");
    conn.connect();
    if (INTERNAL_DEBUG)
        Logger.debug("Connect Response");

    // check login tries
    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        int loginTry = getLoginTry(req);
        req.getSession().setAttribute(ATT_OA_LOGINTRY, Integer.toString(loginTry));
        if (loginTry > MAX_OA_LOGINTRY) {
            Logger.debug("Found 401 UNAUTHORIZED, maximum tries exceeded; leaving...");
            cb.disconnect(conn);
            return -401;
        }
    }

    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED
            && OAConfiguration.BINDUNG_FULL.equals(originBinding)) {
        Logger.debug("Found 401 UNAUTHORIZED, leaving...");
        cb.disconnect(conn);
        return conn.getResponseCode();
    }

    resp.setStatus(conn.getResponseCode());
    //Issue by Gregor Karlinger - content type was annotated twice
    //resp.setContentType(conn.getContentType());

    if (loginHeaders != null
            && (conn.getResponseCode() == HttpURLConnection.HTTP_OK
                    || conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)
            && req.getSession().getAttribute(ATT_OA_AUTHORIZATION_HEADER) == null) {
        req.getSession().setAttribute(ATT_OA_AUTHORIZATION_HEADER, authorizationvalue);
        Logger.debug("Login OK. Saving authorization header to remember in further requests");
    }

    // Read response headers
    // Omit response header "content-length" if response header "Transfer-encoding: chunked" is set.
    // Otherwise, the connection will not be kept alive, resulting in subsequent missing requests.
    // See JavaDoc of javax.servlet.http.HttpServlet:
    // When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.
    Vector respHeaders = new Vector();

    boolean chunked = false;
    String contentLengthKey = null;
    String transferEncodingKey = null;
    int i = 1;
    String headerKey;
    String loginType = (String) req.getSession().getAttribute(ATT_OA_LOGINTYPE);
    while ((headerKey = conn.getHeaderFieldKey(i)) != null) {
        String headerValue = conn.getHeaderField(i);

        if (headerKey.equalsIgnoreCase("WWW-Authenticate")) {
            int start = headerValue.indexOf("Basic realm=\"");
            boolean requestsBasicAuth = headerValue.substring(start).startsWith("Basic realm=\"");
            if (requestsBasicAuth) {
                headerValue = "Basic realm=\"" + publicURLPrefix + "\"";

                if (OAConfiguration.BINDUNG_USERNAME.equals(originBinding)
                        || OAConfiguration.BINDUNG_NOMATCH.equals(originBinding))
                    headerValue = "Basic realm=\"Bitte Passwort eingeben\"";
                else if ("none".equals(originBinding)) {
                    headerValue = "Basic realm=\"Bitte Benutzername und Passwort eingeben\"";
                }
            }
        }

        //    // berschrift im Browser-Passworteingabedialog setzen (sonst ist der reale host eingetragen)
        //    if (headerKey.equalsIgnoreCase("WWW-Authenticate") && headerValue.startsWith("Basic realm=\"")) {
        //      headerValue = "Basic realm=\"" + publicURLPrefix + "\"";
        //      if (OAConfiguration.BINDUNG_USERNAME.equals(originBinding) || OAConfiguration.BINDUNG_NOMATCH.equals(originBinding)) {
        //         headerValue = "Basic realm=\"Bitte Passwort eingeben\"";
        //      } else if (OAConfiguration.BINDUNG_NONE.equals(originBinding)) {
        //         headerValue = "Basic realm=\"Bitte Benutzername und Passwort eingeben\"";
        //      }
        //    }

        String respHeader[] = new String[2];
        if ((conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
                && headerKey.equalsIgnoreCase("content-length")) {
            //alter the unauthorized message with template for login 
            //TODO: supply a special login form on unauthorized messages with bindings!=full
            headerValue = Integer.toString(RET_401_MSG.length());
        }
        respHeader[0] = headerKey;
        respHeader[1] = headerValue;

        if (!(OAConfiguration.BINDUNG_FULL.equals(originBinding)
                && OAConfiguration.LOGINTYPE_STATELESS.equals(loginType)
                && headerKey.equalsIgnoreCase("WWW-Authenticate")
                && headerValue.startsWith("Basic realm=\""))) {
            respHeaders.add(respHeader);
            if (INTERNAL_DEBUG)
                Logger.debug("Resp header " + headerKey + ": " + headerValue);
        } else {
            Logger.debug("Resp header ---REMOVED--- " + headerKey + ": " + headerValue);
        }
        if (isTransferEncodingChunkedHeader(headerKey, headerValue)
                || "content-length".equalsIgnoreCase(headerKey)) {
            respHeaders.remove(respHeader);
            Logger.debug("Resp header " + headerKey + " REMOVED");
        }

        i++;
    }

    String headerValue;
    String respHeader[] = new String[2];

    //write out all Responseheaders 
    for (Iterator iter = respHeaders.iterator(); iter.hasNext();) {
        respHeader = (String[]) iter.next();
        headerKey = respHeader[0];
        headerValue = respHeader[1];
        resp.addHeader(headerKey, headerValue);
    }

    //Logger.debug(">>>> Copy Content");
    //Logger.debug("  from ()" + conn.getURL());
    //Logger.debug("  to (" + req.getRemoteAddr() + ":"+ ") " +req.getRequestURL());

    // read response stream
    Logger.debug("Resp from " + conn.getURL().toString() + ": status " + conn.getResponseCode());
    // Load content unless the server lets us know that the content is NOT MODIFIED...
    if (conn.getResponseCode() != HttpURLConnection.HTTP_NOT_MODIFIED) {
        BufferedInputStream respIn = new BufferedInputStream(conn.getInputStream());
        //Logger.debug("Got Inputstream");
        BufferedOutputStream respOut = new BufferedOutputStream(resp.getOutputStream());
        //Logger.debug("Got Outputstream");

        byte[] buffer = new byte[4096];
        if (respOut != null) {
            int bytesRead;
            while ((bytesRead = respIn.read(buffer)) >= 0) {
                if (conn.getResponseCode() != HttpURLConnection.HTTP_UNAUTHORIZED)
                    respOut.write(buffer, 0, bytesRead);
            }
        } else {
            while (respIn.read(buffer) >= 0)
                ;
        }

        /*
        int ch;
        StringBuffer strBuf = new StringBuffer("");
        while ((ch = respIn.read()) >= 0) {
          if (conn.getResponseCode()!=HttpURLConnection.HTTP_UNAUTHORIZED) respOut.write(ch);
          strBuf.append((char)ch);
        }
        Logger.debug("Resp Content:");
        if (strBuf.toString().length()>500)
          Logger.debug(strBuf.toString().substring(0,500));
        else
          Logger.debug(strBuf.toString());
        */

        if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            respOut.write(RET_401_MSG.getBytes());
        }
        respOut.flush();
        respOut.close();
        respIn.close();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            Logger.debug("Found 401 UNAUTHORIZED...");
            cb.disconnect(conn);
            return conn.getResponseCode();
        }
    } else {
        //if (conn.getResponseCode()==HttpURLConnection.HTTP_NOT_MODIFIED) 
        Logger.debug("Found 304 NOT MODIFIED...");
    }

    cb.disconnect(conn);
    Logger.debug("Request done");

    return conn.getResponseCode();
}

From source file:org.panlab.tgw.resources.PTMResource.java

@POST // The Java method will produce content identified by the MIME Media
// type "text/plain"
@Produces("text/xml")
@Consumes("application/x-www-form-urlencoded")
public String postResource(@PathParam("ptmid") String ptmid, @PathParam("resourceid") String resourceid,
        String content) {//  w  w  w .  j av  a2s.c om
    log.info("POST (" + j + ") /" + ptmid + "/" + resourceid + " " + content);
    try {

        XMLElement tempTop = XMLUtil.getTopElement(content);
        if (org.panlab.tgw.App.getStatus(ptmid) != 0) {
            String type = tempTop.m_name;
            return createError(org.panlab.tgw.App.statusText(org.panlab.tgw.App.getStatus(ptmid)), resourceid,
                    type);
        }
        if (org.panlab.tgw.App.getRAStatus(resourceid) != 0) {
            String type = tempTop.m_name;
            return createError("RA: " + resourceid + " has reported an error", resourceid, type);
        }
        String context = XMLUtil.getXMLElement(content, "context");
        String vctid = XMLUtil.getXMLElement(context, "vctId");
        content = XMLUtil.getXMLElement(content, "configuration");
        tempTop.m_value = content;
        content = tempTop.toString();
        if (tempTop.m_name.equalsIgnoreCase("vlan")) {
            Object[] tempList = XMLUtil.getElements(content);
            if (tempList != null && tempList.length > 0) {
                String tempid = ((XMLElement) (tempList[0])).m_value;
                tempid = tempid.substring(0, tempid.indexOf("."));
                ptmid = tempid;
                resourceid = ptmid + ".top-0";
                log.info("changed to: " + ptmid + "/" + resourceid);
            }
        }
        log.info("POST (" + j + ") /" + ptmid + "/" + resourceid + " vctID:" + vctid + " " + content);
        if (ptmid.equalsIgnoreCase("share")) {
            T1ServiceLocator l = new T1ServiceLocator();
            T1SoapBindingStub stub;
            XMLElement top = XMLUtil.getTopElement(content);
            Object elements[] = XMLUtil.getElements(content);
            log.info(top.m_name);
            if (top.m_name.equalsIgnoreCase("vpn")) {
                int vpnsize = elements.length;
                Hashtable<String, String> igwSettings = new Hashtable<String, String>();
                for (int i = 0; i < elements.length; i++) {
                    XMLElement temp = (XMLElement) elements[i];
                    log.info(temp.toString());
                    if (temp.m_attribute != null) {
                        String ptm = temp.m_value.substring(0, temp.m_value.indexOf("."));
                        stub = (T1SoapBindingStub) (l.getT1((URL) (org.panlab.tgw.App.ptm_indexes.get(ptm))));
                        ProvisioningResponse ref;
                        ref = stub.query(vctid, temp.m_value, "<connectivity></connectivity>", null);
                        log.info(ref.getConfig_data());
                        igwSettings.put(temp.m_value, ref.getConfig_data());
                    }
                }
                String vpn_id = "";
                Enumeration<String> en = igwSettings.keys();
                log.info("igwSettings " + igwSettings.size());
                while (en.hasMoreElements()) {
                    String current = en.nextElement();
                    String currentdetails = igwSettings.get(current);
                    log.info(current + ": " + currentdetails);
                    while (en.hasMoreElements()) {
                        String other = en.nextElement();
                        String otherdetails = igwSettings.get(other);

                        String ptm = current.substring(0, current.indexOf("."));
                        vpn_id += current;
                        stub = (T1SoapBindingStub) (l.getT1((URL) (org.panlab.tgw.App.ptm_indexes.get(ptm))));
                        ProvisioningResponse ref;
                        ref = stub.update(vctid, current, otherdetails, null);
                        log.info(ref.getStatus_code());
                        ptm = other.substring(0, other.indexOf("."));
                        vpn_id += other;
                        stub = (T1SoapBindingStub) (l.getT1((URL) (org.panlab.tgw.App.ptm_indexes.get(ptm))));
                        ref = stub.update(vctid, other, currentdetails, null);
                        log.info(ref.getStatus_code());

                    }
                    igwSettings.remove(current);
                    log.info("igwSettings " + igwSettings.size());
                    en = igwSettings.keys();
                }
                log.info("VPN_ID: " + vpn_id);
                return createOK(vpn_id, "vpn");
            } else
                return createError("Share ptm expects only vlan or vpn. Check VCT design", resourceid,
                        top.m_name);

        } else {
            T1ServiceLocator l = new T1ServiceLocator();
            T1SoapBindingStub stub;
            XMLElement top = XMLUtil.getTopElement(content);
            Object elements[] = XMLUtil.getElements(content);
            String conf = "";
            Vector<String> referencedRAIDs = new Vector<String>();
            for (int i = 0; i < elements.length; i++) {
                XMLElement temp = (XMLElement) elements[i];
                log.info(temp.toString());
                if (temp.m_attributes.containsKey("type")
                        && temp.m_attributes.get("type").equalsIgnoreCase("\"reference\"")) {
                    if (!(temp.m_value.equalsIgnoreCase(""))) {
                        referencedRAIDs.add(temp.m_value);
                        String ptm = temp.m_value.substring(0, temp.m_value.indexOf("."));
                        stub = (T1SoapBindingStub) (l.getT1((URL) (org.panlab.tgw.App.ptm_indexes.get(ptm))));
                        ProvisioningResponse ref;
                        if (resourceid.endsWith("top-0") && top.m_name.equalsIgnoreCase("vlan"))
                            ref = stub.query(vctid, temp.m_value, "<connectivity></connectivity>", null);
                        else
                            ref = stub.query(vctid, temp.m_value, "<reference></reference>", null);

                        log.info(temp.m_value + " ref data: " + ref.getConfig_data());
                        if (resourceid.endsWith("top-0") && top.m_name.equalsIgnoreCase("vlan"))
                            elements[i] = new XMLElement("item-" + i, null, null, ref.getConfig_data());
                        else
                            elements[i] = new XMLElement(temp.m_name, null, null, ref.getConfig_data());
                    }
                }
                if (temp.m_value != null)
                    conf += elements[i].toString();
            }

            ProvisioningResponse res = null;
            if (top.m_attributes.containsKey("action")
                    && top.m_attributes.get("action").equalsIgnoreCase("\"update\"")) {
                log.info(top.m_attributes.get("action"));
                log.info("SENDING: " + conf);
                stub = (T1SoapBindingStub) (l.getT1((URL) (org.panlab.tgw.App.ptm_indexes.get(ptmid))));
                if (top.m_attributes.containsKey("mode")
                        && top.m_attributes.get("mode").equalsIgnoreCase("\"asynchronous\""))
                    res = stub.update(vctid, resourceid, conf,
                            "https://" + System.getProperty("publicIP") + ":8070/axis/services/TeagleGW");
                else
                    res = stub.update(vctid, resourceid, conf, null);
                log.info("https://" + java.net.Inet4Address.getLocalHost() + ":8070/axis/services/TeagleGW");
            } else {
                conf = "<" + top.m_name + ">" + conf + "</" + top.m_name + ">";
                log.info("SENDING: " + conf);
                stub = (T1SoapBindingStub) (l.getT1((URL) (org.panlab.tgw.App.ptm_indexes.get(ptmid))));
                //log.info(vctid+" "+resourceid+" "+conf);
                if (top.m_attributes.containsKey("mode")
                        && top.m_attributes.get("mode").equalsIgnoreCase("\"asynchronous\""))
                    res = stub.create(vctid, resourceid, conf,
                            "https://62.103.214.70:8070/axis/services/TeagleGW");
                else
                    res = stub.create(vctid, resourceid, conf, null);
                if (res != null) {
                    if (!(res.getConfig_data().contains("FAIL")))
                        resourceid = XMLUtil.getXMLElement(res.getConfig_data(), "uuid");
                    else
                        resourceid = res.getConfig_data();
                }
            }
            if (res != null) {
                int referencedSize = referencedRAIDs.size();
                if (!(top.m_attributes.containsKey("mode")) || (top.m_attributes.containsKey("mode")
                        && !(top.m_attributes.get("mode").equalsIgnoreCase("\"asynchronous\""))))
                    if (referencedSize > 0) {
                        stub = (T1SoapBindingStub) (l.getT1((URL) (org.panlab.tgw.App.ptm_indexes.get(ptmid))));
                        ProvisioningResponse ref;
                        ref = stub.query(vctid, resourceid, "<reference></reference>", null);
                        conf = "<" + top.m_name + ">" + ref.getConfig_data() + "</" + top.m_name + ">";
                        log.info("The following data have to be sent to all referenced resources by "
                                + resourceid + " :" + conf);
                        if (!org.panlab.tgw.App.CIRCULAR_REFERENCE) {
                            log.info("reverse reference disabled");
                            referencedSize = 0;
                        }
                        for (int k = 0; k < referencedSize; k++) {
                            String temp = referencedRAIDs.remove(0);
                            if (temp != null) {
                                log.info("Updating " + temp);
                                log.info(conf);
                                String ptm = temp.substring(0, temp.indexOf("."));
                                stub = (T1SoapBindingStub) (l
                                        .getT1((URL) (org.panlab.tgw.App.ptm_indexes.get(ptm))));
                                ProvisioningResponse update;
                                update = stub.update(vctid, temp, conf, null);
                                log.info("Updated " + temp + " :" + update.getStatus_code());
                            }
                        }
                    }
                //String type = resourceid.substring(resourceid.lastIndexOf(".")+1,resourceid.lastIndexOf("-"));
                String response = "";
                if (top.m_attributes.containsKey("action")
                        && top.m_attributes.get("action").equalsIgnoreCase("\"update\"")) {
                    log.info("RETURNING conf: " + res.getConfig_data());
                    log.info("RETURNING status: " + res.getStatus_code());
                    log.info("RETURNING id: " + res.getRequest_id());
                    response = res.getStatus_code();
                } else {
                    log.info("RETURNING conf: " + res.getConfig_data());
                    log.info("RETURNING status: " + res.getStatus_code());
                    log.info("RETURNING id: " + res.getRequest_id());
                    response = res.getConfig_data();
                }
                if (top.m_attributes.containsKey("mode")
                        && top.m_attributes.get("mode").equalsIgnoreCase("\"asynchronous\"")) {
                    App.async_reqs.put(res.getRequest_id(), new Notification(res.getRequest_id(), "", "", vctid,
                            "RETURN_STATUS", "MESSAGE", "", ptmid, top.m_name, referencedRAIDs));

                    return createOK(null, top.m_name/*type*/, res.getRequest_id());
                } else {
                    m_ids.put(resourceid, vctid);
                    return createOK(resourceid, top.m_name/*type*/);
                }
            } else {
                //String type = resourceid.substring(resourceid.lastIndexOf(".")+1,resourceid.lastIndexOf("-"));
                return createError("Null response from PTM", resourceid, top.m_name/*type*/);
            }

        }
    } catch (Exception error) {
        //error.printStackTrace();
        String type = resourceid.substring(resourceid.lastIndexOf(".") + 1, resourceid.lastIndexOf("-"));
        log.info("RETURNING: " + error.getMessage());
        return createError(error.getMessage(), resourceid, type);
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.Uploader.java

/**
 * @param mapping/*from  w  ww  .  j av  a  2 s .  co  m*/
 * @throws UploaderException
 * 
 * Adds elements to uploadFields as required for relationship described in mapping.
 */
protected void addMappingRelFlds(UploadMappingDefRel mapping) throws UploaderException {
    if (mapping.getSequenceFld() != null) {
        Field fld = db.getSchema().getField(mapping.getTable(), mapping.getSequenceFld());
        if (fld == null) {
            logDebug("could not find field in db: " + mapping.getTable() + "." + mapping.getField());
        }
        UploadField newFld = new UploadField(fld, -1, mapping.getWbFldName(), null);
        newFld.setSequence(mapping.getSequence());
        newFld.setValue(mapping.getSequence().toString());
        uploadFields.add(newFld);
    }
    Table t1 = db.getSchema().getTable(mapping.getTable());
    Table t2 = db.getSchema().getTable(mapping.getRelatedTable());
    for (ImportMappingRelFld fld : mapping.getLocalFields()) {
        Field dbFld = t1.getField(fld.getFieldName());
        if (dbFld == null) {
            logDebug("could not find field in db: " + t1.getName() + "." + fld.getFieldName());
        }
        UploadField newFld = new UploadField(dbFld, fld.getFldIndex(), fld.getWbFldName(), null);
        newFld.setSequence(mapping.getSequence());
        uploadFields.add(newFld);
    }
    if (mapping.getRelatedFields().size() > 0) {
        //Relationship r = null;
        Vector<Relationship> rs;
        try {
            rs = db.getGraph().getAllEdgeData(t1, t2);
            if (rs.size() == 0) {
                rs = db.getGraph().getAllEdgeData(t2, t1);
            }
        } catch (DirectedGraphException ex) {
            throw new UploaderException(ex, UploaderException.ABORT_IMPORT);
        }
        // find the 'right' rel. ie: discard Agent ->> ModifiedByAgentID/CreatedByAgentID
        //Actually it seems the modifiedby and createdby 'system' relationships get filtered out during graph creation,
        //so the filtering isn't necessarily necessary.
        for (int r = rs.size() - 1; r > -1; r--) {
            if (rs.get(r).getRelatedField().getName().equalsIgnoreCase("modifiedbyagentid")
                    || rs.get(r).getRelatedField().getName().equalsIgnoreCase("createdbyagentid")) {
                rs.remove(r);
            }
        }

        //            for (Relationship rel : rs)
        //            {
        //               if (!rel.getRelatedField().getName().equalsIgnoreCase("modifiedbyagentid")
        //                        && !rel.getRelatedField().getName().equalsIgnoreCase("createdbyagentid"))
        //                {
        //                    r = rel;
        //                    break;
        //                }
        //            }
        if (rs.size() > 0) {
            for (Relationship r : rs) {
                if (r.getRelatedField().getName().equalsIgnoreCase(mapping.getField())) {
                    Vector<ImportMappingRelFld> relFlds = mapping.getRelatedFields();
                    for (int relF = 0; relF < relFlds.size(); relF++) {
                        Field fld = db.getSchema().getField(t2.getName(), relFlds.get(relF).getFieldName());
                        int fldIdx = relFlds.get(relF).getFldIndex();
                        String wbFldName = relFlds.get(relF).getWbFldName();
                        UploadField newFld = new UploadField(fld, fldIdx, wbFldName, r);
                        newFld.setSequence(mapping.getSequence());
                        uploadFields.add(newFld);
                    }
                    return;
                }
            }
        }
        throw new UploaderException("could not find relationship for mapping.", UploaderException.ABORT_IMPORT);
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.Uploader.java

/**
 * @return true if the dataset can be uploaded.
 * /*www .  ja v a 2  s  .  c  om*/
 * Checks that the import mapping and graph are OK. Checks that all required data (TreeDefs,
 * TreeDefItems, DeterminationStatuses, etc) is present in the database.
 * 
 * Saves messages for each problem.
 */
public Vector<UploadMessage> verifyUploadability() throws UploaderException, ClassNotFoundException {
    Vector<UploadMessage> errors = new Vector<UploadMessage>();
    try {
        Vector<Vector<Table>> missingTbls = new Vector<Vector<Table>>();

        //check that parents exist for one-to-one children (which are required to be defined as many-to-one parents 
        //in hibernate)
        for (UploadTable t : uploadTables) {
            if (t.isOneToOneChild() && !t.getHasChildren() && !(t.getTblClass().equals(LocalityDetail.class)
                    || t.getTblClass().equals(GeoCoordDetail.class))) {
                Vector<Vertex<Table>> vs = db.getGraph()
                        .getAdjacentVertices(new Vertex<Table>(t.getTable().getName(), t.getTable()));
                Vector<Table> tbls = new Vector<Table>();
                for (Vertex<Table> vertex : vs) {
                    tbls.add(vertex.getData());
                }
                missingTbls.add(tbls);
            }
        }
        if (!uploadGraph.isConnected()) {
            missingTbls.addAll(getMissingTbls());
        }
        if (missingTbls.size() > 0) {
            Vector<Pair<String, Vector<Table>>> missingTblHints = new Vector<Pair<String, Vector<Table>>>();
            int h = 1;
            for (Vector<Table> tbls : missingTbls) {
                String msg = "";
                if (tbls != null && tbls.size() > 0) {
                    msg += " ";
                    for (int t = 0; t < tbls.size(); t++) {
                        if (t > 0) {
                            msg += ", ";
                        }
                        msg += tbls.get(t).getTableInfo().getTitle();
                    }
                }
                if (!msg.equals("")) {
                    missingTblHints.add(new Pair<String, Vector<Table>>(
                            String.format(getResourceString("WB_UPLOAD_MISSING_TBL_HINT"), h++, msg), tbls));
                }
            }
            if (missingTblHints.size() > 0) {
                errors.add(new BaseUploadMessage(getResourceString("WB_UPLOAD_MISSING_TBL_HINTS")));
                for (Pair<String, Vector<Table>> hint : missingTblHints) {
                    errors.add(new InvalidStructure("   " + hint.getFirst(), hint.getSecond()));
                }
            } else {
                errors.add(new BaseUploadMessage(getResourceString("WB_UPLOAD_MISSING_TBL_NO_HINTS")));
            }
        }
    } catch (DirectedGraphException ex) {
        throw new UploaderException(ex, UploaderException.ABORT_IMPORT);
    }

    errors.addAll(validateConsistency());

    if (!verifyAttachments()) {
        String msg = String.format(UIRegistry.getResourceString("WB_UPLOAD_NO_ATTACHABLES"),
                getAttachableStr());
        errors.add(new BaseUploadMessage(msg));
    }

    //if tables are missing return now, because spurious errors may be generated.
    if (errors.size() != 0) {
        return errors;
    }

    // now find out what data is not available in the dataset and not available in the database
    // Considering such issues 'structural' for now.
    missingRequiredClasses.clear();
    missingRequiredFields.clear();
    Iterator<RelatedClassSetter> rces;
    Iterator<DefaultFieldEntry> dfes;
    for (UploadTable t : uploadTables) {
        try {
            rces = t.getRelatedClassDefaults();
        } catch (ClassNotFoundException ex) {
            log.error(ex);
            return null;
        }
        while (rces.hasNext()) {
            missingRequiredClasses.add(rces.next());
        }

        try {
            dfes = t.getMissingRequiredFlds();
        } catch (NoSuchMethodException ex) {
            log.error(ex);
            return null;
        }
        while (dfes.hasNext()) {
            missingRequiredFields.add(dfes.next());
        }
    }
    resolver = new MissingDataResolver(missingRequiredClasses, missingRequiredFields);
    for (RelatedClassSetter rcs : missingRequiredClasses) {
        if (!rcs.isDefined()) {
            // Assume it is undefined because no related data exists in the database.
            // Also assuming (currently erroneously) that definition problems related to
            // choosing
            // from multiple existing related data have been resolved through user interaction.
            String tblName = DBTableIdMgr.getInstance()
                    .getByShortClassName(rcs.getRelatedClass().getSimpleName()).getTitle();
            // a very vague message...
            String msg = getResourceString("WB_UPLOAD_MISSING_DBDATA") + ": " + tblName;
            errors.add(new InvalidStructure(msg, this));
        }
    }

    Vector<DefaultFieldEntry> undefinedDfes = new Vector<DefaultFieldEntry>();
    for (DefaultFieldEntry dfe : missingRequiredFields) {
        if (!dfe.isDefined()) {
            undefinedDfes.add(dfe);
        }
    }
    //now remove possibly confusing or redundant dfes.
    Collections.sort(undefinedDfes, new Comparator<DefaultFieldEntry>() {

        /* (non-Javadoc)
         * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
         */
        @Override
        public int compare(DefaultFieldEntry o1, DefaultFieldEntry o2) {
            int result = o1.getUploadTbl().getTable().getName()
                    .compareTo(o2.getUploadTbl().getTable().getName());
            if (result != 0) {
                return result;
            }
            boolean o1IsUserFld = o1.getUploadFld() == null || o1.getUploadFld().getIndex() != -1;
            boolean o2IsUserFld = o2.getUploadFld() == null || o2.getUploadFld().getIndex() != -1;
            if (o1IsUserFld == o2IsUserFld) {
                return (o1.getFldName().compareTo(o2.getFldName()));
            }
            if (o1IsUserFld) {
                return -1;
            }
            return 1;
        }

    });
    UploadTable currentTbl = null;
    Vector<DefaultFieldEntry> dfes4Tbl = new Vector<DefaultFieldEntry>();
    Vector<DefaultFieldEntry> dfes2Remove = new Vector<DefaultFieldEntry>();
    for (DefaultFieldEntry dfe : undefinedDfes) {
        if (dfe.getUploadTbl() != currentTbl) {
            if (dfes4Tbl.size() > 1) {
                boolean gotAUserFld = false;
                for (DefaultFieldEntry tblDfe : dfes4Tbl) {
                    boolean isAUserFld = tblDfe.getUploadFld() == null
                            || tblDfe.getUploadFld().getIndex() != -1;
                    gotAUserFld = gotAUserFld || isAUserFld;
                    if (!isAUserFld && gotAUserFld) {
                        //remove weird fields if there are other non-weird fields from the table
                        dfes2Remove.add(tblDfe);
                    }
                }
            }
            dfes4Tbl.clear();
            currentTbl = dfe.getUploadTbl();
        }
        dfes4Tbl.add(dfe);
    }
    if (dfes4Tbl.size() > 1) {
        boolean gotAUserFld = false;
        for (DefaultFieldEntry tblDfe : dfes4Tbl) {
            boolean isAUserFld = tblDfe.getUploadFld() == null || tblDfe.getUploadFld().getIndex() != -1;
            gotAUserFld = gotAUserFld || isAUserFld;
            if (!isAUserFld && gotAUserFld) {
                //remove weird fields if there are other non-weird(or weird) fields from the table
                dfes2Remove.add(tblDfe);
            }
        }
    }
    for (DefaultFieldEntry dfe : dfes2Remove) {
        undefinedDfes.remove(dfe);
    }
    for (DefaultFieldEntry dfe : undefinedDfes) {
        // see note above for missignRequiredClasses iteration
        // another very vague message...
        String msg = getResourceString("WB_UPLOAD_MISSING_DBDATA") + ": "
                + dfe.getUploadTbl().getTable().getTableInfo().getTitle() + "." + dfe.getFldName(); // i18n (dfe.getFldName() is not using title nor wb
                                                                                                                                                                      // column header)
        errors.add(new InvalidStructure(msg, this));
    }

    for (UploadTable t : uploadTables) {
        errors.addAll(t.verifyUploadability());
    }

    return errors;
}

From source file:com.peterbochs.PeterBochsDebugger.java

private void updateBreakpoint() {
    try {/* www  . j a  v a  2  s .c  o  m*/
        jStatusLabel.setText("Updating breakpoint");
        // commandReceiver.setCommandNoOfLine(-1);
        commandReceiver.clearBuffer();
        sendCommand("info break");
        Thread.currentThread();
        String result = commandReceiver.getCommandResultUntilEnd();
        String[] lines = result.split("\n");
        DefaultTableModel model = (DefaultTableModel) breakpointTable.getModel();
        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }

        for (int x = 1; x < lines.length; x++) {
            if (lines[x].contains("breakpoint")) {
                Vector<String> strs = new Vector<String>(Arrays.asList(lines[x].trim().split(" \\s")));
                strs.add("0"); // hit count
                if (strs.size() > 1) {
                    strs.remove(1);
                    model.addRow(strs);
                }
            }
        }

        this.jRefreshELFBreakpointButtonActionPerformed(null);
        jStatusLabel.setText("");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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

/**
 * @param discipline//from   w ww  .  j a va2s.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;
}