Example usage for java.util Hashtable get

List of usage examples for java.util Hashtable get

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:com.hp.it.spf.wsrp.axis.transport.http.HTTPSender.java

/**
 * Reads the SOAP response back from the server
 *
 * @param msgContext message context//w ww . ja v  a  2  s.c  o  m
 *
 * @throws IOException
 */
private InputStream readFromSocket(SocketHolder socketHolder, MessageContext msgContext, InputStream inp,
        Hashtable headers) throws IOException {
    Message outMsg = null;
    byte b;

    Integer rc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
    int returnCode = 0;
    if (rc != null) {
        returnCode = rc.intValue();
    } else {
        // No return code?? Should have one by now.
    }

    /* All HTTP headers have been read. */
    String contentType = (String) headers.get(HEADER_CONTENT_TYPE_LC);

    contentType = (null == contentType) ? null : contentType.trim();

    String location = (String) headers.get(HEADER_LOCATION_LC);

    location = (null == location) ? null : location.trim();

    if ((returnCode > 199) && (returnCode < 300)) {
        if (returnCode == 202) {
            return inp;
        }
        // SOAP return is OK - so fall through
    } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        // For now, if we're SOAP 1.2, fall through, since the range of
        // valid result codes is much greater
    } else if ((contentType != null) && !contentType.startsWith("text/html")
            && ((returnCode > 499) && (returnCode < 600))) {
        // SOAP Fault should be in here - so fall through
    } else if ((location != null) && ((returnCode == 302) || (returnCode == 307))) {
        // Temporary Redirect (HTTP: 302/307)
        // close old connection
        inp.close();
        socketHolder.getSocket().close();
        // remove former result and set new target url
        msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
        msgContext.setProperty(MessageContext.TRANS_URL, location);
        // next try
        invoke(msgContext);
        return inp;
    } else if (returnCode == 100) {
        msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
        msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
        readHeadersFromSocket(socketHolder, msgContext, inp, headers);
        return readFromSocket(socketHolder, msgContext, inp, headers);
    } else {
        // Unknown return code - so wrap up the content into a
        // SOAP Fault.
        ByteArrayOutputStream buf = new ByteArrayOutputStream(4097);

        while (-1 != (b = (byte) inp.read())) {
            buf.write(b);
        }
        String statusMessage = msgContext.getStrProp(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
        AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

        fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, buf.toString()));
        fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
        throw fault;
    }

    String contentLocation = (String) headers.get(HEADER_CONTENT_LOCATION_LC);

    contentLocation = (null == contentLocation) ? null : contentLocation.trim();

    String contentLength = (String) headers.get(HEADER_CONTENT_LENGTH_LC);

    contentLength = (null == contentLength) ? null : contentLength.trim();

    String transferEncoding = (String) headers.get(HEADER_TRANSFER_ENCODING_LC);

    if (null != transferEncoding) {
        transferEncoding = transferEncoding.trim().toLowerCase();
        if (transferEncoding.equals(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
            inp = new ChunkedInputStream(inp);
        }
    }

    outMsg = new Message(new SocketInputStream(inp, socketHolder.getSocket()), false, contentType,
            contentLocation);
    // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
    MimeHeaders mimeHeaders = outMsg.getMimeHeaders();
    for (Enumeration e = headers.keys(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        mimeHeaders.addHeader(key, ((String) headers.get(key)).trim());
    }
    outMsg.setMessageType(Message.RESPONSE);
    msgContext.setResponseMessage(outMsg);
    if (log.isDebugEnabled()) {
        if (null == contentLength) {
            log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
        }
        log.debug("\n" + Messages.getMessage("xmlRecd00"));
        log.debug("-----------------------------------------------");
        log.debug(outMsg.getSOAPEnvelope().toString());
    }

    return inp;
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.control.ControlServ.java

/** Attemp to re-authenticate the given client. This is called whenever a client sends an
 *  authentication request into a session that is already running. Re-authentication will fail
 *  if the client is not a part of the session. In this case an AUTH_FAILED authPacket is sent
 *  back to the dispatcher. Otherwise return a RE_AUTH_SUCCESS packet to the dispatcher, which
 *  will contain all the state information needed by the re-authenticating client */
private AuthUpdate reauthClient(int sessionId, SessionState session, String name, int dbId,
        Hashtable disconnected) {
    try {/* ww w. j a  va  2  s  . c o  m*/
        PeriodDef pinfo = session.getSession().getPeriod(session.getPeriodNum());
        SubjectDef sinfo = pinfo.getSubjectInfo();
        int id = sinfo.getId(dbId);
        if (id == -1) {
            return createAuthFailedPacket(
                    "Re-authentication failed: You are not enrolled in session " + sessionId, false);
        }

        Boolean discon = (Boolean) disconnected.get(new Integer(dbId));
        if (discon == null) {
            return createAuthFailedPacket(
                    "Re-authentication failed: You have no connectivity status in session " + sessionId, false);
        }

        disconnected.put(new Integer(dbId), Boolean.FALSE);

        AuthUpdate authPacket = new AuthUpdate(AuthUpdate.RE_AUTH_SUCCESS);
        authPacket.setUpdateTime(session.getUpdateTime());
        authPacket.setId(id);
        authPacket.setName(name);
        authPacket.setPeriodInfo(pinfo);

        if (!discon.booleanValue()) {
            authPacket.setReplacement(true);
        } else {
            authPacket.setReplacement(false);
        }

        log.info("Client " + name + " (ID: " + (id) + ") is  re-authenticating into session " + sessionId);

        return authPacket;

    } catch (Exception e) {
        log.error("Failed to re-authenticate client to session " + sessionId, e);
    }
    return createAuthFailedPacket("Re-authentication failed for unknown reason", false);
}

From source file:edu.stanford.cfuller.imageanalysistools.filter.ConvexHullByLabelFilter.java

/**
 * Applies the convex hull filter to the supplied mask.
 * @param im    The Image to process-- a mask whose regions will be replaced by their filled convex hulls.
 */// w ww . ja va2 s .  c  om
@Override
public void apply(WritableImage im) {

    RelabelFilter RLF = new RelabelFilter();

    RLF.apply(im);

    Histogram h = new Histogram(im);

    java.util.Hashtable<Integer, java.util.Vector<Integer>> xLists = new java.util.Hashtable<Integer, java.util.Vector<Integer>>();
    java.util.Hashtable<Integer, java.util.Vector<Integer>> yLists = new java.util.Hashtable<Integer, java.util.Vector<Integer>>();

    java.util.Vector<Integer> minValues = new java.util.Vector<Integer>(h.getMaxValue() + 1);
    java.util.Vector<Integer> minIndices = new java.util.Vector<Integer>(h.getMaxValue() + 1);

    for (int i = 0; i < h.getMaxValue() + 1; i++) {
        minValues.add(im.getDimensionSizes().get(ImageCoordinate.X));
        minIndices.add(0);
    }

    for (ImageCoordinate i : im) {

        int value = (int) im.getValue(i);

        if (value == 0)
            continue;

        if (!xLists.containsKey(value)) {
            xLists.put(value, new java.util.Vector<Integer>());
            yLists.put(value, new java.util.Vector<Integer>());
        }

        xLists.get(value).add(i.get(ImageCoordinate.X));
        yLists.get(value).add(i.get(ImageCoordinate.Y));

        if (i.get(ImageCoordinate.X) < minValues.get(value)) {
            minValues.set(value, i.get(ImageCoordinate.X));
            minIndices.set(value, xLists.get(value).size() - 1);
        }

    }

    java.util.Vector<Integer> hullPointsX = new java.util.Vector<Integer>();
    java.util.Vector<Integer> hullPointsY = new java.util.Vector<Integer>();

    ImageCoordinate ic = ImageCoordinate.createCoordXYZCT(0, 0, 0, 0, 0);

    for (int k = 1; k < h.getMaxValue() + 1; k++) {
        hullPointsX.clear();
        hullPointsY.clear();

        java.util.Vector<Integer> xList = xLists.get(k);
        java.util.Vector<Integer> yList = yLists.get(k);

        int minIndex = (int) minIndices.get(k);

        //start at the leftmost point

        int currentIndex = minIndex;
        int currentX = xList.get(currentIndex);
        int currentY = yList.get(currentIndex);

        hullPointsX.add(currentX);
        hullPointsY.add(currentY);

        org.apache.commons.math3.linear.RealVector angles = new org.apache.commons.math3.linear.ArrayRealVector(
                xList.size());

        Vector3D currentVector = new Vector3D(0, -1, 0);

        java.util.HashSet<Integer> visited = new java.util.HashSet<Integer>();

        do {

            visited.add(currentIndex);

            int maxIndex = 0;
            double maxAngle = -2 * Math.PI;
            double dist = Double.MAX_VALUE;
            for (int i = 0; i < xList.size(); i++) {
                if (i == currentIndex)
                    continue;
                Vector3D next = new Vector3D(xList.get(i) - xList.get(currentIndex),
                        yList.get(i) - yList.get(currentIndex), 0);

                double angle = Vector3D.angle(currentVector, next);
                angles.setEntry(i, angle);
                if (angle > maxAngle) {
                    maxAngle = angle;
                    maxIndex = i;
                    dist = next.getNorm();
                } else if (angle == maxAngle) {
                    double tempDist = next.getNorm();
                    if (tempDist < dist) {
                        dist = tempDist;
                        maxAngle = angle;
                        maxIndex = i;
                    }
                }
            }

            currentX = xList.get(maxIndex);
            currentY = yList.get(maxIndex);

            currentVector = new Vector3D(xList.get(currentIndex) - currentX, yList.get(currentIndex) - currentY,
                    0);

            hullPointsX.add(currentX);
            hullPointsY.add(currentY);

            currentIndex = maxIndex;

        } while (!visited.contains(currentIndex));

        //hull vertices have now been determined .. need to fill in the lines
        //between them so I can apply a fill filter

        //approach: x1, y1 to x0, y0:
        //start at min x, min y, go to max x, max y
        // if x_i, y_i = x0, y0  + slope to within 0.5 * sqrt(2), then add to hull

        double eps = Math.sqrt(2);

        for (int i = 0; i < hullPointsX.size() - 1; i++) {

            int x0 = hullPointsX.get(i);
            int y0 = hullPointsY.get(i);

            int x1 = hullPointsX.get(i + 1);
            int y1 = hullPointsY.get(i + 1);

            int xmin = (x0 < x1) ? x0 : x1;
            int ymin = (y0 < y1) ? y0 : y1;
            int xmax = (x0 > x1) ? x0 : x1;
            int ymax = (y0 > y1) ? y0 : y1;

            x1 -= x0;
            y1 -= y0;

            double denom = (x1 * x1 + y1 * y1);

            for (int x = xmin; x <= xmax; x++) {
                for (int y = ymin; y <= ymax; y++) {

                    int rel_x = x - x0;
                    int rel_y = y - y0;

                    double projLength = (x1 * rel_x + y1 * rel_y) / denom;

                    double projPoint_x = x1 * projLength;
                    double projPoint_y = y1 * projLength;

                    if (Math.hypot(rel_x - projPoint_x, rel_y - projPoint_y) < eps) {
                        ic.set(ImageCoordinate.X, x);
                        ic.set(ImageCoordinate.Y, y);
                        im.setValue(ic, k);
                    }

                }
            }

        }

    }

    ic.recycle();

    FillFilter ff = new FillFilter();

    ff.apply(im);

}

From source file:gamlss.algorithm.GlimFitCG.java

public ArrayRealVector glimFitFunctionCG(GAMLSSFamilyDistribution distr, ArrayRealVector response,
        Hashtable<Integer, BlockRealMatrix> X, ArrayRealVector fv, ArrayRealVector weights,
        int whichDistParameter, double step, double offSet, double globalDeviance,
        Hashtable<String, ArrayRealVector> cgData, MakeLinkFunction makelink) {

    int itn = 0;//from ww w.  ja  v a2s . c o m
    double[] temp = new double[0];

    //G.dev.in <- G.dev+1
    //     double gDevIn = globalDeviance +1;

    //i.G.dev <- G.dev
    double gDev = globalDeviance;

    double gDevOld = globalDeviance + 1;

    //first.iter <- FALSE  
    boolean firstIter = false;

    //while ( abs(G.dev.in -i.G.dev) > i.c.crit && i.iter < i.n.cyc )
    while (FastMath.abs(gDevOld - gDev) > Controls.GLIM_CONV_CRIT && itn < Controls.GLIM_NUM_CYCLES) {

        //i.iter <- i.iter+1
        itn = itn + 1;

        //for (int i = 1; i < distr.getNumberOfDistribtionParameters()+1; i++ ){
        switch (whichDistParameter) {
        case DistributionSettings.MU:
            // whichDistParameter = DistributionSettings.MU;

            //adj.mu <- -(w.mu.sigma*(eta.sigma-eta.old.sigma)+w.mu.nu*(eta.nu-eta.old.nu)+w.mu.tau*(eta.tau-eta.old.tau))/w.mu 
            adj = setAdj(cgData.get("wMuSigma"), cgData.get("eta" + DistributionSettings.SIGMA),
                    cgData.get("etaOld" + DistributionSettings.SIGMA), cgData.get("wMuNu"),
                    cgData.get("eta" + DistributionSettings.NU), cgData.get("etaOld" + DistributionSettings.NU),
                    cgData.get("wMuTau"), cgData.get("eta" + DistributionSettings.TAU),
                    cgData.get("etaOld" + DistributionSettings.TAU), cgData.get("w" + DistributionSettings.MU));

            cgData.put("adj" + DistributionSettings.MU, adj);

            break;
        case DistributionSettings.SIGMA:
            // whichDistParameter = DistributionSettings.SIGMA;

            // adj.sigma <- -(w.mu.sigma*(eta.mu-eta.old.mu)+ w.sigma.nu*(eta.nu-eta.old.nu)+w.sigma.tau*(eta.tau-eta.old.tau))/w.sigma 
            adj = setAdj(cgData.get("wMuSigma"), cgData.get("eta" + DistributionSettings.MU),
                    cgData.get("etaOld" + DistributionSettings.MU), cgData.get("wSigmaNu"),
                    cgData.get("eta" + DistributionSettings.NU), cgData.get("etaOld" + DistributionSettings.NU),
                    cgData.get("wSigmaTau"), cgData.get("eta" + DistributionSettings.TAU),
                    cgData.get("etaOld" + DistributionSettings.TAU),
                    cgData.get("w" + DistributionSettings.SIGMA));

            cgData.put("adj" + DistributionSettings.SIGMA, adj);

            break;
        case DistributionSettings.NU:
            // whichDistParameter = DistributionSettings.NU;
            break;
        case DistributionSettings.TAU:
            // whichDistParameter = DistributionSettings.TAU;
            break;
        }

        //wv.mu  <- z.mu+adj.mu
        ArrayRealVector wv = setWV(cgData.get("z" + whichDistParameter),
                cgData.get("adj" + whichDistParameter));

        //mu.fit <<- lm.wfit(x=mu.X,y=wv.mu,w=w.mu*w,method="qr") 
        wls.newSampleData(wv, X.get(whichDistParameter).copy(),
                cgData.get("w" + whichDistParameter).ebeMultiply(weights));
        ArrayRealVector fit = (ArrayRealVector) wls.calculateFittedValues(false);

        //System.out.println(wls.calculateBeta());
        //           bettas.put(whichDistParameter, (ArrayRealVector) wls.calculateBeta());

        //mu.fit$eta <<- eta.mu <- mu.fit$fitted.values+mu.offset
        temp = new double[fit.getDimension()];
        for (int j = 0; j < temp.length; j++) {
            temp[j] = fit.getEntry(j) + offSet;
        }
        //eta = new ArrayRealVector(temp,false);
        cgData.put("eta" + whichDistParameter, new ArrayRealVector(temp, false));
        temp = null;

        //mu.fit$fv <<-    mu <<- mu.object$linkinv(eta.mu)

        ArrayRealVector dParam = makelink.linkInv(distr.getDistributionParameterLink(whichDistParameter),
                cgData.get("eta" + whichDistParameter));

        distr.setDistributionParameter(whichDistParameter, dParam);

        //mu.fit$wv <<- wv.mu
        //mu.fit$wt <<- w.mu  

        //G.dev.in <- i.G.dev
        gDevOld = gDev;

        //G.dev.incr <- eval(G.dev.expr) 
        //i.G.dev <- sum(w*G.dev.incr)
        gDev = weights.dotProduct(distr.globalDevianceIncreament(response));

        if (gDev > gDevOld && itn >= 2 && Controls.AUTO_STEP) {
            for (int i = 0; i < 5; i++) {

                //eta.mu <- (eta.mu+eta.old.mu)/2
                ArrayRealVector etaM = etaMean(cgData.get("eta" + whichDistParameter),
                        cgData.get("etaOld" + whichDistParameter));
                cgData.put("eta" + whichDistParameter, etaM);
                //mu <<- mu.object$linkinv(eta.mu) 

                distr.setDistributionParameter(whichDistParameter,
                        makelink.linkInv(distr.getDistributionParameterLink(whichDistParameter), etaM));

                //if(length(who.mu) > 0) s.mu <- (s.mu+s.mu.old)/2 
                //   }
            }
        }

        //if(i.trace)
        if (Controls.GLIM_TRACE) {
            //cat("CG inner iteration ", iter, ": Global Deviance = ",format(round(i.G.dev, 4)), " \n", sep = "")           
            System.err.println("CG inner iteration " + itn + " : Global Deviance = " + gDev);
        }
        //if (i.G.dev > (G.dev.in+gd.tol) && iter >1 )
        if (gDev > (gDevOld + Controls.GLOB_DEVIANCE_TOL) && itn > 1) {

            //stop(paste("The global deviance is increasing in the inner CG loop", "\n","Try different steps for the parameters or the model maybe inappropriate"))
            System.out.println(
                    "The global deviance is increasing in the inner CG loop, try different steps for the parameters or the model maybe inappropriate");
            break;
        }
    }

    //G.dev.old <- G.dev
    //        gDevOld = gDev;

    //G.dev.incr <- eval(G.dev.expr)   
    //G.dev <- sum(w*G.dev.incr)
    //     gDev = weights.dotProduct(distr.globalDevianceIncreament(response));

    //if (G.dev > G.dev.old && iter >= 2 && autostep == TRUE)

    return (ArrayRealVector) wls.calculateBeta();
}

From source file:edu.ku.brc.specify.datamodel.SpUIViewDef.java

/**
 * @param enableRulesArg//from  w  w  w .  java 2 s.  c om
 * @return
 */
protected String createEnableRulesXML(final Hashtable<String, String> enableRulesArg) {
    if (enableRulesArg.keySet().size() > 0) {
        StringBuilder sb = new StringBuilder("<enableRules>");
        for (String key : enableRulesArg.keySet()) {
            sb.append("<rule id=\"");
            sb.append(key);
            sb.append("\"><![CDATA[");
            sb.append(enableRulesArg.get(key));
            sb.append("]]></rule>");
        }
        sb.append("</enableRules>");
        return sb.toString();
    }
    return null;
}

From source file:BeanVector.java

/**
 * performs a selection sort on all the beans in the Vector by
 * PropertyName/*from w w w.j av  a2  s  . c  o  m*/
 *
 * <p>You can use a mixture of bean classes as long as all the beans
 * support the same property (getName() for instance), and all have the
 * same return type, or can be compareTo()ed each other.</p>
 *
 * <p>For optimal performance, it is recommended that if you have a
 * mixed class set the you have them grouped with like classes together
 * as this will minimize reflection inspections.</p>
 * @param propertyName String value containing the property to sort on.
 * @param ascending == sorts up if true, down if not.
 * @throws java.lang.IllegalAccessException reflection exception
 * @throws java.beans.IntrospectionException reflection exception
 * @throws java.lang.reflect.InvocationTargetException reflection exception
 */
public synchronized void sortOnProperty(String propertyName, boolean ascending)
        throws java.lang.IllegalAccessException, java.beans.IntrospectionException,
        java.lang.reflect.InvocationTargetException {
    T[] old = null;

    if ((this.indexPropertyName != null) && (this.changes != null)) {
        old = this.toTypedArray();
    }

    T temp = null;
    String currentClass = "";
    PropertyDescriptor pd = null;
    Hashtable cache = new Hashtable();

    for (int i = 0; i < (this.size() - 1); i++) {
        for (int j = i + 1; j < this.size(); j++) {
            T o1 = this.elementAt(i);

            if (!currentClass.equals(o1.getClass().getName())) {
                pd = (PropertyDescriptor) cache.get(o1.getClass().getName());

                if (pd == null) {
                    PropertyDescriptor[] pds = Introspector.getBeanInfo(o1.getClass()).getPropertyDescriptors();
                    boolean foundProperty = false;

                    for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                        if (pds[pdi].getName().equals(propertyName)) {
                            pd = pds[pdi];
                            cache.put(o1.getClass().getName(), pd);
                            foundProperty = true;
                        }
                    }
                }
            }

            //System.out.println( "o1: "+o1+" "+pd);
            //System.out.println( propertyName +" "+ (pd == null ));
            Comparable oc1 = (Comparable) pd.getReadMethod().invoke(o1);

            T o2 = this.elementAt(j);

            if (!currentClass.equals(o2.getClass().getName())) {
                pd = (PropertyDescriptor) cache.get(o2.getClass().getName());

                if (pd == null) {
                    PropertyDescriptor[] pds = Introspector.getBeanInfo(o2.getClass()).getPropertyDescriptors();
                    boolean foundProperty = false;

                    for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                        if (pds[pdi].getName().equals(propertyName)) {
                            pd = pds[pdi];
                            foundProperty = true;
                        }
                    }
                }
            }

            Comparable oc2 = (Comparable) pd.getReadMethod().invoke(o2);

            if (ascending) {
                if ((oc1 != oc2)
                        && ((oc2 == null) || ((oc1 != null) && (oc2 != null) && (oc2.compareTo(oc1) < 0)))) { //swap
                    this.setElementAt(o2, i);
                    this.setElementAt(o1, j);
                }
            } else {
                if ((oc1 != oc2)
                        && ((oc1 == null) || ((oc1 != null) && (oc2 != null) && (oc1.compareTo(oc2) < 0)))) { //swap
                    this.setElementAt(o2, i);
                    this.setElementAt(o1, j);
                }
            }
        }

        if (old != null) {
            changes.firePropertyChange(this.indexPropertyName, old, this.toTypedArray());
        }
    }
}

From source file:BeanVector.java

/**
 * Filters a property using the Comparable.compareTo() on the porperty to
 * test for a range/*from   w  ww . j  a  va  2  s  . co m*/
 * @param propertyName property to filter on
 * @param inclusive include the values of the range limiters
 * @param fromValue low range value
 * @param toValue high range value
 * @throws java.lang.IllegalAccessException reflection exception
 * @throws java.beans.IntrospectionException reflection exception
 * @throws java.lang.reflect.InvocationTargetException reflection exception
 * @return new BeanVector filtered on the range
 */
public BeanVector<T> getFiltered(String propertyName, boolean inclusive, Comparable fromValue,
        Comparable toValue) throws java.lang.IllegalAccessException, java.beans.IntrospectionException,
        java.lang.reflect.InvocationTargetException {
    Hashtable cache = new Hashtable();
    String currentClass = "";
    PropertyDescriptor pd = null;
    BeanVector<T> results = new BeanVector<T>();

    for (int i = 0; i < this.size(); i++) {
        T o = this.elementAt(i);

        if (!currentClass.equals(o.getClass().getName())) {
            pd = (PropertyDescriptor) cache.get(o.getClass().getName());

            if (pd == null) {
                PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors();
                boolean foundProperty = false;

                for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                    if (pds[pdi].getName().equals(propertyName)) {
                        pd = pds[pdi];
                        cache.put(o.getClass().getName(), pd);
                        foundProperty = true;
                    }
                }
            }
        }

        Comparable value = (Comparable) pd.getReadMethod().invoke(o);

        if ((value.compareTo(fromValue) > 0) && (value.compareTo(toValue) < 0)) {
            results.add(o);
        } else if (inclusive && ((value.compareTo(fromValue) == 0) || (value.compareTo(toValue) == 0))) {
            results.add(o);
        }
    }

    return results;
}

From source file:BeanVector.java

/**
 * This method does a string match on values of a property.
 * @param propertyName String value containing the name of the property to match.
 * @param match Value to search for. This is a case-insensitive value that takes % as a multiple character wildcard value.
 * @throws java.lang.IllegalAccessException reflection exception
 * @throws java.beans.IntrospectionException reflection exception
 * @throws java.lang.reflect.InvocationTargetException reflection exception
 * @return a new BeanVector filtered on the specified property
 *//*from  w  w w  .j a  v a  2 s.  c o  m*/
public BeanVector<T> getFilteredStringMatch(String propertyName, String match)
        throws java.lang.IllegalAccessException, java.beans.IntrospectionException,
        java.lang.reflect.InvocationTargetException {
    Hashtable cache = new Hashtable();
    String currentClass = "";
    PropertyDescriptor pd = null;
    BeanVector<T> results = new BeanVector<T>();

    for (int i = 0; i < this.size(); i++) {
        T o = this.elementAt(i);

        if (!currentClass.equals(o.getClass().getName())) {
            pd = (PropertyDescriptor) cache.get(o.getClass().getName());

            if (pd == null) {
                PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors();
                boolean foundProperty = false;

                for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) {
                    if (pds[pdi].getName().equals(propertyName)) {
                        pd = pds[pdi];
                        cache.put(o.getClass().getName(), pd);
                        foundProperty = true;
                    }
                }
            }
        }

        String value = pd.getReadMethod().invoke(o).toString().toLowerCase();
        StringTokenizer st = new StringTokenizer(match.toLowerCase(), "%");
        boolean isMatch = true;
        int matchIndex = 0;

        while (st.hasMoreTokens() && isMatch) {
            String tk = st.nextToken();

            if (value.indexOf(tk, matchIndex) == -1) {
                isMatch = false;
            } else {
                matchIndex = value.indexOf(tk, matchIndex) + tk.length();
            }
        }

        if (isMatch) {
            results.add(o);
        }
    }

    return results;
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void createModuleDef(ArrayList list, String classname) {
    String result = "";
    try {/*www  .j  ava 2  s  .c o  m*/

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

        Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile()));
        //Document doc = docBuilder.newDocument();
        NodeList modules = doc.getElementsByTagName("modules");
        Node modulesNode = modules.item(0);
        Element module_ex = doc.getElementById(classname);
        if (module_ex != null) {
            modulesNode.removeChild(module_ex);
        }
        Element module = doc.createElement("module");
        Element property_list = doc.createElement("property-list");
        module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname);
        module.setAttribute("type", "pojo");
        module.setAttribute("id", classname);
        for (int cnt = 0; cnt < list.size(); cnt++) {
            Element propertyNode = doc.createElement("property");
            Hashtable mapObj = (Hashtable) list.get(cnt);

            propertyNode.setAttribute("name", mapObj.get("name").toString());
            propertyNode.setAttribute("type", mapObj.get("type").toString().toLowerCase());
            property_list.appendChild(propertyNode);

        }

        module.appendChild(property_list);
        modulesNode.appendChild(module);
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/module.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);
        //       result  = sw.toString();

    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    } finally {
        // System.out.println(result);
        // return result;
    }
}

From source file:eionet.gdem.dcm.business.SchemaManager.java

/**
 * Get stylesheet information for given XML Schema.
 * @param schema XML Schema URL or database ID
 * @return List of styleseeht objects./*from   w w  w . java2s  . com*/
 * @throws DCMException in case of database error.
 */

public ArrayList getSchemaStylesheets(String schema) throws DCMException {

    ArrayList<Stylesheet> stls = new ArrayList<Stylesheet>();

    try {

        ConversionServiceIF cs = new ConversionService();
        Vector stylesheets = cs.listConversions(schema);

        for (int i = 0; i < stylesheets.size(); i++) {
            Hashtable hash = (Hashtable) stylesheets.get(i);
            String convertId = (String) hash.get("convert_id");
            String xslFileName = (String) hash.get("xsl");
            String type = (String) hash.get("result_type");
            String description = (String) hash.get("description");
            boolean ddConv = false;
            String xslUrl;

            if (!xslFileName.startsWith(Properties.gdemURL + "/do/getStylesheet?id=")) {
                xslUrl = Properties.gdemURL + "/" + Names.XSL_FOLDER + xslFileName;
            } else {
                xslUrl = (String) hash.get("xsl");
                ddConv = true;
            }

            Stylesheet stl = new Stylesheet();
            stl.setConvId(convertId);
            stl.setType(type);
            stl.setXsl(xslUrl);
            stl.setXslFileName(xslFileName);
            stl.setDescription(description);
            stl.setDdConv(ddConv);
            stls.add(stl);
        }

    } catch (Exception e) {
        LOGGER.error("Error getting schema stylesheets", e);
        throw new DCMException(BusinessConstants.EXCEPTION_GENERAL);
    }
    return stls;
}