Example usage for java.util Hashtable isEmpty

List of usage examples for java.util Hashtable isEmpty

Introduction

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

Prototype

public synchronized boolean isEmpty() 

Source Link

Document

Tests if this hashtable maps no keys to values.

Usage

From source file:org.apache.synapse.transport.passthru.util.PassThroughTransportUtils.java

/**
 * Returns the HTML text for the list of services deployed.
 * This can be delegated to another Class as well
 * where it will handle more options of GET messages.
 *
 * @param prefix to be used for the Service names
 * @param cfgCtx axis2 configuration context
 * @return the HTML to be displayed as a String
 *///w w  w  .j av a2 s  .  c  om
public String getServicesHTML(String prefix, ConfigurationContext cfgCtx) {

    Map services = cfgCtx.getAxisConfiguration().getServices();
    Hashtable erroneousServices = cfgCtx.getAxisConfiguration().getFaultyServices();
    boolean servicesFound = false;

    StringBuffer resultBuf = new StringBuffer();
    resultBuf.append("<html><head><title>Axis2: Services</title></head>" + "<body>");

    if ((services != null) && !services.isEmpty()) {

        servicesFound = true;
        resultBuf.append("<h2>" + "Deployed services" + "</h2>");

        for (Object service : services.values()) {

            AxisService axisService = (AxisService) service;
            Parameter parameter = axisService.getParameter(PassThroughConstants.HIDDEN_SERVICE_PARAM_NAME);
            if (axisService.getName().startsWith("__")
                    || (parameter != null && JavaUtils.isTrueExplicitly(parameter.getValue()))) {
                continue; // skip private services
            }

            Iterator iterator = axisService.getOperations();
            resultBuf.append("<h3><a href=\"").append(prefix).append(axisService.getName()).append("?wsdl\">")
                    .append(axisService.getName()).append("</a></h3>");

            if (iterator.hasNext()) {
                resultBuf.append("Available operations <ul>");

                for (; iterator.hasNext();) {
                    AxisOperation axisOperation = (AxisOperation) iterator.next();
                    resultBuf.append("<li>").append(axisOperation.getName().getLocalPart()).append("</li>");
                }
                resultBuf.append("</ul>");
            } else {
                resultBuf.append("No operations specified for this service");
            }
        }
    }

    if ((erroneousServices != null) && !erroneousServices.isEmpty()) {
        servicesFound = true;
        resultBuf.append("<hr><h2><font color=\"blue\">Faulty Services</font></h2>");
        Enumeration faultyservices = erroneousServices.keys();

        while (faultyservices.hasMoreElements()) {
            String faultyserviceName = (String) faultyservices.nextElement();
            resultBuf.append("<h3><font color=\"blue\">").append(faultyserviceName).append("</font></h3>");
        }
    }

    if (!servicesFound) {
        resultBuf.append("<h2>There are no services deployed</h2>");
    }

    resultBuf.append("</body></html>");
    return resultBuf.toString();
}

From source file:org.webdavaccess.servlet.WebdavServlet.java

/**
 * DELETE Method./*from ww  w. j  ava2s.  c  o  m*/
 * 
 * @param req
 *            HttpServletRequest
 * @param resp
 *            HttpServletResponse
 * @throws IOException
 *             if an error in the underlying store occurs
 */
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (!readOnly) {
        String path = getRelativePath(req);
        String lockOwner = "doDelete" + System.nanoTime() + req.toString();
        if (fResLocks.lock(path, lockOwner, true, -1)) {
            try {
                Hashtable errorList = new Hashtable();
                deleteResource(path, errorList, req, resp);
                if (!errorList.isEmpty()) {
                    sendReport(req, resp, errorList);
                }
            } catch (AccessDeniedException e) {
                log.error("WebdavServer not authenticated: ", e);
                resp.sendError(WebdavStatus.SC_FORBIDDEN);
            } catch (ObjectAlreadyExistsException e) {
                resp.sendError(WebdavStatus.SC_NOT_FOUND, req.getRequestURI());
            } catch (WebdavException e) {
                log.error("WebdavServer internal error: ", e);
                resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            } finally {
                fResLocks.unlock(path, lockOwner);
            }
        } else {
            log.error("WebdavServer unable to lock resource " + lockOwner);
            resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        log.error("WebdavServer not authenticated for write");
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
    }

}

From source file:org.webdavaccess.servlet.WebdavServlet.java

/**
 * MOVE Method./* ww  w  .  j av a2  s.  c o m*/
 * 
 * @param req
 *            HttpServletRequest
 * @param resp
 *            HttpServletResponse
 * @throws ServletException
 * @throws WebdavException
 *             if an error in the underlying store occurs
 * @throws IOException
 *             when an error occurs while sending the response
 */
protected void doMove(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (!readOnly) {

        String path = getRelativePath(req);
        String lockOwner = "doMove" + System.nanoTime() + req.toString();
        if (fResLocks.lock(path, lockOwner, false, -1)) {
            try {
                String destinationPath = copyResource(req, resp);
                if (destinationPath != null) {
                    Hashtable errorList = new Hashtable();
                    deleteResource(path, errorList, req, resp);
                    if (!errorList.isEmpty()) {
                        sendReport(req, resp, errorList);
                    }
                    if (fAliasManager != null)
                        fAliasManager.resourceMovedNotification(path, destinationPath);
                } else {
                    log.error("Destination directory in doMove cannot be empty");
                    resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
                }
            } catch (AccessDeniedException e) {
                log.error("WebdavServer not authenticated: ", e);
                resp.sendError(WebdavStatus.SC_FORBIDDEN);
            } catch (ObjectAlreadyExistsException e) {
                resp.sendError(WebdavStatus.SC_NOT_FOUND, req.getRequestURI());
            } catch (WebdavException e) {
                log.error("WebdavServer internal error: ", e);
                resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
            } finally {
                fResLocks.unlock(path, lockOwner);
            }
        } else {
            log.error("WebdavServer unable to lock resource " + lockOwner);
            resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        log.error("WebdavServer not authenticated for write");
        resp.sendError(WebdavStatus.SC_FORBIDDEN);

    }
}

From source file:org.webdavaccess.servlet.WebdavServlet.java

/**
 * Copy a resource.//from   w  w  w . ja v  a  2s  .  c  o  m
 * 
 * @param req
 *            Servlet request
 * @param resp
 *            Servlet response
 * @return true if the copy is successful
 * @throws WebdavException
 *             if an error in the underlying store occurs
 * @throws IOException
 *             when an error occurs while sending the response
 */
private String copyResource(HttpServletRequest req, HttpServletResponse resp)
        throws WebdavException, IOException {

    // Parsing destination header

    String destinationPath = req.getHeader("Destination");

    if (destinationPath == null) {
        resp.sendError(WebdavStatus.SC_BAD_REQUEST);
        return null;
    }

    // Remove url encoding from destination
    destinationPath = RequestUtil.URLDecode(destinationPath, "UTF8");

    int protocolIndex = destinationPath.indexOf("://");
    if (protocolIndex >= 0) {
        // if the Destination URL contains the protocol, we can safely
        // trim everything upto the first "/" character after "://"
        int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4);
        if (firstSeparator < 0) {
            destinationPath = "/";
        } else {
            destinationPath = destinationPath.substring(firstSeparator);
        }
    } else {
        String hostName = req.getServerName();
        if ((hostName != null) && (destinationPath.startsWith(hostName))) {
            destinationPath = destinationPath.substring(hostName.length());
        }

        int portIndex = destinationPath.indexOf(":");
        if (portIndex >= 0) {
            destinationPath = destinationPath.substring(portIndex);
        }

        if (destinationPath.startsWith(":")) {
            int firstSeparator = destinationPath.indexOf("/");
            if (firstSeparator < 0) {
                destinationPath = "/";
            } else {
                destinationPath = destinationPath.substring(firstSeparator);
            }
        }
    }

    // Normalise destination path (remove '.' and '..')
    destinationPath = normalize(destinationPath);

    String contextPath = req.getContextPath();
    if ((contextPath != null) && (destinationPath.startsWith(contextPath))) {
        destinationPath = destinationPath.substring(contextPath.length());
    }

    String path = getRelativePath(req);

    // if source = destination
    if (path.equals(destinationPath)) {
        log.error("WebdavServer cannot copy if source and destination is the same");
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
    }

    // Parsing overwrite header

    boolean overwrite = true;
    String overwriteHeader = req.getHeader("Overwrite");

    if (overwriteHeader != null) {
        overwrite = overwriteHeader.equalsIgnoreCase("T");
    }

    // Overwriting the destination
    String lockOwner = "copyResource" + System.nanoTime() + req.toString();
    if (fResLocks.lock(destinationPath, lockOwner, true, -1)) {
        try {

            // Retrieve the resources
            if (!fStore.objectExists(path)) {
                log.error("Recource to be copied does not exist " + path);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return null;
            }

            Hashtable errorList = new Hashtable();

            copy(path, destinationPath, overwrite, errorList, req, resp);
            if (!errorList.isEmpty()) {
                sendReport(req, resp, errorList);
            }

        } finally {
            fResLocks.unlock(destinationPath, lockOwner);
        }
    } else {
        log.error("WebdavServer unable to lock resource " + lockOwner);
        resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
    return destinationPath;

}

From source file:org.apache.synapse.transport.nhttp.DefaultHttpGetProcessor.java

/**
 * Returns the HTML text for the list of services deployed.
 * This can be delegated to another Class as well
 * where it will handle more options of GET messages.
 *
 * @param prefix to be used for the Service names
 * @return the HTML to be displayed as a String
 *///from www .jav a  2  s .  c  om
protected String getServicesHTML(String prefix) {

    Map services = cfgCtx.getAxisConfiguration().getServices();
    Hashtable erroneousServices = cfgCtx.getAxisConfiguration().getFaultyServices();
    boolean servicesFound = false;

    StringBuffer resultBuf = new StringBuffer();
    resultBuf.append("<html><head><title>Axis2: Services</title></head>" + "<body>");

    if ((services != null) && !services.isEmpty()) {

        servicesFound = true;
        resultBuf.append("<h2>" + "Deployed services" + "</h2>");

        for (Object service : services.values()) {

            AxisService axisService = (AxisService) service;
            Parameter parameter = axisService.getParameter(NhttpConstants.HIDDEN_SERVICE_PARAM_NAME);
            if (axisService.getName().startsWith("__")
                    || (parameter != null && JavaUtils.isTrueExplicitly(parameter.getValue()))) {
                continue; // skip private services
            }

            Iterator iterator = axisService.getOperations();
            resultBuf.append("<h3><a href=\"").append(prefix).append(axisService.getName()).append("?wsdl\">")
                    .append(axisService.getName()).append("</a></h3>");

            if (iterator.hasNext()) {
                resultBuf.append("Available operations <ul>");

                for (; iterator.hasNext();) {
                    AxisOperation axisOperation = (AxisOperation) iterator.next();
                    resultBuf.append("<li>").append(axisOperation.getName().getLocalPart()).append("</li>");
                }
                resultBuf.append("</ul>");
            } else {
                resultBuf.append("No operations specified for this service");
            }
        }
    }

    if ((erroneousServices != null) && !erroneousServices.isEmpty()) {
        servicesFound = true;
        resultBuf.append("<hr><h2><font color=\"blue\">Faulty Services</font></h2>");
        Enumeration faultyservices = erroneousServices.keys();

        while (faultyservices.hasMoreElements()) {
            String faultyserviceName = (String) faultyservices.nextElement();
            resultBuf.append("<h3><font color=\"blue\">").append(faultyserviceName).append("</font></h3>");
        }
    }

    if (!servicesFound) {
        resultBuf.append("<h2>There are no services deployed</h2>");
    }

    resultBuf.append("</body></html>");
    return resultBuf.toString();
}

From source file:org.wso2.carbon.mediation.transport.handlers.PassThroughNHttpGetProcessor.java

/**
 * Returns the HTML text for the list of services deployed.
 * This can be delegated to another Class as well
 * where it will handle more options of GET messages.
 *
 * @param prefix to be used for the Service names
 * @return the HTML to be displayed as a String
 *//*from  w w  w  .  jav a  2  s.c  om*/
protected String getServicesHTML(String prefix) {

    Map services = cfgCtx.getAxisConfiguration().getServices();
    Hashtable erroneousServices = cfgCtx.getAxisConfiguration().getFaultyServices();
    boolean servicesFound = false;

    StringBuffer resultBuf = new StringBuffer();
    resultBuf.append("<html><head><title>Axis2: Services</title></head>" + "<body>");

    if ((services != null) && !services.isEmpty()) {

        servicesFound = true;
        resultBuf.append("<h2>" + "Deployed services" + "</h2>");

        for (Object service : services.values()) {

            AxisService axisService = (AxisService) service;
            Parameter isHiddenService = axisService.getParameter(NhttpConstants.HIDDEN_SERVICE_PARAM_NAME);
            Parameter isAdminService = axisService.getParameter("adminService");
            boolean isClientSide = axisService.isClientSide();

            boolean isSkippedService = (isHiddenService != null
                    && JavaUtils.isTrueExplicitly(isHiddenService.getValue()))
                    || (isAdminService != null && JavaUtils.isTrueExplicitly(isAdminService.getValue()))
                    || isClientSide;
            if (axisService.getName().startsWith("__") || isSkippedService) {
                continue; // skip private services
            }

            Iterator iterator = axisService.getOperations();
            resultBuf.append("<h3><a href=\"").append(prefix).append(axisService.getName()).append("?wsdl\">")
                    .append(axisService.getName()).append("</a></h3>");

            if (iterator.hasNext()) {
                resultBuf.append("Available operations <ul>");

                for (; iterator.hasNext();) {
                    AxisOperation axisOperation = (AxisOperation) iterator.next();
                    resultBuf.append("<li>").append(axisOperation.getName().getLocalPart()).append("</li>");
                }
                resultBuf.append("</ul>");
            } else {
                resultBuf.append("No operations specified for this service");
            }
        }
    }

    if ((erroneousServices != null) && !erroneousServices.isEmpty()) {
        servicesFound = true;
        resultBuf.append("<hr><h2><font color=\"blue\">Faulty Services</font></h2>");
        Enumeration faultyservices = erroneousServices.keys();

        while (faultyservices.hasMoreElements()) {
            String faultyserviceName = (String) faultyservices.nextElement();
            resultBuf.append("<h3><font color=\"blue\">").append(faultyserviceName).append("</font></h3>");
        }
    }

    if (!servicesFound) {
        resultBuf.append("<h2>There are no services deployed</h2>");
    }

    resultBuf.append("</body></html>");
    return resultBuf.toString();
}

From source file:io.cloudslang.content.database.services.dbconnection.DBConnectionManager.java

/**
 * clean any empty datasource and pool in the dbmsPool table.
 *//* www .j  av a  2  s.c  o  m*/
public void cleanDataSources() {

    Hashtable<String, List<String>> removedDsKeyTable = null;

    //gather all the empty ds's key, can't remove item while iterate
    Enumeration<String> allPoolKeys = dbmsPoolTable.keys();
    while (allPoolKeys.hasMoreElements()) {
        String dbPoolKey = allPoolKeys.nextElement();
        Hashtable<String, DataSource> dsTable = dbmsPoolTable.get(dbPoolKey);
        Enumeration<String> allDsKeys = dsTable.keys();
        while (allDsKeys.hasMoreElements()) {
            String dsKey = allDsKeys.nextElement();
            DataSource ds = dsTable.get(dsKey);

            //c3p0 impl
            if (ds != null && ds instanceof PooledDataSource) {
                PooledDataSource pDs = (PooledDataSource) ds;
                int conCount;
                try {
                    conCount = pDs.getNumConnectionsAllUsers();
                } catch (SQLException e) {
                    //                  todo      logger.error
                    //                                ("Failed to get total number of connections for datasource. dbmsPoolKey = "
                    //                                        + dbPoolKey, e);
                    continue;
                }
                //no connections
                if (conCount == 0) {
                    List<String> removedList = null;
                    if (removedDsKeyTable == null) {
                        removedDsKeyTable = new Hashtable<>();
                    } else {
                        removedList = removedDsKeyTable.get(dbPoolKey);
                    }

                    if (removedList == null) {
                        removedList = new ArrayList<>();
                        removedList.add(dsKey);
                        removedDsKeyTable.put(dbPoolKey, removedList);
                    } else {
                        removedList.add(dsKey);
                    }
                }
            }
        }
    }

    //have empty ds
    if (removedDsKeyTable != null && !removedDsKeyTable.isEmpty()) {
        Enumeration<String> removedPoolKeys = removedDsKeyTable.keys();
        while (removedPoolKeys.hasMoreElements()) {
            String removedPoolKey = removedPoolKeys.nextElement();
            PooledDataSourceProvider provider = this.getProvider(removedPoolKey);
            List<String> removedDsList = removedDsKeyTable.get(removedPoolKey);
            Hashtable<String, DataSource> dsTable = dbmsPoolTable.get(removedPoolKey);
            for (String dsKey : removedDsList) {
                DataSource removedDs = dsTable.remove(dsKey);
                try {
                    provider.closePooledDataSource(removedDs);
                } catch (SQLException e) {
                    //can't show the dsKey since it has encrypted password there
                    //                  todo      logger.error("Failed to close datadsource in dmbs poolKey = "
                    //                                + removedPoolKey, e);
                    continue;
                }

                //tracing
                //                todo    if (logger.isDebugEnabled()) {
                //                        logger.debug("Removed one datasource in dbms poolKey = "
                //                                + removedPoolKey);
                //                    }
            }
            //don't have any ds for the pool key
            if (dsTable.isEmpty()) {
                dbmsPoolTable.remove(removedPoolKey);
                //tracing
                //              todo      if (logger.isDebugEnabled()) {
                //                        logger.debug("Removed dbms poolKey = " + removedPoolKey);
                //                    }
            }
        }
    }
}

From source file:net.sourceforge.floggy.persistence.Weaver.java

/**
 * DOCUMENT ME!//from  w w w.  j a  va  2  s  . co m
*
* @throws CannotCompileException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
* @throws NotFoundException DOCUMENT ME!
*/
protected void addPersistableMetadataManagerClass()
        throws CannotCompileException, IOException, NotFoundException {
    alreadyProcessedMetadatas.addAll(configuration.getPersistableMetadatas());

    Set metadatas = alreadyProcessedMetadatas;
    StringBuffer buffer = new StringBuffer();

    buffer.append("public static void init() throws Exception {\n");
    buffer.append("rmsBasedMetadatas = new java.util.Hashtable();\n");
    buffer.append("classBasedMetadatas = new java.util.Hashtable();\n");
    buffer.append("java.util.Hashtable persistableImplementations = null;\n");
    buffer.append("java.util.Vector indexMetadatas = null;\n");
    buffer.append("java.util.Vector fields = null;\n");

    for (Iterator iterator = metadatas.iterator(); iterator.hasNext();) {
        PersistableMetadata metadata = (PersistableMetadata) iterator.next();
        boolean isAbstract = metadata.isAbstract();
        String className = metadata.getClassName();
        String superClassName = metadata.getSuperClassName();
        String[] fieldNames = metadata.getFieldNames();
        int[] fieldTypes = metadata.getFieldTypes();
        Hashtable persistableImplementations = metadata.getPersistableImplementations();
        String recordStoreName = metadata.getRecordStoreName();
        int persistableStrategy = metadata.getPersistableStrategy();
        Vector indexMetadatas = metadata.getIndexMetadatas();
        String[] descendents = metadata.getDescendents();

        StringBuffer fieldNamesBuffer = new StringBuffer("new String[");
        StringBuffer fieldTypesBuffer = new StringBuffer("new int[");
        boolean addHeader = true;

        for (int i = 0; i < fieldNames.length; i++) {
            if (addHeader) {
                fieldNamesBuffer.append("]{");
                fieldTypesBuffer.append("]{");
                addHeader = false;
            }

            fieldNamesBuffer.append("\"");
            fieldNamesBuffer.append(fieldNames[i]);
            fieldNamesBuffer.append("\",");

            fieldTypesBuffer.append(fieldTypes[i]);
            fieldTypesBuffer.append(",");
        }

        if (addHeader) {
            fieldNamesBuffer.append("0]");
            fieldTypesBuffer.append("0]");
        } else {
            fieldNamesBuffer.deleteCharAt(fieldNamesBuffer.length() - 1);
            fieldNamesBuffer.append("}");
            fieldTypesBuffer.deleteCharAt(fieldTypesBuffer.length() - 1);
            fieldTypesBuffer.append("}");
        }

        if ((persistableImplementations != null) && !persistableImplementations.isEmpty()) {
            buffer.append("persistableImplementations = new java.util.Hashtable();\n");

            Enumeration enumeration = persistableImplementations.keys();

            while (enumeration.hasMoreElements()) {
                String fieldName = (String) enumeration.nextElement();
                String classNameOfField = (String) persistableImplementations.get(fieldName);
                buffer.append("persistableImplementations.put(\"");
                buffer.append(fieldName);
                buffer.append("\", \"");
                buffer.append(classNameOfField);
                buffer.append("\");\n");
            }
        } else {
            buffer.append("persistableImplementations = null;\n");
        }

        if ((indexMetadatas != null) && !indexMetadatas.isEmpty()) {
            buffer.append("indexMetadatas = new java.util.Vector();\n");

            Enumeration enumeration = indexMetadatas.elements();

            while (enumeration.hasMoreElements()) {
                IndexMetadata indexMetadata = (IndexMetadata) enumeration.nextElement();

                buffer.append("fields = new java.util.Vector();\n");

                Vector fields = indexMetadata.getFields();

                for (int j = 0; j < fields.size(); j++) {
                    buffer.append("fields.addElement(\"");
                    buffer.append(fields.elementAt(j));
                    buffer.append("\");\n");
                }

                buffer.append(
                        "indexMetadatas.addElement(new net.sourceforge.floggy.persistence.impl.IndexMetadata(\"");
                buffer.append(indexMetadata.getRecordStoreName());
                buffer.append("\", \"");
                buffer.append(indexMetadata.getName());
                buffer.append("\", fields));\n");
            }
        } else {
            buffer.append("indexMetadatas = null;\n");
        }

        StringBuffer descendentsBuffer = new StringBuffer("new String[");
        addHeader = true;

        if (descendents != null) {
            for (int i = 0; i < descendents.length; i++) {
                if (addHeader) {
                    descendentsBuffer.append("]{");
                    addHeader = false;
                }

                descendentsBuffer.append("\"");
                descendentsBuffer.append(descendents[i]);
                descendentsBuffer.append("\",");
            }
        }

        if (addHeader) {
            descendentsBuffer.append("0]");
        } else {
            descendentsBuffer.deleteCharAt(descendentsBuffer.length() - 1);
            descendentsBuffer.append("}");
        }

        buffer.append("classBasedMetadatas.put(\"" + className
                + "\", new net.sourceforge.floggy.persistence.impl.PersistableMetadata(" + isAbstract + ", \""
                + className + "\", "
                + ((superClassName != null) ? ("\"" + superClassName + "\", ") : ("null, "))
                + fieldNamesBuffer.toString() + ", " + fieldTypesBuffer.toString()
                + ", persistableImplementations, indexMetadatas, " + "\"" + recordStoreName + "\", "
                + persistableStrategy + ", " + descendentsBuffer.toString() + "));\n");
    }

    buffer.append("load();\n");
    buffer.append("}\n");

    CtClass ctClass = this.classpathPool
            .get("net.sourceforge.floggy.persistence.impl.PersistableMetadataManager");
    CtMethod[] methods = ctClass.getMethods();

    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName().equals("init")) {
            ctClass.removeMethod(methods[i]);
        }
    }

    ctClass.addMethod(CtNewMethod.make(buffer.toString(), ctClass));
    embeddedClassesOutputPool.addClass(ctClass);
}

From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * Copy a resource.//from   w w w.  ja v a 2 s.com
 *
 * @param req  Servlet request
 * @param resp Servlet response
 * @return boolean true if the copy is successful
 * @throws javax.servlet.ServletException Description of the Exception
 * @throws java.io.IOException            Description of the Exception
 */
private boolean copyResource(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    // Parsing destination header

    String destinationPath = req.getHeader("Destination");

    if (destinationPath == null) {
        resp.sendError(WebdavStatus.SC_BAD_REQUEST);
        return false;
    }

    // Remove url encoding from destination
    destinationPath = RequestUtil.URLDecode(destinationPath, "UTF8");

    int protocolIndex = destinationPath.indexOf("://");
    if (protocolIndex >= 0) {
        // if the Destination URL contains the protocol, we can safely
        // trim everything upto the first "/" character after "://"
        int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4);
        if (firstSeparator < 0) {
            destinationPath = "/";
        } else {
            destinationPath = destinationPath.substring(firstSeparator);
        }
    } else {
        String hostName = req.getServerName();
        if ((hostName != null) && (destinationPath.startsWith(hostName))) {
            destinationPath = destinationPath.substring(hostName.length());
        }

        int portIndex = destinationPath.indexOf(":");
        if (portIndex >= 0) {
            destinationPath = destinationPath.substring(portIndex);
        }

        if (destinationPath.startsWith(":")) {
            int firstSeparator = destinationPath.indexOf("/");
            if (firstSeparator < 0) {
                destinationPath = "/";
            } else {
                destinationPath = destinationPath.substring(firstSeparator);
            }
        }
    }

    // Normalise destination path (remove '.' and '..')
    destinationPath = normalize(destinationPath);

    String contextPath = req.getContextPath();
    if ((contextPath != null) && (destinationPath.startsWith(contextPath))) {
        destinationPath = destinationPath.substring(contextPath.length());
    }

    String pathInfo = req.getPathInfo();
    if (pathInfo != null) {
        String servletPath = req.getServletPath();
        if ((servletPath != null) && (destinationPath.startsWith(servletPath))) {
            destinationPath = destinationPath.substring(servletPath.length());
        }
    }

    if (debug > 0) {
        System.out.println("Dest path :" + destinationPath);
    }

    if ((destinationPath.toUpperCase().startsWith("/WEB-INF"))
            || (destinationPath.toUpperCase().startsWith("/META-INF"))) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    String path = getRelativePath(req);

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    if (destinationPath.equals(path)) {
        resp.sendError(WebdavStatus.SC_FORBIDDEN);
        return false;
    }

    // Parsing overwrite header

    boolean overwrite = true;
    String overwriteHeader = req.getHeader("Overwrite");

    if (overwriteHeader != null) {
        if (overwriteHeader.equalsIgnoreCase("T")) {
            overwrite = true;
        } else {
            overwrite = false;
        }
    }

    // Overwriting the destination

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

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

    boolean exists = true;
    try {
        resources.lookup(destinationPath);
    } catch (NamingException e) {
        exists = false;
    }

    if (overwrite) {

        // Delete destination resource, if it exists
        if (exists) {
            if (!deleteResource(destinationPath, req, resp, true)) {
                return false;
            }
        } else {
            resp.setStatus(WebdavStatus.SC_CREATED);
        }

    } else {

        // If the destination exists, then it's a conflict
        if (exists) {
            resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
            return false;
        }
    }

    // Copying source to destination

    Hashtable errorList = new Hashtable();

    boolean result = copyResource(resources, errorList, path, destinationPath);

    if ((!result) || (!errorList.isEmpty())) {

        sendReport(req, resp, errorList);
        return false;
    }

    // Removing any lock-null resource which would be present at
    // the destination path
    lockNullResources.remove(destinationPath);

    return true;
}

From source file:org.fcrepo.server.access.DefaultAccess.java

/**
 * <p>//from w w  w .j  a v  a 2  s.c  o m
 * Validates user-supplied method parameters against values in the
 * corresponding Service Definition object. The method will validate for:
 * </p>
 * <ol>
 * <li>Valid name - each name must match a valid method parameter name</li>
 * <li>DefaultValue - any specified parameters with valid default values
 * will have the default value substituted if the user-supplied value is
 * null</li>
 * <li>Required name - each required method parameter name must be present
 * </ol>
 *
 * @param context
 *        The context of this request.
 * @param PID
 *        The persistent identifier of the digital object.
 * @param sDefPID
 *        The persistent identifier of the Service Definition object.
 * @param methodName
 *        The name of the method.
 * @param h_userParms
 *        A hashtable of user-supplied method parameter name/value pairs.
 * @param versDateTime
 *        The version datetime stamp of the digital object.
 * @throws ServerException
 *         If any type of error occurred fulfilling the request.
 */
private void validateUserParms(Context context, String PID, String sDefPID, ServiceDeploymentReader sdepreader,
        String methodName, Hashtable<String, String> h_userParms, Date versDateTime) throws ServerException {
    PID = Server.getPID(PID).toString();
    sDefPID = Server.getPID(sDefPID).toString();
    MethodParmDef[] methodParms = null;
    MethodParmDef methodParm = null;
    StringBuffer sb = new StringBuffer();
    Hashtable<String, MethodParmDef> h_validParms = new Hashtable<String, MethodParmDef>();
    boolean isValid = true;

    if (sdepreader != null) // this code will be used for the CMDA example
    {
        MethodDef[] methods = sdepreader.getServiceMethods(versDateTime);
        // Filter out parms that are internal to the mechanism and not part
        // of the abstract method definition.  We just want user parms.
        for (MethodDef element : methods) {
            if (element.methodName.equalsIgnoreCase(methodName)) {
                ArrayList<MethodParmDef> filteredParms = new ArrayList<MethodParmDef>();
                MethodParmDef[] parms = element.methodParms;
                for (MethodParmDef element2 : parms) {
                    if (element2.parmType.equalsIgnoreCase(MethodParmDef.USER_INPUT)) {
                        filteredParms.add(element2);
                    }
                }
                methodParms = filteredParms.toArray(METHOD_PARM_DEF_TYPE);
            }
        }
    } else {
        String message = "[DefaultAccess] Old-style disseminators are no longer supported ";
        throw new DisseminatorNotFoundException(message);
        //        reader = m_manager.getReader(Server.GLOBAL_CHOICE, context, PID);
        //        methodParms = reader.getObjectMethodParms(sDefPID, methodName, versDateTime);
    }

    // Put valid method parameters and their attributes into hashtable
    if (methodParms != null) {
        for (int i = 0; i < methodParms.length; i++) {
            methodParm = methodParms[i];
            h_validParms.put(methodParm.parmName, methodParm);
            if (logger.isDebugEnabled()) {
                logger.debug("methodParms[" + i + "]: " + methodParms[i].parmName + "\nlabel: "
                        + methodParms[i].parmLabel + "\ndefault: " + methodParms[i].parmDefaultValue
                        + "\nrequired: " + methodParms[i].parmRequired + "\ntype: " + methodParms[i].parmType);
                for (String element : methodParms[i].parmDomainValues) {
                    logger.debug("domainValue: {}", element);
                }
            }
        }
    }

    if (!h_validParms.isEmpty()) {
        // Iterate over valid parmameters to check for any missing required parms.
        Enumeration<String> e = h_validParms.keys();
        while (e.hasMoreElements()) {
            String validName = e.nextElement();
            MethodParmDef mp = h_validParms.get(validName);
            if (mp.parmRequired && h_userParms.get(validName) == null) {
                // This is a fatal error. A required method parameter does not
                // appear in the list of user supplied parameters.
                sb.append("The required parameter \"" + validName + "\" was not found in the "
                        + "user-supplied parameter list.");
                throw new InvalidUserParmException("[Invalid User Parameters] " + sb.toString());
            }
        }

        // Iterate over each user supplied parameter name
        Enumeration<String> parmNames = h_userParms.keys();
        while (parmNames.hasMoreElements()) {
            String parmName = parmNames.nextElement();
            methodParm = h_validParms.get(parmName);
            if (methodParm != null && methodParm.parmName != null) {
                // Method has one or more parameters defined
                // Check for default value if user-supplied value is null or empty
                String value = h_userParms.get(methodParm.parmName);
                if (value == null || value.equalsIgnoreCase("")) {
                    // Value of user-supplied parameter is  null or empty
                    if (methodParm.parmDefaultValue != null) {
                        // Default value is specified for this parameter.
                        // Substitute default value.
                        h_userParms.put(methodParm.parmName, methodParm.parmDefaultValue);
                    } else {
                        // This is a non-fatal error. There is no default specified
                        // for this parameter and the user has supplied no value for
                        // the parameter. The value of the empty string will be used
                        // as the value of the parameter.
                        logger.warn("The method parameter \"" + methodParm.parmName
                                + "\" has no default value and no " + "value was specified by the user.  "
                                + "The value of the empty string has " + "been assigned to this parameter.");
                    }
                } else {
                    // Value of user-supplied parameter contains a value.
                    // Validate the supplied value against the parmDomainValues list.
                    String[] parmDomainValues = methodParm.parmDomainValues;
                    if (parmDomainValues.length > 0) {
                        if (!parmDomainValues[0].equalsIgnoreCase("null")) {
                            boolean isValidValue = false;
                            String userValue = h_userParms.get(methodParm.parmName);
                            for (String element : parmDomainValues) {
                                if (userValue.equalsIgnoreCase(element) || element.equalsIgnoreCase("null")) {
                                    isValidValue = true;
                                }
                            }
                            if (!isValidValue) {
                                for (int i = 0; i < parmDomainValues.length; i++) {
                                    sb.append(parmDomainValues[i]);
                                    if (i != parmDomainValues.length - 1) {
                                        sb.append(", ");
                                    }
                                }
                                sb.append("The method parameter \"" + methodParm.parmName
                                        + "\" with a value of \"" + h_userParms.get(methodParm.parmName)
                                        + "\" is not allowed for the method \"" + methodName
                                        + "\". Allowed values for this " + "method include \"" + sb.toString()
                                        + "\".");
                                isValid = false;
                            }
                        }
                    }
                }
            } else {
                // This is a fatal error. A user-supplied parameter name does
                // not match any valid parameter names for this method.
                sb.append("The method parameter \"" + parmName + "\" is not valid for the method \""
                        + methodName + "\".");
                isValid = false;
            }
        }
    } else {
        // There are no method parameters define for this method.
        if (!h_userParms.isEmpty()) {
            // This is an error. There are no method parameters defined for
            // this method and user parameters are specified in the
            // dissemination request.
            Enumeration<String> e = h_userParms.keys();
            while (e.hasMoreElements()) {
                sb.append("The method parameter \"" + e.nextElement() + "\" is not valid for the method \""
                        + methodName + "\"." + "The method \"" + methodName
                        + "\" defines no method parameters.");
            }
            throw new InvalidUserParmException("[Invalid User Parameters] " + sb.toString());
        }
    }
    if (!isValid) {
        throw new InvalidUserParmException("[Invalid User Parameter] " + sb.toString());
    }
    return;
}