Example usage for java.util HashSet contains

List of usage examples for java.util HashSet contains

Introduction

In this page you can find the example usage for java.util HashSet contains.

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java

/**
 * //  w  w w . j av a 2 s .c  om
 */
protected void createIndexFile() {
    HashSet<String> nameHash = new HashSet<String>();

    String fName = schemaDir.getAbsolutePath() + File.separator + "index.html";
    try {
        File html = new File(fName);
        BufferedWriter output = new BufferedWriter(new FileWriter(html));

        int index = mapTemplate.indexOf(contentTag);
        String subContent = mapTemplate.substring(0, index);
        subContent = StringUtils.replace(subContent, "<!-- Updated -->",
                (new SimpleDateFormat("yyyy-MM-dd")).format(Calendar.getInstance().getTime()));
        output.write(StringUtils.replace(subContent, "<!-- Title -->", "Schema Index"));

        output.write("<UL>");
        output.write("<LI><a href=\"CollectionOverview.html\">Schema Overview</a></LI>\n");
        for (ERDTable t : tblTracker.getList()) {
            DBTableInfo ti = t.getTable();

            // Make Unique file name
            String outFileName = ti.getShortClassName();
            int i = 1;
            while (nameHash.contains(outFileName)) {
                outFileName = ti.getShortClassName() + i;
                i++;
            }
            nameHash.add(outFileName);

            output.write("<LI><a href=\"" + outFileName + ".html\">"
                    + StringEscapeUtils.escapeHtml(ti.getTitle()) + "</a></LI>\n");
        }
        output.write("</UL>");
        output.write(mapTemplate.substring(index + contentTag.length() + 1, mapTemplate.length()));

        output.close();

    } catch (Exception e) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, e);
        e.printStackTrace();
    }

}

From source file:com.sun.faban.harness.webclient.ResultAction.java

/**
 * This method is responsible for uploading the runs to repository.
 * @param uploadSet// w w w . j av  a 2s.  c o m
 * @param replaceSet
 * @return HashSet
 * @throws java.io.IOException
 */
public static HashSet<String> uploadRuns(String[] runIds, HashSet<File> uploadSet, HashSet<String> replaceSet)
        throws IOException {
    // 3. Upload the run
    HashSet<String> duplicates = new HashSet<String>();

    // Prepare run id set for cross checking.
    HashSet<String> runIdSet = new HashSet<String>(runIds.length);
    for (String runId : runIds) {
        runIdSet.add(runId);
    }

    // Prepare the parts for the request.
    ArrayList<Part> params = new ArrayList<Part>();
    params.add(new StringPart("host", Config.FABAN_HOST));
    for (String replaceId : replaceSet) {
        params.add(new StringPart("replace", replaceId));
    }
    for (File jarFile : uploadSet) {
        params.add(new FilePart("jarfile", jarFile));
    }
    Part[] parts = new Part[params.size()];
    parts = params.toArray(parts);

    // Send the request for each reposotory.
    for (URL repository : Config.repositoryURLs) {
        URL repos = new URL(repository, "/controller/uploader/upload_runs");
        PostMethod post = new PostMethod(repos.toString());
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_FORBIDDEN)
            logger.warning("Server denied permission to upload run !");
        else if (status == HttpStatus.SC_NOT_ACCEPTABLE)
            logger.warning("Run origin error!");
        else if (status != HttpStatus.SC_CREATED)
            logger.warning(
                    "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
        for (File jarFile : uploadSet) {
            jarFile.delete();
        }

        String response = post.getResponseBodyAsString();

        if (status == HttpStatus.SC_CREATED) {

            StringTokenizer t = new StringTokenizer(response.trim(), "\n");
            while (t.hasMoreTokens()) {
                String duplicateRun = t.nextToken().trim();
                if (duplicateRun.length() > 0)
                    duplicates.add(duplicateRun.trim());
            }

            for (Iterator<String> iter = duplicates.iterator(); iter.hasNext();) {
                String runId = iter.next();
                if (!runIdSet.contains(runId)) {
                    logger.warning("Unexpected archive response from " + repos + ": " + runId);
                    iter.remove();
                }
            }
        } else {
            logger.warning("Message from repository: " + response);
        }
    }
    return duplicates;
}

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.
 *///from  w  w  w.j a v  a 2  s .c  o m
@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:com.sun.faban.harness.webclient.ResultAction.java

/**
 * This method is responsible for archiving the runs to the repository.
 * @param request//w w  w.  j  av  a 2s  .c o  m
 * @param response
 * @return String
 * @throws java.io.IOException
 * @throws java.io.FileNotFoundException
 * @throws java.text.ParseException
 * @throws java.lang.ClassNotFoundException
 */
public String archive(HttpServletRequest request, HttpServletResponse response)
        throws IOException, FileNotFoundException, ParseException, ClassNotFoundException {
    //Reading values from request
    String[] duplicateIds = request.getParameterValues("duplicates");
    String[] replaceIds = request.getParameterValues("replace");
    String[] runIds = request.getParameterValues("select");
    String submitAction = request.getParameter("process");

    HashSet<String> modelDuplicates = new HashSet<String>();
    HashSet<String> replaceSet = new HashSet<String>();
    HashSet<File> uploadSet = new HashSet<File>();
    HashSet<String> uploadedRuns = new HashSet<String>();
    HashSet<String> duplicateSet = new HashSet<String>();
    if (replaceIds != null) {
        for (String replaceId : replaceIds) {
            replaceSet.add(replaceId);
        }
    }

    EditArchiveModel model = new EditArchiveModel();
    model.runIds = runIds;
    if (duplicateIds != null) {
        for (String duplicateId : duplicateIds) {
            modelDuplicates.add(duplicateId);
        }
    }
    model.duplicates = modelDuplicates;
    if (Config.repositoryURLs != null && Config.repositoryURLs.length > 1)
        model.head = "Repositories";
    else
        model.head = "Repository";

    model.results = new RunResult[runIds.length];
    for (int i = 0; i < runIds.length; i++) {
        model.results[i] = RunResult.getInstance(new RunId(runIds[i]));
    }

    if (submitAction.equals("Archive")) {
        for (int i = 0; i < model.runIds.length; i++) {
            String runId = model.runIds[i];
            if (model.duplicates.contains(runId)) {
                if (replaceIds != null) {
                    if (replaceSet.contains(runId)) {
                        prepareUpload(request, model.results[i], uploadedRuns, uploadSet);
                    } else { // Description or tags got changed, replace anyway...
                        if (!model.results[i].description.equals(request.getParameter(runId + "_description"))
                                || !model.results[i].tags.toString()
                                        .equals(request.getParameter(runId + "_tags"))) {
                            replaceSet.add(runId);
                            prepareUpload(request, model.results[i], uploadedRuns, uploadSet);
                        }
                    }
                } else { // Single run, description changed, replace anyway.
                    if (!model.results[i].description.equals(request.getParameter(runId + "_description"))
                            || !model.results[i].tags.toString()
                                    .equals(request.getParameter(runId + "_tags"))) {
                        replaceSet.add(runId);
                        prepareUpload(request, model.results[i], uploadedRuns, uploadSet);
                    }
                }
            } else {
                prepareUpload(request, model.results[i], uploadedRuns, uploadSet);
            }
        }
    }
    duplicateSet = uploadRuns(runIds, uploadSet, replaceSet);
    request.setAttribute("archive.model", model);
    request.setAttribute("uploadedRuns", uploadedRuns);
    request.setAttribute("duplicateRuns", duplicateSet);
    return "/archive_results.jsp";
}

From source file:eu.europa.ec.fisheries.uvms.rules.service.business.AbstractFact.java

public boolean valueDoesNotContainAll(List<CodeType> codeTypes, String... valuesToMatch) {
    HashSet<String> valuesFoundInListOfCodeTypes = new HashSet<>();
    HashSet<String> valuesToBeFound = new HashSet<>(Arrays.asList(valuesToMatch));

    if (valuesToMatch == null || valuesToMatch.length == 0 || CollectionUtils.isEmpty(codeTypes)) {
        return true;
    }//from  w  w  w .jav  a 2s.  co m

    for (CodeType codeType : codeTypes) {
        String value = codeType.getValue();

        if (valuesToBeFound.contains(value)) {
            valuesFoundInListOfCodeTypes.add(value);
        }
    }

    return !valuesFoundInListOfCodeTypes.equals(valuesToBeFound);
}

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

/**
 * //www .  j ava  2s .co  m
 */
private void discoverLocalesFromData(final Vector<DisciplineBasedContainer> containers) {
    HashSet<String> hash = new HashSet<String>();

    for (DisciplineBasedContainer container : containers) {
        for (SpLocaleItemStr str : container.getNames()) {
            String language = str.getLanguage();
            String country = str.getCountry();
            String variant = str.getVariant();

            String key = String.format("%s_%s_%s", language, country != null ? country : "",
                    variant != null ? variant : "");
            if (!hash.contains(key)) {
                Locale locale = null;
                if (StringUtils.isNotBlank(language) && StringUtils.isNotBlank(country)
                        && StringUtils.isNotBlank(variant)) {
                    locale = new Locale(language, country, variant);

                } else if (StringUtils.isNotBlank(language) && StringUtils.isNotBlank(country)) {
                    locale = new Locale(language, country);

                } else if (StringUtils.isNotBlank(language)) {
                    locale = new Locale(language);
                }
                if (locale != null) {
                    System.err.println("[" + key + "] " + locale);
                    availLocales.add(locale);
                    hash.add(key);
                }
            }
        }
    }
}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.AgentCleanupProcessor.java

/**
 * @param ti//from  w  w w .  j  ava 2  s  . c  o m
 * @param fii
 * @param inClause
 * @return
 */
private JoinTableDupStatus fixRelationships(final DBTableInfo ti, final FindItemInfo fii,
        final String inClause) {
    /*
    12 - AccessionAgent.java:   @UniqueConstraint(columnNames = { "Role", "AgentID", "AccessionID" }) })
    19 - BorrowAgent.java:      @UniqueConstraint(columnNames = { "Role", "AgentID", "BorrowID" }) 
    35 - DeaccessionAgent.java: @UniqueConstraint(columnNames = { "Role", "AgentID", "DeaccessionID" }) })
    53 - LoanAgent.java:        @UniqueConstraint(columnNames = { "Role", "AgentID", "LoanID" })
    133 - GiftAgent.java         @UniqueConstraint(columnNames = { "Role", "AgentID", "GiftID" }) 
            
    30 - Collector.java:        @UniqueConstraint(columnNames = {"AgentID", "CollectingEventID"}) })
    146 - FundingAgent.java:     @UniqueConstraint(columnNames = {"AgentID", "CollectingTripID"}) })
            
     // Ordering
    86 - AgentSpecialty.java:   @UniqueConstraint(columnNames = {"AgentID", "OrderNumber"}) })
    49 - GroupPerson.java:      @UniqueConstraint(columnNames = { "OrderNumber", "GroupID" }) 
    */

    int tblId = ti.getTableId();

    if (tblId == 86) {
        if (hasAgentSpecialty) {
            return fixAgentSpecialty(ti, fii);
        }
        return JoinTableDupStatus.eOK;
    }

    if (tblId == 49) {
        if (hasGroups) {
            return fixGroupPersons(fii);
        }
        return JoinTableDupStatus.eOK;
    }

    String tblName = ti.getName();

    String otherFld = null;
    switch (tblId) {
    // Has Role
    case 12:
        otherFld = "AccessionID";
        break;
    case 19:
        otherFld = "BorrowID";
        break;
    case 35:
        otherFld = "DeaccessionID";
        break;
    case 53:
        otherFld = "LoanID";
        break;
    case 133:
        otherFld = "GiftID";
        break;

    // No Role
    case 30:
        otherFld = "CollectingEventID";
        break;
    case 146:
        otherFld = "CollectingTripID";
        break;
    }

    String sql = String.format(
            "SELECT COUNT(*) FROM (SELECT %s,COUNT(%s) CNT FROM %s WHERE AgentID IN %s GROUP BY %s) T1 WHERE CNT > 1",
            otherFld, otherFld, tblName, inClause, otherFld);
    logSQL(sql);
    int numDups = BasicSQLUtils.getCountAsInt(sql);
    if (numDups == 0) {
        return JoinTableDupStatus.eNeedUpdating;
    }

    final String srchStr = "SELECT %s FROM %s WHERE AgentID = %d";

    boolean isError = false;
    HashSet<Integer> usedSet = new HashSet<Integer>();
    sql = String.format(srchStr, otherFld, tblName, fii.getId());
    Integer otherId = BasicSQLUtils.getCountAsInt(sql);
    if (otherId != null) {
        usedSet.add(otherId);
    }

    for (Integer agentId : fii.getDuplicateIds()) {
        sql = String.format(srchStr, otherFld, tblName, agentId);
        logSQL(sql);
        otherId = BasicSQLUtils.getCountAsInt(sql);
        System.out.println(
                String.format("%d %s - %s", otherId, usedSet.contains(otherId) ? "Contains" : "no", sql));

        int cnt = BasicSQLUtils
                .getCountAsInt(String.format("SELECT COUNT(*) FROM %s WHERE %s = %d AND AgentID = %d", tblName,
                        otherFld, otherId, fii.getId()));
        logSQL(sql);
        boolean isDelete;
        if (cnt > 0 || usedSet.contains(otherId)) {
            sql = String.format("DELETE FROM %s WHERE AgentID = %d AND %s = %d", tblName, agentId, otherFld,
                    otherId);
            isDelete = true;
        } else {
            sql = String.format("UPDATE %s SET AgentID = %d WHERE AgentID = %d AND %s = %d", tblName,
                    fii.getId(), agentId, otherFld, otherId);
            usedSet.add(otherId);
            isDelete = false;
        }
        logSQL(sql);
        if (BasicSQLUtils.update(sql) != 1) {
            showProcessingMessage(String.format("Error deleting/updating table %s", tblName));
            isError = true;
            break;
        }
        if (isDelete) {
            totalDeleted++;
        } else {
            totalUpdated++;
        }
    }

    if (!isError) {
        if (updCnt > 0)
            outputRows[3].append(", ");
        outputRows[3].append(ti.getTitle());
    }
    return isError ? JoinTableDupStatus.eError : JoinTableDupStatus.eNeedUpdating;
}

From source file:com.predic8.membrane.annot.bean.MCUtil.java

private static void addXML(Object object, String id, XMLStreamWriter xew, SerializationContext sc)
        throws XMLStreamException {
    if (object == null)
        throw new InvalidParameterException("'object' must not be null.");

    Class<? extends Object> clazz = object.getClass();

    MCElement e = clazz.getAnnotation(MCElement.class);
    if (e == null)
        throw new IllegalArgumentException("'object' must be @MCElement-annotated.");

    BeanWrapperImpl src = new BeanWrapperImpl(object);

    xew.writeStartElement(e.name());/*from   w w w  .j  ava2 s  .co m*/

    if (id != null)
        xew.writeAttribute("id", id);

    HashSet<String> attributes = new HashSet<String>();
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCAttribute a = m.getAnnotation(MCAttribute.class);
        if (a != null) {
            Object value = src.getPropertyValue(propertyName);
            String str;
            if (value == null)
                continue;
            else if (value instanceof String)
                str = (String) value;
            else if (value instanceof Boolean)
                str = ((Boolean) value).toString();
            else if (value instanceof Integer)
                str = ((Integer) value).toString();
            else if (value instanceof Long)
                str = ((Long) value).toString();
            else if (value instanceof Enum<?>)
                str = value.toString();
            else {
                MCElement el = value.getClass().getAnnotation(MCElement.class);
                if (el != null) {
                    str = defineBean(sc, value, null, true);
                } else {
                    str = "?";
                    sc.incomplete = true;
                }
            }

            if (a.attributeName().length() > 0)
                propertyName = a.attributeName();

            attributes.add(propertyName);
            xew.writeAttribute(propertyName, str);
        }
    }
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class);
        if (o != null) {
            Object value = src.getPropertyValue(propertyName);
            if (value instanceof Map<?, ?>) {
                Map<?, ?> map = (Map<?, ?>) value;
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    Object key = entry.getKey();
                    Object val = entry.getValue();
                    if (!(key instanceof String) || !(val instanceof String)) {
                        sc.incomplete = true;
                        key = "incompleteAttributes";
                        val = "?";
                    }
                    if (attributes.contains(key))
                        continue;
                    attributes.add((String) key);
                    xew.writeAttribute((String) key, (String) val);
                }
            } else {
                xew.writeAttribute("incompleteAttributes", "?");
                sc.incomplete = true;
            }
        }
    }

    List<Method> childElements = new ArrayList<Method>();
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));

        MCChildElement c = m.getAnnotation(MCChildElement.class);
        if (c != null) {
            childElements.add(m);
        }
        MCTextContent t = m.getAnnotation(MCTextContent.class);
        if (t != null) {
            Object value = src.getPropertyValue(propertyName);
            if (value == null) {
                continue;
            } else if (value instanceof String) {
                xew.writeCharacters((String) value);
            } else {
                xew.writeCharacters("?");
                sc.incomplete = true;
            }
        }
    }

    Collections.sort(childElements, new Comparator<Method>() {

        @Override
        public int compare(Method o1, Method o2) {
            MCChildElement c1 = o1.getAnnotation(MCChildElement.class);
            MCChildElement c2 = o2.getAnnotation(MCChildElement.class);
            return c1.order() - c2.order();
        }
    });

    for (Method m : childElements) {
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));

        Object value = src.getPropertyValue(propertyName);
        if (value != null) {
            if (value instanceof Collection<?>) {
                for (Object item : (Collection<?>) value)
                    addXML(item, null, xew, sc);
            } else {
                addXML(value, null, xew, sc);
            }
        }
    }

    xew.writeEndElement();
}

From source file:eu.europa.ec.fisheries.uvms.rules.service.business.AbstractFact.java

public boolean listIdDoesNotContainAll(List<CodeType> codeTypes, String... valuesToMatch) {
    HashSet<String> valuesFoundInListOfCodeTypes = new HashSet<>();
    HashSet<String> valuesToBeFound = new HashSet<>(Arrays.asList(valuesToMatch));

    if (valuesToMatch == null || valuesToMatch.length == 0 || CollectionUtils.isEmpty(codeTypes)) {
        return true;
    }/*www .j  a  v  a 2  s  .  c  om*/

    for (CodeType codeType : codeTypes) {
        if (codeType != null) {
            String listId = codeType.getListId();

            if (valuesToBeFound.contains(listId)) {
                valuesFoundInListOfCodeTypes.add(listId);
            }
        }
    }

    return !valuesFoundInListOfCodeTypes.equals(valuesToBeFound);
}

From source file:org.epics.archiverappliance.retrieval.DataRetrievalServlet.java

/**
 * If the pv is hosted on another appliance, proxy retrieval requests from that appliance
 * We expect to return immediately after this method. 
 * @param req/*w w  w  .  j  a  v  a 2 s .  c o m*/
 * @param resp
 * @param pvName
 * @param useChunkedEncoding
 * @param dataRetrievalURLForPV
 * @throws IOException
 */
private void proxyRetrievalRequest(HttpServletRequest req, HttpServletResponse resp, String pvName,
        boolean useChunkedEncoding, String dataRetrievalURLForPV) throws IOException {
    try {
        // TODO add some intelligent business logic to determine if redirect/proxy. 
        // It may be beneficial to support both and choose based on where the client in calling from or perhaps from a header?
        boolean redirect = false;
        if (redirect) {
            logger.debug("Data for pv " + pvName + "is elsewhere. Redirecting to appliance "
                    + dataRetrievalURLForPV);
            URI redirectURI = new URI(dataRetrievalURLForPV + "/" + req.getPathInfo());
            String redirectURIStr = redirectURI.normalize().toString() + "?" + req.getQueryString();
            logger.debug("URI for redirect is " + redirectURIStr);
            resp.sendRedirect(redirectURIStr);
            return;
        } else {
            logger.debug("Data for pv " + pvName + "is elsewhere. Proxying appliance " + dataRetrievalURLForPV);
            URI redirectURI = new URI(dataRetrievalURLForPV + "/" + req.getPathInfo());
            String redirectURIStr = redirectURI.normalize().toString() + "?" + req.getQueryString();
            logger.debug("URI for proxying is " + redirectURIStr);

            //            if(useChunkedEncoding) { 
            //               resp.addHeader("Transfer-Encoding", "chunked");
            //            }

            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet getMethod = new HttpGet(redirectURIStr);
            getMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/
            try (CloseableHttpResponse response = httpclient.execute(getMethod)) {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    HashSet<String> proxiedHeaders = new HashSet<String>();
                    proxiedHeaders.addAll(Arrays.asList(MimeResponse.PROXIED_HEADERS));
                    Header[] headers = response.getAllHeaders();
                    for (Header header : headers) {
                        if (proxiedHeaders.contains(header.getName())) {
                            logger.debug("Adding headerName " + header.getName() + " and value "
                                    + header.getValue() + " when proxying request");
                            resp.addHeader(header.getName(), header.getValue());
                        }
                    }

                    if (entity != null) {
                        logger.debug("Obtained a HTTP entity of length " + entity.getContentLength());
                        try (OutputStream os = resp.getOutputStream();
                                InputStream is = new BufferedInputStream(entity.getContent())) {
                            byte buf[] = new byte[10 * 1024];
                            int bytesRead = is.read(buf);
                            while (bytesRead > 0) {
                                os.write(buf, 0, bytesRead);
                                resp.flushBuffer();
                                bytesRead = is.read(buf);
                            }
                        }
                    } else {
                        throw new IOException("HTTP response did not have an entity associated with it");
                    }
                } else {
                    logger.error("Invalid status code " + response.getStatusLine().getStatusCode()
                            + " when connecting to URL " + redirectURIStr + ". Sending the errorstream across");
                    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                        try (InputStream is = new BufferedInputStream(response.getEntity().getContent())) {
                            byte buf[] = new byte[10 * 1024];
                            int bytesRead = is.read(buf);
                            while (bytesRead > 0) {
                                os.write(buf, 0, bytesRead);
                                bytesRead = is.read(buf);
                            }
                        }
                        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                        resp.sendError(response.getStatusLine().getStatusCode(), new String(os.toByteArray()));
                    }
                }
            }
        }
        return;
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }
}