Example usage for java.util Vector isEmpty

List of usage examples for java.util Vector isEmpty

Introduction

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

Prototype

public synchronized boolean isEmpty() 

Source Link

Document

Tests if this vector has no components.

Usage

From source file:org.aselect.server.request.handler.aselect.authentication.ApplicationBrowserHandler.java

/**
 * Private method to check whether the user's tgt is valid and satisfies the required level for the current
 * application. TGT must be available in _htTGTContext.
 * //from  w  w w.j  ava2s. c  o  m
 * @param sTgt
 *            The ticket granting ticket.
 * @param sUid
 *            The user ID.
 * @param sServerId
 *            The server ID.
 * @return -1 - credentials not ok, 0 - ok, 1 - ok, but no organization choice made yet.
 */
private int checkCredentials(String sTgt, String sUid, String sServerId) {
    String sMethod = "checkCredentials";
    Integer intRequiredLevel;

    // 20120712, Bauke, not needed, ASelectAuthenticationProfile has already read the TGT
    //_htTGTContext = _tgtManager.getTGT(sTgt);
    if (_htTGTContext == null) {
        return -1;
    }
    if (!((String) _htTGTContext.get("uid")).equals(sUid)) {
        return -1;
    }
    if (!sServerId.equals(_sMyServerId)) {
        return -1;
    }
    _systemLogger.log(Level.INFO, _sModule, sMethod, "checkCred SSO");

    // check single sign-on groups
    Vector vCurSSOGroups = (Vector) _htSessionContext.get("sso_groups");
    Vector vOldSSOGroups = (Vector) _htTGTContext.get("sso_groups");
    if (vCurSSOGroups != null && vOldSSOGroups != null) {
        if (!vCurSSOGroups.isEmpty() && !vOldSSOGroups.isEmpty()) {
            if (!_applicationManager.isValidSSOGroup(vCurSSOGroups, vOldSSOGroups))
                return -1;
        }
    }
    intRequiredLevel = (Integer) _htSessionContext.get("level");
    int iTGTLevel = getLevelFromTGT(_htTGTContext);
    _systemLogger.log(Level.INFO, _sModule, sMethod,
            "CHECK LEVEL, requires: " + intRequiredLevel + " tgt: " + iTGTLevel);
    if (iTGTLevel < intRequiredLevel.intValue()) {
        return -1; // level is not high enough
    }

    // No organization gathering specified: no org_id in TGT
    // Organization gathering specified but no organization found or choice not made yet: org_id="" in TGT
    // Choice made by the user: org_id has a value
    String sOrgId = (String) _htTGTContext.get("org_id");
    if (sOrgId != null && sOrgId.equals(""))
        return 1; // No organization choice was made yet

    // OK!
    return 0;
}

From source file:com.mobiperf.MeasurementScheduler.java

/**
 * Update the schedule based on a set of tasks from the server.
 * <p>/*  w w w .  ja v a 2s  .c o m*/
 * The current tasks to schedule are in a hash table indexed by a unique task key.
 * <p>
 * Remove all tasks from the schedule that are not in the new list or that have changed.
 * Then, add all tasks from the new list that were not in the schedule, or have changed.
 * Then, the schedule will match the one in the server, and unchanged tasks are left as they are.
 * 
 * <p>
 * If the state has changed and the schedule was received from the server, save it to disk
 * so it can be recovered in case of a crash. 
 * 
 * @param newTasks List of MeasurementTasks from the server
 * @param reLoad if it's True, we're loading from disk: don't adjust frequencies or save to disk again.
 */
private void updateSchedule(List<MeasurementTask> newTasks, boolean reLoad) {

    // Keep track of what tasks need to be added.
    // Altered tasks are removed and then added, so they go here too
    Vector<MeasurementTask> tasksToAdd = new Vector<MeasurementTask>();

    // Keep track of what keys are not being used. Remove keys from this as
    // you find they are in use.
    Set<String> missingKeys = new HashSet<String>(currentSchedule.keySet());
    Set<String> keysToRemove = new HashSet<String>();

    Logger.i("Attempting to add new tasks");

    for (MeasurementTask newTask : newTasks) {

        // Adjust the frequency of the new task, based on the selected data consumption profile,
        // or ignore it if the task is disabled for this profile.
        // If we are loading again, don't re-adjust task frequencies.
        if (!reLoad) {
            if (!adjustInterval(newTask)) {
                continue;
            }
        }

        String newKey = newTask.getDescription().key;
        if (!missingKeys.contains(newKey)) {
            tasksToAdd.add(newTask);
        } else {
            // check for changes. If any parameter changes, it counts as a change.
            if (!currentSchedule.get(newKey).getDescription().equals(newTask.getDescription())) {
                // If there's a change, replace the task with the new task from the server
                keysToRemove.add(newKey);
                tasksToAdd.add(newTask);
            }
            // We've seen the task
            missingKeys.remove(newKey);
        }
    }

    // scheduleKeys now contain all keys that do not exist
    keysToRemove.addAll(missingKeys);

    // Add all new tasks, and copy all unmodified tasks, to a new queue.
    // Also update currentSchedule accordingly.
    PriorityBlockingQueue<MeasurementTask> newQueue = new PriorityBlockingQueue<MeasurementTask>(
            Config.MAX_TASK_QUEUE_SIZE, new TaskComparator());

    synchronized (currentSchedule) {
        Logger.i("Tasks to remove:" + keysToRemove.size());
        for (MeasurementTask task : this.taskQueue) {
            String taskKey = task.getDescription().key;
            if (!keysToRemove.contains(taskKey)) {
                newQueue.add(task);
            } else {
                Logger.w("Removing task with key" + taskKey);
                // Also need to keep our master schedule up to date
                currentSchedule.remove(taskKey);
            }
        }
        this.taskQueue = newQueue;
        // add all new tasks
        Logger.i("New tasks added:" + tasksToAdd.size());
        for (MeasurementTask task : tasksToAdd) {
            submitTask(task);
            currentSchedule.put(task.getDescription().key, task);
        }
    }

    if (!reLoad && (!tasksToAdd.isEmpty() || !keysToRemove.isEmpty())) {
        saveSchedulerState();
    }
}

From source file:org.apache.ws.security.handler.WSHandler.java

protected void checkSignatureConfirmation(RequestData reqData, Vector wsResult) throws WSSecurityException {
    if (doDebug) {
        log.debug("Check Signature confirmation");
    }// w w w  . ja v a 2 s . c  om

    /*
     * First get all Signature values stored during sending the request
     */
    Vector sigv = (Vector) getProperty(reqData.getMsgContext(), WSHandlerConstants.SEND_SIGV);
    /*
     * Now get all results that hold a SignatureConfirmation element from
     * the current run of receiver (we can have more than one run: if we
     * have several security header blocks with different actors/roles)
     */
    Vector sigConf = new Vector();
    WSSecurityUtil.fetchAllActionResults(wsResult, WSConstants.SC, sigConf);
    /*
     * now loop over all SignatureConfirmation results and check:
     * - if there is a signature value and no Signature value generated in request: error
     * - if there is a signature value and no matching Signature value found: error
     * 
     *  If a matching value found: remove from vector of stored signature values
     */
    for (int i = 0; i < sigConf.size(); i++) {
        WSSecurityEngineResult result = (WSSecurityEngineResult) sigConf.get(i);
        SignatureConfirmation sc = (SignatureConfirmation) result
                .get(WSSecurityEngineResult.TAG_SIGNATURE_CONFIRMATION);

        byte[] sigVal = sc.getSignatureValue();
        if (sigVal != null) {
            if (sigv == null || sigv.size() == 0) {
                // If there are no stored signature values
                if (sigVal.length != 0) {
                    // If there's no value in the case where there are no
                    // stored SV it is valid. Therefore if there IS a value 
                    // in the sig confirmation element
                    throw new WSSecurityException(
                            "WSHandler: Check Signature confirmation: got a SC element, " + "but no stored SV");
                }
            } else {
                //If we have stored signature values
                boolean found = false;
                for (int ii = 0; ii < sigv.size(); ii++) {
                    byte[] storedValue = (byte[]) sigv.get(ii);
                    if (Arrays.equals(sigVal, storedValue)) {
                        found = true;
                        sigv.remove(ii);
                        break;
                    }
                }
                if (!found) {
                    throw new WSSecurityException(
                            "WSHandler: Check Signature confirmation: got SC element, " + "but no matching SV");
                }
            }
        }
    }

    /*
     * This indicates this is the last handler: the vector holding the
     * stored Signature values must be empty, otherwise we have an error
     */
    if (!reqData.isNoSerialization()) {
        log.debug("Check Signature confirmation - last handler");
        if (sigv != null && !sigv.isEmpty()) {
            throw new WSSecurityException(
                    "WSHandler: Check Signature confirmation: stored SV vector not empty");
        }
    }
}

From source file:de.codesourcery.eve.skills.market.impl.EveCentralMarketDataProvider.java

@Override
public Map<InventoryType, PriceInfoQueryResult> getPriceInfos(final MarketFilter filter,
        final IPriceQueryCallback callback, final InventoryType... items) throws PriceInfoUnavailableException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getPriceInfos(): filter = " + filter + ", items = " + items);
    }/*from w w w. j a v a2 s  .  c om*/

    if (ArrayUtils.isEmpty(items)) {
        return Collections.emptyMap();
    }

    final AtomicReference<Map<InventoryType, PriceInfoQueryResult>> resultHolder = new AtomicReference<Map<InventoryType, PriceInfoQueryResult>>(
            new ConcurrentHashMap<InventoryType, PriceInfoQueryResult>());

    final IUpdateStrategy updateStrategy = createUpdateStrategy(filter.getUpdateMode(), filter.getOrderType());

    final Vector<NameValuePair> params = new Vector<NameValuePair>();

    /*
     * NEEDS to be run on the EDT since Hibernate
     * lazy-fetching might kick in and
     * the Hibernate session is confined to the EDT.
     */
    runOnEDT(new Runnable() {

        @Override
        public void run() {
            if (LOG.isDebugEnabled()) {
                LOG.debug("getPriceInfos(): update_strategy = " + updateStrategy);
            }

            for (InventoryType t : items) {

                // make sure we don't query over and over
                // for prices that are unavailable anyway
                if (isPriceMissingOnEveCentral(filter, t)) {
                    if (!mayQueryAgainForMissingPrice(filter, t)) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("getPriceInfos(): " + "Price for " + t + " "
                                    + "unavailable on eve-central , filter " + filter);
                        }
                        continue;
                    }

                    if (LOG.isDebugEnabled()) {
                        LOG.debug("getPriceInfos(): [ retrying ] " + "Price for " + t + " "
                                + "unavailable on eve-central , filter " + filter);
                    }
                }

                final PriceInfoQueryResult cached = getCachedEntry(filter, t);

                resultHolder.get().put(t, cached);

                if (LOG.isDebugEnabled()) {

                    if (cached.isEmpty()) {
                        LOG.debug("getPriceInfos(): [ NOT CACHED ] type = " + t.getId() + " , name = "
                                + t.getName());
                    } else {
                        LOG.debug("getPriceInfos(): [ CACHE HIT ] " + cached);
                    }
                }

                final boolean requiresUpdate;
                switch (filter.getOrderType()) {
                case BUY:
                    requiresUpdate = updateStrategy.requiresUpdate(t,
                            cached.hasBuyPrice() ? cached.buyPrice() : null);
                    break;
                case SELL:
                    requiresUpdate = updateStrategy.requiresUpdate(t,
                            cached.hasSellPrice() ? cached.sellPrice() : null);
                    break;
                case ANY:
                    requiresUpdate = (updateStrategy.requiresUpdate(t,
                            cached.hasBuyPrice() ? cached.buyPrice() : null)
                            || updateStrategy.requiresUpdate(t,
                                    cached.hasSellPrice() ? cached.sellPrice() : null));
                    break;
                default:
                    throw new RuntimeException("Unhandled switch/case: " + filter.getOrderType());
                }

                if (LOG.isDebugEnabled()) {
                    LOG.debug("getPriceInfos(): [ " + updateStrategy + "] requires_update => " + requiresUpdate
                            + " , type=" + t.getName());
                }

                if (requiresUpdate) {
                    params.add(new BasicNameValuePair("typeid", t.getId().toString()));
                }
            }
        }
    });

    if (params.isEmpty() || isOfflineMode()) { // all entries served from cache
        return resultHolder.get();
    }

    addFilterToRequest(params, filter);

    /*
     * Query data from eve central
     */
    final String responseXmlFromServer = eveCentralClient.sendRequestToServer(params);
    final AtomicReference<String> xml = new AtomicReference<String>(responseXmlFromServer);

    /*
     * NEEDS to be run on the EDT since Hibernate
     * lazy-fetching might kick in and
     * the Hibernate session is confined to the EDT.
     */
    return runOnEventThread(new PriceCallable() {

        public Map<InventoryType, PriceInfoQueryResult> call() throws PriceInfoUnavailableException {
            final Map<InventoryType, PriceInfoQueryResult> realResult = resultHolder.get();

            final Map<Long, List<PriceInfo>> result = parsePriceInfo(filter, xml.get());

            // group prices by item types

            List<PriceInfo> updated = new ArrayList<>();
            try {
                for (InventoryType type : items) {
                    List<PriceInfo> info = result.get(type.getId());

                    if (info == null || info.isEmpty()) {
                        // failed to fetch data, query user 
                        rememberPriceMissingOnEveCentral(filter, type);
                        info = queryPriceFromUser(filter, callback, type);
                    }

                    forgetPriceMissingOnEveCentral(filter, type);

                    for (PriceInfo dataFromServer : info) {
                        dataFromServer.setRegion(filter.getRegion());
                        dataFromServer.setTimestamp(new EveDate(systemClock));
                        dataFromServer.setInventoryType(type);

                        final PriceInfoQueryResult cachedResult = realResult.get(type);

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("getPriceInfos(): from server: " + dataFromServer + " , cached="
                                    + cachedResult);
                        }

                        PriceInfo existing;
                        switch (filter.getOrderType()) {
                        case BUY:
                            existing = cachedResult.hasBuyPrice() ? cachedResult.buyPrice() : null;
                            if (updateStrategy.requiresUpdate(type, existing)) {
                                LOG.debug("getPriceInfos(): merging buy price.");
                                realResult.put(type, cachedResult.merge(filter.getOrderType(), dataFromServer));
                                storeCacheEntry(dataFromServer);
                                updated.add(dataFromServer);
                            }
                            break;
                        case SELL:
                            existing = cachedResult.hasSellPrice() ? cachedResult.sellPrice() : null;
                            if (updateStrategy.requiresUpdate(type, existing)) {
                                LOG.debug("getPriceInfos(): merging sell price.");
                                realResult.put(type, cachedResult.merge(filter.getOrderType(), dataFromServer));
                                storeCacheEntry(dataFromServer);
                                updated.add(dataFromServer);
                            }
                            break;
                        case ANY:
                            existing = cachedResult.hasBuyPrice() ? cachedResult.buyPrice() : null;
                            if (updateStrategy.requiresUpdate(type, existing)) {
                                LOG.debug("getPriceInfos(): merging buy price.");
                                realResult.put(type, cachedResult.merge(PriceInfo.Type.BUY, dataFromServer));
                                storeCacheEntry(dataFromServer);
                                updated.add(dataFromServer);
                            }
                            existing = cachedResult.hasSellPrice() ? cachedResult.sellPrice() : null;
                            if (updateStrategy.requiresUpdate(type, existing)) {
                                LOG.debug("getPriceInfos(): merging sell price.");
                                realResult.put(type, cachedResult.merge(PriceInfo.Type.SELL, dataFromServer));
                                storeCacheEntry(dataFromServer);
                                updated.add(dataFromServer);
                            }
                            break;
                        default:
                            throw new RuntimeException("Unhandled switch/case: " + filter.getOrderType());
                        }
                    }
                }
            } finally {
                fireItemPriceChanged(updated);
            }
            return realResult;
        }
    });
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Serve the specified resource, optionally including the data content.
 *
 * @param context  The servlet request we are processing
 * @param content  Should the content be included?
 * @param method  Description of the Parameter
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet-specified error occurs
 *///from  w w  w  .  j  a v a2  s  .  com
protected void serveResource(ActionContext context, boolean content, String method)
        throws IOException, ServletException {

    //TODO: remove this hardcoding
    debug = 2;
    // Identify the requested resource path
    String path = getRelativePath(context.getRequest());

    if (path.indexOf("/.") > -1) {
        //MAC OSX Fix
        return;
    }

    if (debug > 0) {
        if (content) {
            log("DefaultServlet.serveResource:  Serving resource '" + path + "' headers and data");
        } else {
            log("DefaultServlet.serveResource:  Serving resource '" + path + "' headers only");
        }
    }

    // Retrieve the Catalina context and Resources implementation

    Connection db = null;
    ModuleContext resources = null;
    ResourceInfo resourceInfo = null;
    SystemStatus thisSystem = null;
    boolean status = true;
    try {
        //System.out.println("DefaultServlet-> Serving Resource " + (content ? "WITH CONTENT" : "WITHOUT CONTENT"));
        db = this.getConnection(context);
        resources = getCFSResources(db, context);
        if (resources == null) {
            context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        thisSystem = this.getSystemStatus(context);
        if (method.equals(METHOD_GET)) {
            Object current = resources.lookup(thisSystem, db, path);
        }
        resourceInfo = new ResourceInfo(thisSystem, path, resources);
    } catch (SQLException e) {
        e.printStackTrace(System.out);
        context.getResponse().sendError(CFS_SQLERROR, e.getMessage());
        status = false;
    } catch (Exception e) {
    } finally {
        this.freeConnection(db, context);
    }
    if (!status) {
        return;
    }

    if (!resourceInfo.exists) {
        context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, context.getRequest().getRequestURI());
        return;
    }

    // If the resource is not a collection, and the resource path
    // ends with "/" or "\", return NOT FOUND
    if (!resourceInfo.collection) {
        if (path.endsWith("/") || (path.endsWith("\\"))) {
            context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND,
                    context.getRequest().getRequestURI());
            return;
        }
    }

    // Check if the conditions specified in the optional If headers are
    // satisfied.
    if (!resourceInfo.collection) {

        // Checking If headers
        boolean included = (context.getRequest().getAttribute(Globals.INCLUDE_CONTEXT_PATH_ATTR) != null);
        if (!included && !checkIfHeaders(context.getRequest(), context.getResponse(), resourceInfo)) {
            return;
        }
    }

    // Find content type
    String contentType = getServletContext().getMimeType(resourceInfo.clientFilename);

    Vector ranges = null;

    if (resourceInfo.collection) {

        // Skip directory listings if we have been configured to
        // suppress them
        if (!listings) {
            context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND,
                    context.getRequest().getRequestURI());
            return;
        }
        contentType = "text/html;charset=UTF-8";

    } else {
        // Parse range specifier
        ranges = parseRange(context.getRequest(), context.getResponse(), resourceInfo);
        // ETag header
        context.getResponse().setHeader("ETag", getETag(resourceInfo));
        // Last-Modified header
        if (debug > 0) {
            log("DefaultServlet.serveFile:  lastModified='" + (new Timestamp(resourceInfo.date)).toString()
                    + "'");
        }
        context.getResponse().setHeader("Last-Modified", resourceInfo.httpDate);
    }

    ServletOutputStream ostream = null;
    PrintWriter writer = null;

    if (content) {
        // Trying to retrieve the servlet output stream
        try {
            ostream = context.getResponse().getOutputStream();
        } catch (IllegalStateException e) {
            // If it fails, we try to get a Writer instead if we're
            // trying to serve a text file
            if ((contentType == null) || (contentType.startsWith("text"))) {
                writer = context.getResponse().getWriter();
            } else {
                throw e;
            }
        }
    }

    if ((resourceInfo.collection) || (((ranges == null) || (ranges.isEmpty()))
            && (context.getRequest().getHeader("Range") == null))) {

        // Set the appropriate output headers
        if (contentType != null) {
            if (debug > 0) {
                log("DefaultServlet.serveFile:  contentType='" + contentType + "'");
            }
            context.getResponse().setContentType(contentType);
        }
        long contentLength = resourceInfo.length;
        if ((!resourceInfo.collection) && (contentLength >= 0)) {
            if (debug > 0) {
                log("DefaultServlet.serveFile:  contentLength=" + contentLength);
            }
            context.getResponse().setContentLength((int) contentLength);
        }
        if (resourceInfo.collection) {
            if (content) {
                // Serve the directory browser
                resourceInfo.setStream(render(context.getRequest().getContextPath(), resourceInfo));
            }
        }
        // Copy the input stream to our output stream (if requested)
        if (content) {
            try {
                context.getResponse().setBufferSize(output);
            } catch (IllegalStateException e) {
                // Silent catch
            }
            if (ostream != null) {
                copy(resourceInfo, ostream);
            } else {
                copy(resourceInfo, writer);
            }
        }
    } else {
        if ((ranges == null) || (ranges.isEmpty())) {
            return;
        }
        // Partial content response.
        context.getResponse().setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        if (ranges.size() == 1) {
            Range range = (Range) ranges.elementAt(0);
            context.getResponse().addHeader("Content-Range",
                    "bytes " + range.start + "-" + range.end + "/" + range.length);
            context.getResponse().setContentLength((int) (range.end - range.start + 1));

            if (contentType != null) {
                if (debug > 0) {
                    log("DefaultServlet.serveFile:  contentType='" + contentType + "'");
                }
                context.getResponse().setContentType(contentType);
            }

            if (content) {
                try {
                    context.getResponse().setBufferSize(output);
                } catch (IllegalStateException e) {
                    // Silent catch
                }
                if (ostream != null) {
                    copy(resourceInfo, ostream, range);
                } else {
                    copy(resourceInfo, writer, range);
                }
            }
        } else {

            context.getResponse().setContentType("multipart/byteranges; boundary=" + mimeSeparation);

            if (content) {
                try {
                    context.getResponse().setBufferSize(output);
                } catch (IllegalStateException e) {
                    // Silent catch
                }
                if (ostream != null) {
                    copy(resourceInfo, ostream, ranges.elements(), contentType);
                } else {
                    copy(resourceInfo, writer, ranges.elements(), contentType);
                }
            }
        }
    }
}

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//w w w . j a va2 s  .c o  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:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * LOCK Method.//from w w  w.  j av  a2s. c  o  m
 *
 * @param req  Description of the Parameter
 * @param resp Description of the Parameter
 * @throws javax.servlet.ServletException Description of the Exception
 * @throws java.io.IOException            Description of the Exception
 */
protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (readOnly) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }

    WebdavServlet.LockInfo lock = new WebdavServlet.LockInfo();

    // Parsing lock request

    // Parsing depth header

    String depthStr = req.getHeader("Depth");

    if (depthStr == null) {
        lock.depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            lock.depth = 0;
        } else {
            lock.depth = INFINITY;
        }
    }

    // Parsing timeout header

    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = req.getHeader("Timeout");
    if (lockDurationStr == null) {
        lockDuration = DEFAULT_TIMEOUT;
    } else {
        int commaPos = lockDurationStr.indexOf(",");
        // If multiple timeouts, just use the first
        if (commaPos != -1) {
            lockDurationStr = lockDurationStr.substring(0, commaPos);
        }
        if (lockDurationStr.startsWith("Second-")) {
            lockDuration = (new Integer(lockDurationStr.substring(7))).intValue();
        } else {
            if (lockDurationStr.equalsIgnoreCase("infinity")) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = (new Integer(lockDurationStr)).intValue();
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000);

    int lockRequestType = LOCK_CREATION;

    Node lockInfoNode = null;

    DocumentBuilder documentBuilder = getDocumentBuilder();

    try {
        Document document = documentBuilder.parse(new InputSource(req.getInputStream()));

        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (Exception e) {
        lockRequestType = LOCK_REFRESH;
    }

    if (lockInfoNode != null) {

        // Reading lock information

        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;

        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;

        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                if (nodeName.endsWith("lockscope")) {
                    lockScopeNode = currentNode;
                }
                if (nodeName.endsWith("locktype")) {
                    lockTypeNode = currentNode;
                }
                if (nodeName.endsWith("owner")) {
                    lockOwnerNode = currentNode;
                }
                break;
            }
        }

        if (lockScopeNode != null) {

            childList = lockScopeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempScope = currentNode.getNodeName();
                    if (tempScope.indexOf(':') != -1) {
                        lock.scope = tempScope.substring(tempScope.indexOf(':') + 1);
                    } else {
                        lock.scope = tempScope;
                    }
                    break;
                }
            }

            if (lock.scope == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockTypeNode != null) {

            childList = lockTypeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempType = currentNode.getNodeName();
                    if (tempType.indexOf(':') != -1) {
                        lock.type = tempType.substring(tempType.indexOf(':') + 1);
                    } else {
                        lock.type = tempType;
                    }
                    break;
                }
            }

            if (lock.type == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockOwnerNode != null) {

            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    lock.owner += currentNode.getNodeValue();
                    break;
                case Node.ELEMENT_NODE:
                    strWriter = new StringWriter();
                    domWriter = new DOMWriter(strWriter, true);
                    domWriter.setQualifiedNames(false);
                    domWriter.print(currentNode);
                    lock.owner += strWriter.toString();
                    break;
                }
            }

            if (lock.owner == null) {
                // Bad request
                resp.setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            lock.owner = new String();
        }

    }

    String path = getRelativePath(req);

    lock.path = path;

    // Retrieve the resources
    DirContext resources = getResources();

    if (resources == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    boolean exists = true;
    Object object = null;
    try {
        object = resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    Enumeration locksList = null;

    if (lockRequestType == LOCK_CREATION) {

        // Generating lock id
        String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-"
                + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-"
                + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret;
        String lockToken = md5Encoder.encode(md5Helper.digest(lockTokenStr.getBytes()));

        if ((exists) && (object instanceof DirContext) && (lock.depth == INFINITY)) {

            // Locking a collection (and all its member resources)

            // Checking if a child resource of this collection is
            // already locked
            Vector lockPaths = new Vector();
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child collection of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }
            locksList = resourceLocks.elements();
            while (locksList.hasMoreElements()) {
                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child resource of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }

            if (!lockPaths.isEmpty()) {

                // One of the child paths was locked
                // We generate a multistatus error report

                Enumeration lockPathsList = lockPaths.elements();

                resp.setStatus(WebdavStatus.SC_CONFLICT);

                XMLWriter generatedXML = new XMLWriter();
                generatedXML.writeXMLHeader();

                generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                        XMLWriter.OPENING);

                while (lockPathsList.hasMoreElements()) {
                    generatedXML.writeElement(null, "response", XMLWriter.OPENING);
                    generatedXML.writeElement(null, "href", XMLWriter.OPENING);
                    generatedXML.writeText((String) lockPathsList.nextElement());
                    generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
                    generatedXML.writeElement(null, "status", XMLWriter.OPENING);
                    generatedXML.writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " "
                            + WebdavStatus.getStatusText(WebdavStatus.SC_LOCKED));
                    generatedXML.writeElement(null, "status", XMLWriter.CLOSING);

                    generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
                }

                generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);

                Writer writer = resp.getWriter();
                writer.write(generatedXML.toString());
                writer.close();

                return;
            }

            boolean addLock = true;

            // Checking if there is already a shared lock on this path
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {

                WebdavServlet.LockInfo currentLock = (WebdavServlet.LockInfo) locksList.nextElement();
                if (currentLock.path.equals(lock.path)) {

                    if (currentLock.isExclusive()) {
                        resp.sendError(WebdavStatus.SC_LOCKED);
                        return;
                    } else {
                        if (lock.isExclusive()) {
                            resp.sendError(WebdavStatus.SC_LOCKED);
                            return;
                        }
                    }

                    currentLock.tokens.addElement(lockToken);
                    lock = currentLock;
                    addLock = false;

                }
            }

            if (addLock) {
                lock.tokens.addElement(lockToken);
                collectionLocks.addElement(lock);
            }
        } else {

            // Locking a single resource

            // Retrieving an already existing lock on that resource
            WebdavServlet.LockInfo presentLock = (WebdavServlet.LockInfo) resourceLocks.get(lock.path);
            if (presentLock != null) {

                if ((presentLock.isExclusive()) || (lock.isExclusive())) {
                    // If either lock is exclusive, the lock can't be
                    // granted
                    resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
                    return;
                } else {
                    presentLock.tokens.addElement(lockToken);
                    lock = presentLock;
                }

            } else {

                lock.tokens.addElement(lockToken);
                resourceLocks.put(lock.path, lock);

                // Checking if a resource exists at this path
                exists = true;
                try {
                    object = resources.lookup(path);
                } catch (NamingException e) {
                    exists = false;
                }
                if (!exists) {

                    // "Creating" a lock-null resource
                    int slash = lock.path.lastIndexOf('/');
                    String parentPath = lock.path.substring(0, slash);

                    Vector lockNulls = (Vector) lockNullResources.get(parentPath);
                    if (lockNulls == null) {
                        lockNulls = new Vector();
                        lockNullResources.put(parentPath, lockNulls);
                    }

                    lockNulls.addElement(lock.path);

                }
                // Add the Lock-Token header as by RFC 2518 8.10.1
                // - only do this for newly created locks
                resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">");
            }

        }

    }

    if (lockRequestType == LOCK_REFRESH) {

        String ifHeader = req.getHeader("If");
        if (ifHeader == null) {
            ifHeader = "";
        }

        // Checking resource locks

        WebdavServlet.LockInfo toRenew = (WebdavServlet.LockInfo) resourceLocks.get(path);
        Enumeration tokenList = null;
        if (lock != null) {

            // At least one of the tokens of the locks must have been given

            tokenList = toRenew.tokens.elements();
            while (tokenList.hasMoreElements()) {
                String token = (String) tokenList.nextElement();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.expiresAt = lock.expiresAt;
                    lock = toRenew;
                }
            }

        }

        // Checking inheritable collection locks

        Enumeration collectionLocksList = collectionLocks.elements();
        while (collectionLocksList.hasMoreElements()) {
            toRenew = (WebdavServlet.LockInfo) collectionLocksList.nextElement();
            if (path.equals(toRenew.path)) {

                tokenList = toRenew.tokens.elements();
                while (tokenList.hasMoreElements()) {
                    String token = (String) tokenList.nextElement();
                    if (ifHeader.indexOf(token) != -1) {
                        toRenew.expiresAt = lock.expiresAt;
                        lock = toRenew;
                    }
                }

            }
        }

    }

    // Set the status, then generate the XML response containing
    // the lock information
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "prop" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.OPENING);

    lock.toXML(generatedXML);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.CLOSING);

    generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);

    resp.setStatus(WebdavStatus.SC_OK);
    resp.setContentType("text/xml; charset=UTF-8");
    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();

}

From source file:com.zeroio.webdav.WebdavServlet.java

/**
 * LOCK Method.//w w  w. j  av  a 2 s. c  om
 *
 * @param context Description of the Parameter
 * @throws ServletException Description of the Exception
 * @throws IOException      Description of the Exception
 */
protected void doLock(ActionContext context) throws ServletException, IOException {

    if (readOnly) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(context.getRequest())) {
        context.getResponse().sendError(WebdavStatus.SC_LOCKED);
        return;
    }

    LockInfo lock = new LockInfo();

    // Parsing lock request

    // Parsing depth header

    String depthStr = context.getRequest().getHeader("Depth");

    if (depthStr == null) {
        lock.depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            lock.depth = 0;
        } else {
            lock.depth = INFINITY;
        }
    }
    // Parsing timeout header

    int lockDuration = DEFAULT_TIMEOUT;
    String lockDurationStr = context.getRequest().getHeader("Timeout");
    if (lockDurationStr == null) {
        lockDuration = DEFAULT_TIMEOUT;
    } else {
        int commaPos = lockDurationStr.indexOf(",");
        // If multiple timeouts, just use the first
        if (commaPos != -1) {
            lockDurationStr = lockDurationStr.substring(0, commaPos);
        }
        if (lockDurationStr.startsWith("Second-")) {
            lockDuration = (new Integer(lockDurationStr.substring(7))).intValue();
        } else {
            if (lockDurationStr.equalsIgnoreCase("infinity")) {
                lockDuration = MAX_TIMEOUT;
            } else {
                try {
                    lockDuration = (new Integer(lockDurationStr)).intValue();
                } catch (NumberFormatException e) {
                    lockDuration = MAX_TIMEOUT;
                }
            }
        }
        if (lockDuration == 0) {
            lockDuration = DEFAULT_TIMEOUT;
        }
        if (lockDuration > MAX_TIMEOUT) {
            lockDuration = MAX_TIMEOUT;
        }
    }
    lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000);

    int lockRequestType = LOCK_CREATION;

    Node lockInfoNode = null;

    DocumentBuilder documentBuilder = getDocumentBuilder();

    try {
        Document document = documentBuilder.parse(new InputSource(context.getRequest().getInputStream()));

        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        lockInfoNode = rootElement;
    } catch (Exception e) {
        lockRequestType = LOCK_REFRESH;
    }

    if (lockInfoNode != null) {

        // Reading lock information

        NodeList childList = lockInfoNode.getChildNodes();
        StringWriter strWriter = null;
        DOMWriter domWriter = null;

        Node lockScopeNode = null;
        Node lockTypeNode = null;
        Node lockOwnerNode = null;

        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                if (nodeName.endsWith("lockscope")) {
                    lockScopeNode = currentNode;
                }
                if (nodeName.endsWith("locktype")) {
                    lockTypeNode = currentNode;
                }
                if (nodeName.endsWith("owner")) {
                    lockOwnerNode = currentNode;
                }
                break;
            }
        }

        if (lockScopeNode != null) {

            childList = lockScopeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempScope = currentNode.getNodeName();
                    if (tempScope.indexOf(':') != -1) {
                        lock.scope = tempScope.substring(tempScope.indexOf(':') + 1);
                    } else {
                        lock.scope = tempScope;
                    }
                    break;
                }
            }

            if (lock.scope == null) {
                // Bad request
                context.getResponse().setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            context.getResponse().setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockTypeNode != null) {

            childList = lockTypeNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    String tempType = currentNode.getNodeName();
                    if (tempType.indexOf(':') != -1) {
                        lock.type = tempType.substring(tempType.indexOf(':') + 1);
                    } else {
                        lock.type = tempType;
                    }
                    break;
                }
            }

            if (lock.type == null) {
                // Bad request
                context.getResponse().setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            // Bad request
            context.getResponse().setStatus(WebdavStatus.SC_BAD_REQUEST);
        }

        if (lockOwnerNode != null) {

            childList = lockOwnerNode.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    lock.owner += currentNode.getNodeValue();
                    break;
                case Node.ELEMENT_NODE:
                    strWriter = new StringWriter();
                    domWriter = new DOMWriter(strWriter, true);
                    domWriter.setQualifiedNames(false);
                    domWriter.print(currentNode);
                    lock.owner += strWriter.toString();
                    break;
                }
            }

            if (lock.owner == null) {
                // Bad request
                context.getResponse().setStatus(WebdavStatus.SC_BAD_REQUEST);
            }
        } else {
            lock.owner = new String();
        }

    }

    String path = getRelativePath(context.getRequest());

    //Fix for MACOSX finder. Do not allow requests for files starting with a period
    if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) {
        return;
    }

    lock.path = path;

    // Retrieve the resources
    DirContext resources = getResources();

    if (resources == null) {
        context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    boolean exists = true;
    Object object = null;
    try {
        object = resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    Enumeration locksList = null;

    if (lockRequestType == LOCK_CREATION) {

        // Generating lock id
        String lockTokenStr = context.getRequest().getServletPath() + "-" + lock.type + "-" + lock.scope + "-"
                + context.getRequest().getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-"
                + lock.tokens + "-" + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret;
        String lockToken = md5Encoder.encode(md5Helper.digest(lockTokenStr.getBytes()));

        if ((exists) && (object instanceof DirContext) && (lock.depth == INFINITY)) {

            // Locking a collection (and all its member resources)

            // Checking if a child resource of this collection is
            // already locked
            Vector lockPaths = new Vector();
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child collection of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }
            locksList = resourceLocks.elements();
            while (locksList.hasMoreElements()) {
                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.hasExpired()) {
                    resourceLocks.remove(currentLock.path);
                    continue;
                }
                if ((currentLock.path.startsWith(lock.path))
                        && ((currentLock.isExclusive()) || (lock.isExclusive()))) {
                    // A child resource of this collection is locked
                    lockPaths.addElement(currentLock.path);
                }
            }

            if (!lockPaths.isEmpty()) {

                // One of the child paths was locked
                // We generate a multistatus error report

                Enumeration lockPathsList = lockPaths.elements();

                context.getResponse().setStatus(WebdavStatus.SC_CONFLICT);

                XMLWriter generatedXML = new XMLWriter();
                generatedXML.writeXMLHeader();

                generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                        XMLWriter.OPENING);

                while (lockPathsList.hasMoreElements()) {
                    generatedXML.writeElement(null, "response", XMLWriter.OPENING);
                    generatedXML.writeElement(null, "href", XMLWriter.OPENING);
                    generatedXML.writeText((String) lockPathsList.nextElement());
                    generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
                    generatedXML.writeElement(null, "status", XMLWriter.OPENING);
                    generatedXML.writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " "
                            + WebdavStatus.getStatusText(WebdavStatus.SC_LOCKED));
                    generatedXML.writeElement(null, "status", XMLWriter.CLOSING);

                    generatedXML.writeElement(null, "response", XMLWriter.CLOSING);
                }

                generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);

                Writer writer = context.getResponse().getWriter();
                writer.write(generatedXML.toString());
                writer.close();

                return;
            }

            boolean addLock = true;

            // Checking if there is already a shared lock on this path
            locksList = collectionLocks.elements();
            while (locksList.hasMoreElements()) {

                LockInfo currentLock = (LockInfo) locksList.nextElement();
                if (currentLock.path.equals(lock.path)) {

                    if (currentLock.isExclusive()) {
                        context.getResponse().sendError(WebdavStatus.SC_LOCKED);
                        return;
                    } else {
                        if (lock.isExclusive()) {
                            context.getResponse().sendError(WebdavStatus.SC_LOCKED);
                            return;
                        }
                    }

                    currentLock.tokens.addElement(lockToken);
                    lock = currentLock;
                    addLock = false;

                }
            }

            if (addLock) {
                lock.tokens.addElement(lockToken);
                collectionLocks.addElement(lock);
            }
        } else {

            // Locking a single resource

            // Retrieving an already existing lock on that resource
            LockInfo presentLock = (LockInfo) resourceLocks.get(lock.path);
            if (presentLock != null) {

                if ((presentLock.isExclusive()) || (lock.isExclusive())) {
                    // If either lock is exclusive, the lock can't be
                    // granted
                    context.getResponse().sendError(WebdavStatus.SC_PRECONDITION_FAILED);
                    return;
                } else {
                    presentLock.tokens.addElement(lockToken);
                    lock = presentLock;
                }

            } else {

                lock.tokens.addElement(lockToken);
                resourceLocks.put(lock.path, lock);

                // Checking if a resource exists at this path
                exists = true;
                try {
                    object = resources.lookup(path);
                } catch (NamingException e) {
                    exists = false;
                }
                if (!exists) {

                    // "Creating" a lock-null resource
                    int slash = lock.path.lastIndexOf('/');
                    String parentPath = lock.path.substring(0, slash);

                    Vector lockNulls = (Vector) lockNullResources.get(parentPath);
                    if (lockNulls == null) {
                        lockNulls = new Vector();
                        lockNullResources.put(parentPath, lockNulls);
                    }

                    //System.out.println("ADDED LOCK AT PATH: " + lock.path);
                    lockNulls.addElement(lock.path);

                }
                // Add the Lock-Token header as by RFC 2518 8.10.1
                // - only do this for newly created locks
                context.getResponse().addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">");
            }

        }

    }

    if (lockRequestType == LOCK_REFRESH) {

        String ifHeader = context.getRequest().getHeader("If");
        if (ifHeader == null) {
            ifHeader = "";
        }

        // Checking resource locks

        LockInfo toRenew = (LockInfo) resourceLocks.get(path);
        Enumeration tokenList = null;
        if (lock != null) {

            // At least one of the tokens of the locks must have been given

            tokenList = toRenew.tokens.elements();
            while (tokenList.hasMoreElements()) {
                String token = (String) tokenList.nextElement();
                if (ifHeader.indexOf(token) != -1) {
                    toRenew.expiresAt = lock.expiresAt;
                    lock = toRenew;
                }
            }

        }

        // Checking inheritable collection locks

        Enumeration collectionLocksList = collectionLocks.elements();
        while (collectionLocksList.hasMoreElements()) {
            toRenew = (LockInfo) collectionLocksList.nextElement();
            if (path.equals(toRenew.path)) {

                tokenList = toRenew.tokens.elements();
                while (tokenList.hasMoreElements()) {
                    String token = (String) tokenList.nextElement();
                    if (ifHeader.indexOf(token) != -1) {
                        toRenew.expiresAt = lock.expiresAt;
                        lock = toRenew;
                    }
                }

            }
        }

    }

    // Set the status, then generate the XML response containing
    // the lock information
    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "prop" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.OPENING);

    lock.toXML(generatedXML);

    generatedXML.writeElement(null, "lockdiscovery", XMLWriter.CLOSING);

    generatedXML.writeElement(null, "prop", XMLWriter.CLOSING);

    context.getResponse().setStatus(WebdavStatus.SC_OK);
    context.getResponse().setContentType("text/xml; charset=UTF-8");
    Writer writer = context.getResponse().getWriter();
    writer.write(generatedXML.toString());
    writer.close();

}

From source file:edu.ku.brc.dbsupport.ImportExportDB.java

@SuppressWarnings("unchecked")
    protected void singleXMLImport(Element dbImport, String dbTable, String parentName, long parentId, int id,
            boolean recursion) {
        try {// w ww.jav a  2  s .  c o  m
            DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());
            String lowerdbTable = lowerFirstChar(dbTable);
            String primaryKey = parentInfo.getPrimaryKeyName();

            Vector collectionIds = new Vector(20);
            Vector collectionNames = new Vector(20);
            // make the agent and the element
            Object agent = parentInfo.getClassObj().newInstance();
            Map<String, Object> agentMap = new HashMap<String, Object>();
            Element dbElement = dbImport;
            Iterator i = dbElement.elementIterator();
            do {// do for each element in the record
                Element element = (Element) i.next();

                Object value = findTypeSequential(element, dbTable, parentId, parentName);// the
                                                                                          // parent
                                                                                          // is
                                                                                          // itself,
                                                                                          // just
                                                                                          // a
                                                                                          // dummy
                                                                                          // variable
                                                                                          // if(value!=null && value != "collection")
                if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                {
                    agentMap.put(element.getName(), value);
                }
                // ignore many-to-many for now
                else if (recursion && (value == "OneToMany" || value == "ManyToMany")) //$NON-NLS-1$ //$NON-NLS-2$
                {// RECURSE
                 // get assoicated ids
                    List temp_collection_ids = element.selectNodes("//" + dbTable + "[" //$NON-NLS-1$ //$NON-NLS-2$
                            + primaryKey + " = \"" + id + "\"]/" + element.getName() + "/*"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    // get collection info and still dont add it
                    if (!temp_collection_ids.isEmpty()) {
                        // get child dbName
                        String childDbName = getDbName(temp_collection_ids);
                        collectionNames.addElement(childDbName);
                        for (int index = 0; index < temp_collection_ids.size(); index++) {
                            collectionIds.addElement(temp_collection_ids.get(index));
                        }
                    }
                } else
                // else, dont add it
                {
                    // if it is an id, just ignore. otherwise print out error
                    if (!element.getName().equals(lowerdbTable + "Id")) //$NON-NLS-1$
                    {
                        log.debug("did not add " + element.getName() + " to the element " //$NON-NLS-1$ //$NON-NLS-2$
                                + dbTable);
                    }
                }
            } while (i.hasNext());

            // populate and save
            BeanUtils.populate(agent, agentMap);

            this.session.save(agent);

            // if there was a collection, then recurse
            if (!collectionIds.isEmpty()) {
                long newParentId = new Long(session.getIdentifier(agent).toString()).longValue();

                sequentialXMLImportRecursion(collectionNames, collectionIds, dbTable, newParentId);
            }
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            ex.printStackTrace();
        }
    }

From source file:edu.ku.brc.dbsupport.ImportExportDB.java

@SuppressWarnings("unchecked")
    protected Map buildSingleDataBaseObjectFromXMLTemp(Element dbImport, String dbTable, String parentName,
            long parentId, int id, boolean recursion) {
        //Object dbObject = new Object();
        Map<String, Object> agentMap = new HashMap<String, Object>();
        try {//from  w  w w  .j  a va 2s  .c om
            DBTableInfo parentInfo = DBTableIdMgr.getInstance().getInfoByTableName(dbTable.toLowerCase());
            //String lowerdbTable = lowerFirstChar(dbTable);
            String primaryKey = parentInfo.getPrimaryKeyName();

            Vector collectionIds = new Vector(20);
            Vector collectionNames = new Vector(20);
            // make the agent and the element
            Object agent = parentInfo.getClassObj().newInstance();

            Element dbElement = dbImport;
            Iterator i = dbElement.elementIterator();
            do {// do for each element in the record
                Element element = (Element) i.next();

                // Object value = findTypeSequential(element, dbTable, parentId, parentName );//the
                // parent is itself, just a dummy variable
                Object value = findTypeDataBaseParent(element, dbTable, parentId, parentName);// the
                                                                                              // parent
                                                                                              // is
                                                                                              // itself,
                                                                                              // just
                                                                                              // a
                                                                                              // dummy
                                                                                              // variable
                if (value != null && value != "OneToMany" && value != "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                {
                    agentMap.put(element.getName(), value);
                }
                // ignore many-to-many for now
                else if (value == "OneToMany" || value == "ManyToMany") //$NON-NLS-1$ //$NON-NLS-2$
                {// RECURSE
                    if (recursion) {
                        // get assoicated ids
                        List temp_collection_ids = element.selectNodes("//" + dbTable + "[" //$NON-NLS-1$ //$NON-NLS-2$
                                + primaryKey + " = \"" + id + "\"]/" + element.getName() + "/*"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        // get collection info and still dont add it
                        if (!temp_collection_ids.isEmpty()) {
                            // get child dbName
                            String childDbName = getDbName(temp_collection_ids);
                            collectionNames.addElement(childDbName);
                            for (int index = 0; index < temp_collection_ids.size(); index++) {
                                collectionIds.addElement(temp_collection_ids.get(index));
                            }
                        }
                    }
                } else
                // else, dont add it
                {
                    // if it is an id, just ignore. otherwise print out error
                    if (!element.getName().equals(primaryKey)) {
                        log.debug("did not add " + element.getName() + " to the element " //$NON-NLS-1$ //$NON-NLS-2$
                                + dbTable);
                    }
                }
            } while (i.hasNext());

            // populate
            // BeanUtils.populate(agent, agentMap);
            // save it then gets its id (assigned by Hibernate)
            // this.session.save(agent);

            // if there was a collection, then recurse
            if (!collectionIds.isEmpty()) {
                long newParentId = new Long(session.getIdentifier(agent).toString()).longValue();

                sequentialXMLImportRecursion(collectionNames, collectionIds, dbTable, newParentId);
            }
            //dbObject = agent;
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex);
            ex.printStackTrace();
        }

        return agentMap;
    }