Java Code Examples for java.util.TreeSet#contains()

The following examples show how to use java.util.TreeSet#contains() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DateTimeFunctions.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
private static int calcBusDays(final FormulaContext ctx, DateTime sdtFrom, DateTime sdtTo, final boolean[] excludeDays,
		final TreeSet<DateTime> excludeDates) {
	sdtFrom = getSDTCopy(ctx, sdtFrom);
	sdtFrom.setAnyTime();
	if (!sdtTo.isAnyTime()) {
		sdtTo = getSDTCopy(ctx, sdtTo);
		sdtTo.setAnyTime();
	}
	if (sdtFrom.compare(sdtFrom, sdtTo) > 0)
		return -1;
	int ret = 0;
	do {
		if (!excludeDays[sdtFrom.toJavaCal().get(Calendar.DAY_OF_WEEK)] && !excludeDates.contains(sdtFrom))
			ret++;
		sdtFrom.adjustDay(1);
	} while (sdtFrom.compare(sdtFrom, sdtTo) <= 0);
	return ret;
}
 
Example 2
Source File: PerturbationSelector.java    From OSPREY3 with GNU General Public License v2.0 6 votes vote down vote up
private void calcResMovedByPert(){
    
    resMovedByPert = new ArrayList<>();
    
    for(int pertIndex=0; pertIndex<ps.pertTypes.size(); pertIndex++){
        
        TreeSet<String> curPertRes = new TreeSet<>();

        curPertRes.addAll(ps.resNums.get(pertIndex));//residue directly affected by pertIndex
        
        for(int pertIndex2=pertIndex+1; pertIndex2<ps.pertTypes.size(); pertIndex2++){
            //for any perturbation coming after pertIndex,
            //if our perturbation (pertIndex) can change its starting conformation,
            //then it can change the conformations of all residues it affects directly
            ArrayList<String> pert2Res = ps.resNums.get(pertIndex2);
            for(String resNum : pert2Res){
                if(curPertRes.contains(resNum)){
                    curPertRes.addAll(pert2Res);
                    break;
                }
            }
        }
        
        resMovedByPert.add(curPertRes);
    }
}
 
Example 3
Source File: VerificationCodeGenerator.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * Collect the file level checksums and filenames
 * @param prefixForRelative The portion of the filepath which preceeds the relative file path for the archive
 * @param sourceDirectory
 * @param fileNameAndChecksums
 * @throws IOException
 */
private void collectFileData(String prefixForRelative, File sourceDirectory,
		ArrayList<String> fileNameAndChecksums, TreeSet<String> skippedFiles) throws IOException {
	if (!sourceDirectory.isDirectory()) {
		return;
	}
	File[] filesAndDirs = sourceDirectory.listFiles();
	for (int i = 0; i < filesAndDirs.length; i++) {
		if (filesAndDirs[i].isDirectory()) {
			collectFileData(prefixForRelative, filesAndDirs[i], fileNameAndChecksums, skippedFiles);
		} else {
			String filePath = normalizeFilePath(filesAndDirs[i].getAbsolutePath()
					.substring(prefixForRelative.length()+1));
			if (!skippedFiles.contains(filePath)) {
				String checksumValue = this.fileChecksumGenerator.getFileChecksum(filesAndDirs[i]).toLowerCase();
				fileNameAndChecksums.add(checksumValue+"||"+filePath+END_OF_LINE_CHAR);
			}
		}
	}
}
 
Example 4
Source File: SelectQueryBuilder.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
public boolean isStaticNode(ExprKraken whereExpr)
{
  TreeSet<String> keys = new TreeSet<>();
  
  whereExpr.fillAssignedKeys(keys);
  
  for (Column col : getTable().getKeyColumns()) {
    if (keys.contains(col.name())) {
      continue;
    }
    else if (keys.contains(":key_" + col.name())) {
      continue;
    }
    else if (":hash".equals(col.name())) {
      continue;
    }
    else {
      return false;
    }
  }
  
  return true;
}
 
Example 5
Source File: LoginController.java    From HubTurbo with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void getPreviousLoginDetails() {
    Optional<RepositoryId> lastViewedRepository = logic.prefs.getLastViewedRepository();
    TreeSet<String> storedRepos = new TreeSet<>(logic.getStoredRepos());
    if (lastViewedRepository.isPresent() &&
            storedRepos.contains(RepositoryId.create(
                    lastViewedRepository.get().getOwner(),
                    lastViewedRepository.get().getName()).generateId())) {
        owner = lastViewedRepository.get().getOwner();
        repo = lastViewedRepository.get().getName();
    } else if (!storedRepos.isEmpty()) {
        RepositoryId repositoryId = RepositoryId.createFromId(storedRepos.first());
        owner = repositoryId.getOwner();
        repo = repositoryId.getName();
    }
    username = logic.prefs.getLastLoginUsername();
    password = logic.prefs.getLastLoginPassword();
}
 
Example 6
Source File: WebViewActivity.java    From GankMeizhi with Apache License 2.0 5 votes vote down vote up
private void onFavoriteClicked(MenuItem item, TreeSet<String> favorites, String objectId) {
    if (favorites.contains(objectId)) {
        favorites.remove(objectId);
    } else {
        favorites.add(objectId);
    }
    DbHelper.getHelper().getLiteOrm().save(favorite);
    changeFavoriteIcon(item, favorites, objectId);
}
 
Example 7
Source File: ProtoApiFromOpenApi.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
public void addFromSwagger(Service.Builder serviceBuilder, Swagger swagger) {
  Map<String, String> duplicateOperationIdLookup = Maps.newHashMap();
  TreeSet<String> urlPaths = Sets.newTreeSet(swagger.getPaths().keySet());
  for (String urlPath : urlPaths) {
    Path pathObj = swagger.getPath(urlPath);
    createServiceMethodsFromPath(serviceBuilder, urlPath, pathObj, duplicateOperationIdLookup);
  }

  if (isAllowAllMethodsConfigured(swagger, diagCollector)) {
    Path userDefinedWildCardPathObject = new Path();
    if (urlPaths.contains(OpenApiUtils.WILDCARD_URL_PATH)) {
      userDefinedWildCardPathObject = swagger.getPath(OpenApiUtils.WILDCARD_URL_PATH);
    }
    createServiceMethodsFromPath(
        serviceBuilder,
        OpenApiUtils.WILDCARD_URL_PATH,
        getNewWildCardPathObject(userDefinedWildCardPathObject),
        duplicateOperationIdLookup);
  }

  coreApiBuilder.setVersion(swagger.getInfo().getVersion());
  if (isDeprecated(swagger)) {
    coreApiBuilder.addOptions(
        createBoolOption(
            ServiceOptions.getDescriptor()
                .findFieldByNumber(ServiceOptions.DEPRECATED_FIELD_NUMBER)
                .getFullName(),
            true));
  }
  serviceBuilder.addApis(coreApiBuilder);
}
 
Example 8
Source File: FormulaUtils.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
@Nonnull
public static String formatFormula(@Nonnull Map<String, Integer> parsedFormula) {

  StringBuilder formattedFormula = new StringBuilder();

  // Use TreeSet to sort the elements by alphabet
  TreeSet<String> elements = new TreeSet<String>(parsedFormula.keySet());

  if (elements.contains("C")) {
    int countC = parsedFormula.get("C");
    formattedFormula.append("C");
    if (countC > 1)
      formattedFormula.append(countC);
    elements.remove("C");
    if (elements.contains("H")) {
      int countH = parsedFormula.get("H");
      formattedFormula.append("H");
      if (countH > 1)
        formattedFormula.append(countH);
      elements.remove("H");
    }
  }
  for (String element : elements) {
    formattedFormula.append(element);
    int count = parsedFormula.get(element);
    if (count > 1)
      formattedFormula.append(count);
  }
  return formattedFormula.toString();
}
 
Example 9
Source File: TreesDeleteBenchmark.java    From BinarySearchTrees with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Object timeJDKTreeSet() {
    TreeSet<Integer> treeSet = new TreeSet<>();
    for (int i = 0; i < SIZE; i++) {
        treeSet.add(randomInts[i]);
    }

    for (int i = 0; i < SIZE; i++) {
        treeSet.remove(randomInts[i]);
    }
    
    return treeSet.contains(randomInts[0]);
}
 
Example 10
Source File: AclTest.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
public void testGetAclHandlerNames() {
    Acl localAcl = new Acl();
    localAcl.registerHandler(MockAclHandler.class.getName());
    TreeSet ts = localAcl.getAclHandlerNames();
    ts.contains("handler_zero");
    ts.contains("handler_one");
    ts.contains("handle_two");
}
 
Example 11
Source File: LabelImages.java    From MorphoLibJ with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
   * Returns the set of unique labels existing in the given image, excluding 
   * the value zero (used for background).
* 
* @param image
*            a label image
* @return the list of unique labels present in image (without background)
   */
  public final static int[] findAllLabels(ImageProcessor image)
  {
      int sizeX = image.getWidth();
      int sizeY = image.getHeight();
      
      TreeSet<Integer> labels = new TreeSet<Integer> ();
      
      // iterate on image pixels
      if (image instanceof FloatProcessor) 
      {
      	// For float processor, use explicit case to int from float value  
      	for (int y = 0; y < sizeY; y++) 
      	{
      		for (int x = 0; x < sizeX; x++) 
      			labels.add((int) image.getf(x, y));
      	}
      } 
      else
      {
      	// for integer-based images, simply use integer result
      	for (int y = 0; y < sizeY; y++) 
      	{
      		for (int x = 0; x < sizeX; x++) 
      			labels.add(image.get(x, y));
      	}
      }
      
      // remove 0 if it exists
      if (labels.contains(0))
          labels.remove(0);
      
      // convert to array of integers
      int[] array = new int[labels.size()];
      Iterator<Integer> iterator = labels.iterator();
      for (int i = 0; i < labels.size(); i++) 
          array[i] = iterator.next();
      
      return array;
  }
 
Example 12
Source File: PreconditionExaminer.java    From JDeodorant with MIT License 5 votes vote down vote up
private boolean movableNonMappedNodeBeforeFirstMappedNode(TreeSet<PDGNode> mappedNodes, PDGNode nonMappedNode) {
	if(isFirstNonMappedNode(mappedNodes, nonMappedNode)) {
		return true;
	}
	Iterator<GraphEdge> incomingDependenceIterator = nonMappedNode.getIncomingDependenceIterator();
	while(incomingDependenceIterator.hasNext()) {
		PDGDependence dependence = (PDGDependence)incomingDependenceIterator.next();
		if(dependence instanceof PDGAbstractDataDependence) {
			PDGAbstractDataDependence dataDependence = (PDGAbstractDataDependence)dependence;
			PDGNode srcPDGNode = (PDGNode)dataDependence.getSrc();
			if(mappedNodes.contains(srcPDGNode)) {
				return false;
			}
			//examine if it is a self-loop edge due to a loop-carried dependence
			if(srcPDGNode.equals(nonMappedNode)) {
				if(dataDependence.isLoopCarried() && mappedNodes.contains(dataDependence.getLoop().getPDGNode())) {
					return false;
				}
			}
		}
	}
	//check if a mappedNode modifies the state of an object that is used by nonMappedNode
	for(PDGNode mappedNode : mappedNodes) {
		if(mappedNode.getId() < nonMappedNode.getId()) {
			Iterator<AbstractVariable> definedVariableIterator = mappedNode.getDefinedVariableIterator();
			while(definedVariableIterator.hasNext()) {
				AbstractVariable definedVariable = definedVariableIterator.next();
				if(definedVariable instanceof CompositeVariable) {
					CompositeVariable compositeVariable = (CompositeVariable)definedVariable;
					PlainVariable initialVariable = compositeVariable.getInitialVariable();
					if(nonMappedNode.usesLocalVariable(initialVariable)) {
						return false;
					}
				}
			}
		}
	}
	return true;
}
 
Example 13
Source File: VM22TJunctionFixer.java    From ldparteditor with MIT License 4 votes vote down vote up
private boolean isTjunctionCandidate(Vertex v, final boolean calculateDistance) {

        HashSet<GData> surfs = getLinkedSurfaces(v);

        int surfCount = surfs.size();
        if (surfCount == 0) {
            return false;
        }

        TreeSet<Vertex> verts = new TreeSet<Vertex>();
        TreeSet<Vertex> verts2 = new TreeSet<Vertex>();

        for (GData g : surfs) {
            switch (g.type()) {
            case 3:
                GData3 g3 = (GData3) g;
                Vertex v1 = new Vertex(g3.X1, g3.Y1, g3.Z1);
                Vertex v2 = new Vertex(g3.X2, g3.Y2, g3.Z2);
                Vertex v3 = new Vertex(g3.X3, g3.Y3, g3.Z3);
                if (verts2.contains(v1)) verts.add(v1);
                if (verts2.contains(v2)) verts.add(v2);
                if (verts2.contains(v3)) verts.add(v3);
                verts2.add(v1);
                verts2.add(v2);
                verts2.add(v3);
                break;
            case 4:
                GData4 g4 = (GData4) g;
                Vertex v4 = new Vertex(g4.X1, g4.Y1, g4.Z1);
                Vertex v5 = new Vertex(g4.X2, g4.Y2, g4.Z2);
                Vertex v6 = new Vertex(g4.X3, g4.Y3, g4.Z3);
                Vertex v7 = new Vertex(g4.X4, g4.Y4, g4.Z4);
                if (verts2.contains(v4)) verts.add(v4);
                if (verts2.contains(v5)) verts.add(v5);
                if (verts2.contains(v6)) verts.add(v6);
                if (verts2.contains(v7)) verts.add(v7);
                verts2.add(v4);
                verts2.add(v5);
                verts2.add(v6);
                verts2.add(v7);
                break;
            default:
            }
        }

        int vertCount = verts.size();

        if (surfCount + 1 != vertCount) {

            if (!calculateDistance) {
                return true;
            }

            for (VertexManifestation mani : vertexLinkedToPositionInFile.get(v)) {
                GData gd = mani.getGdata();
                switch (gd.type()) {
                case 2:
                    selectedLines.add((GData2) gd);
                    break;
                case 3:
                    selectedTriangles.add((GData3) gd);
                    break;
                case 4:
                    selectedQuads.add((GData4) gd);
                    break;
                case 5:
                    selectedCondlines.add((GData5) gd);
                    break;
                default:
                    continue;
                }
                selectedData.add(gd);
            }

            // Then invert the selection, so that getMinimalDistanceVertexToLines() will snap on the target

            selectInverse(new SelectorSettings());

            double result = (double) getMinimalDistanceVerticesToLines(v, false)[3];
            NLogger.debug(getClass(), result);
            return result < 1.0;
        } else {
            return false;
        }
    }
 
Example 14
Source File: QuartzCronExpression.java    From spring-cloud-deployer-cloudfoundry with Apache License 2.0 4 votes vote down vote up
protected void buildExpression(String expression) throws ParseException {

		try {

			if (seconds == null) {
				seconds = new TreeSet<>();
			}
			if (minutes == null) {
				minutes = new TreeSet<>();
			}
			if (hours == null) {
				hours = new TreeSet<>();
			}
			if (daysOfMonth == null) {
				daysOfMonth = new TreeSet<>();
			}
			if (months == null) {
				months = new TreeSet<>();
			}
			if (daysOfWeek == null) {
				daysOfWeek = new TreeSet<>();
			}
			if (years == null) {
				years = new TreeSet<>();
			}

			int exprOn = SECOND;

			StringTokenizer exprsTok = new StringTokenizer(expression, " \t",
					false);

			while (exprsTok.hasMoreTokens() && exprOn <= YEAR) {
				String expr = exprsTok.nextToken().trim();

				// throw an exception if L is used with other days of the month
				if(exprOn == DAY_OF_MONTH && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) {
					throw new ParseException("Support for specifying 'L' and 'LW' with other days of the month is not implemented", -1);
				}
				// throw an exception if L is used with other days of the week
				if(exprOn == DAY_OF_WEEK && expr.indexOf('L') != -1 && expr.length() > 1  && expr.contains(",")) {
					throw new ParseException("Support for specifying 'L' with other days of the week is not implemented", -1);
				}
				if(exprOn == DAY_OF_WEEK && expr.indexOf('#') != -1 && expr.indexOf('#', expr.indexOf('#') +1) != -1) {
					throw new ParseException("Support for specifying multiple \"nth\" days is not implemented.", -1);
				}

				StringTokenizer vTok = new StringTokenizer(expr, ",");
				while (vTok.hasMoreTokens()) {
					String v = vTok.nextToken();
					storeExpressionVals(0, v, exprOn);
				}

				exprOn++;
			}

			if (exprOn <= DAY_OF_WEEK) {
				throw new ParseException("Unexpected end of expression.",
						expression.length());
			}

			if (exprOn <= YEAR) {
				storeExpressionVals(0, "*", YEAR);
			}

			TreeSet<Integer> dow = getSet(DAY_OF_WEEK);
			TreeSet<Integer> dom = getSet(DAY_OF_MONTH);

			// Copying the logic from the UnsupportedOperationException below
			boolean dayOfMSpec = !dom.contains(NO_SPEC);
			boolean dayOfWSpec = !dow.contains(NO_SPEC);

			if (!dayOfMSpec || dayOfWSpec) {
				if (!dayOfWSpec || dayOfMSpec) {
					throw new ParseException(
							"Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.", 0);
				}
			}
		} catch (ParseException pe) {
			throw pe;
		} catch (Exception e) {
			throw new ParseException("Illegal cron expression format ("
					+ e.toString() + ")", 0);
		}
	}
 
Example 15
Source File: casc.java    From Ngram-Graphs with Apache License 2.0 4 votes vote down vote up
public static double calcDistanceBetween(CASCGraph gCorrect, CASCGraph g2, boolean bSilent)
{
    // Normalization factor
    int iNumberOfNodes = 0;
    double dRes = 0; 
    TreeSet tsVisited = new TreeSet();
    
    // Init vertex set
    Iterator iIter = gCorrect.getVerticesIterator();
    // by adding ONLY document vertices to a sorted map
    TreeSet tsVertexSet = new TreeSet();
    while (iIter.hasNext()) {
        Vertex v = (Vertex)iIter.next();
        // Check for lowercase start
        if (gCorrect.getVertexType(v) == gCorrect.NORMAL)
            tsVertexSet.add(v.getLabel());
    }
    
    Iterator iA = tsVertexSet.iterator();
    while (iA.hasNext()) {
        Vertex vA = new VertexImpl((String)iA.next());
        Iterator iB = tsVertexSet.iterator();
        
        while (iB.hasNext()) {
            Vertex vB = new VertexImpl((String)iB.next());
            
            if (vA.getLabel().equals(vB.getLabel()))
                continue;
            
            Iterator iC = tsVertexSet.iterator();
            while (iC.hasNext()) {
                // Calc distance for gCorrect
                Vertex vC = new VertexImpl((String)iC.next());
                
                 if (vA.getLabel().equals(vC.getLabel())
                    || vB.getLabel().equals(vC.getLabel()))
                    continue; // Do NOT check circles
                
                Triplet tCur = new Triplet(vA.getLabel(), vB.getLabel(),
                        vC.getLabel());
                if (tsVisited.contains(tCur))
                    continue;
                    
                Vertex vLocalA = (Vertex)gCorrect.UniqueVertices.get(vA.getLabel());
                Vertex vLocalB = (Vertex)gCorrect.UniqueVertices.get(vB.getLabel());
                Vertex vLocalC = (Vertex)gCorrect.UniqueVertices.get(vC.getLabel());
                
                double dDistAB1 = gCorrect.getShortestLinkBetween(vA, vB).size();
                double dDistAC1 = gCorrect.getShortestLinkBetween(vA, vC).size();

                // Calc distance for g2
                vLocalA = (Vertex)g2.UniqueVertices.get(vA.getLabel());
                vLocalB = (Vertex)g2.UniqueVertices.get(vB.getLabel());
                vLocalC = (Vertex)g2.UniqueVertices.get(vC.getLabel());
                // Ignore non-common nodes
                if ((vLocalA == null) || (vLocalB == null) || (vLocalC == null))
                    continue;
                
                double dDistAB2 = g2.getShortestLinkBetween(vLocalA, vLocalB).size();
                double dDistAC2 = g2.getShortestLinkBetween(vLocalA, vLocalC).size();
                
                // Check matching
                if (!bSilent)
                    // Indicate problem
                    System.err.println("Disagreement for nodes:" + vA.getLabel() +
                            "," + vB.getLabel() + "," + vC.getLabel());
                
                dRes += 1 - (Math.abs(gr.demokritos.iit.jinsect.utils.sign(dDistAB1 - dDistAC1) -
                        gr.demokritos.iit.jinsect.utils.sign(dDistAB2 - dDistAC2)) / 2);
                //System.err.println("Adding..." + (1 - (Math.abs(jinsect.utils.sign(dDistAB1 - dDistAC1) -
                        //jinsect.utils.sign(dDistAB2 - dDistAC2)) / 2)));
                iNumberOfNodes++;
                
                // Add to visited
                tsVisited.add(tCur);
            }
        }
    }
    
    return dRes / iNumberOfNodes;
}
 
Example 16
Source File: SetTests.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void test4NoBugs(TreeSet<? super CharSequence> set) {
    set.contains(new StringBuffer("Key"));
}
 
Example 17
Source File: casc.java    From Ngram-Graphs with Apache License 2.0 4 votes vote down vote up
/** Renders a graph to its DOT representation (See GraphViz for more info on the format). The DOT
 * file follows the CASC (Stemmatology Challenge) directives.
 *@param gTree The input graph.
 *@return The DOT formatted string representation of the graph.
 */
public static String graphToCASCDot(CASCGraph gTree) {
    StringBuffer sb = new StringBuffer();
    String sConnector;
    
    // Render graph
    sb.append("graph {\n");
    sConnector = "--";
    
    Iterator iIter = gTree.getEdgeSet().iterator();
    TreeSet tsDescribed = new TreeSet();
    
    while (iIter.hasNext()) {
        Edge e = (Edge)iIter.next();
        
        // Render not already described vertices
        if (!tsDescribed.contains(e.getVertexA().getLabel())) {
            tsDescribed.add(e.getVertexA().getLabel());
            if (gTree.getVertexType(e.getVertexA()) == gTree.NORMAL)
                // NORMAL
                sb.append("\t" + e.getVertexA().getLabel() + 
                    " [label=\"" + e.getVertexA().getLabel() + "\" shape=plaintext fontsize=24]\n");
            else
                // LATENT
                sb.append("\t" + e.getVertexA().getLabel() + 
                    " [shape=point]\n");
        }
        
        if (!tsDescribed.contains(e.getVertexB().getLabel())) {
            tsDescribed.add(e.getVertexB().getLabel());
            if (gTree.getVertexType(e.getVertexB()) == gTree.NORMAL)
                // NORMAL
                sb.append("\t" + e.getVertexB().getLabel() + 
                    " [label=\"" + e.getVertexB().getLabel() + "\" shape=plaintext fontsize=24]\n");
            else
                // LATENT
                sb.append("\t" + e.getVertexB().getLabel() + 
                    " [shape=point]\n");
        }
        
        // Render edge
        if (e instanceof WeightedEdge)
            sb.append("\t" + e.getVertexA() + " " + sConnector + " " + e.getVertexB() + 
                " [weight=" + (int)(((WeightedEdge)e).getWeight() * 100) + "]\n");
        else
            sb.append("\t" + e.getVertexA() + " " + sConnector + " " + e.getVertexB() + "\n");
    }
    sb.append("}");
    
    return sb.toString();
}
 
Example 18
Source File: EditRoomPrefAction.java    From unitime with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param editRoomPrefForm
 * @param request
 */
private void doUpdate(EditRoomPrefForm editRoomPrefForm, HttpServletRequest request) throws Exception {

	//get location information
	Long id = Long.valueOf(request.getParameter("id"));
	LocationDAO ldao = new LocationDAO();
	Location location = ldao.get(id);
	
	sessionContext.checkPermission(location, Right.RoomEditPreference);
	
	//update dept preference information
	
       TreeSet<Department> departments = Department.getUserDepartments(sessionContext.getUser());
	TreeSet<Department> availableDepts = new TreeSet<Department>();
       for (RoomDept rd: location.getRoomDepts()) {
       	if (departments.contains(rd.getDepartment()))
       		availableDepts.add(rd.getDepartment());
       }

	List selectedId = editRoomPrefForm.getRoomPrefLevels();
	int i = 0;
	for (Department dept: availableDepts) {
		PreferenceLevel seletedPL = PreferenceLevelDAO.getInstance().get(Long.valueOf((String)selectedId.get(i++)));
		RoomPref selectedRP = new RoomPref();
		selectedRP.setRoom(location);
		selectedRP.setPrefLevel(seletedPL);
		selectedRP.setOwner(dept);
		Set prefs = dept.getPreferences();

		for (Iterator iter = prefs.iterator(); iter.hasNext();) {
			Preference p = (Preference)iter.next();
           	if (p instanceof RoomPref && ((RoomPref)p).getRoom().equals(location)) {
           		PreferenceLevelDAO.getInstance().getSession().delete(p);
           		iter.remove();
            }
		}
  
       	prefs.add(selectedRP);
       	PreferenceLevelDAO.getInstance().getSession().saveOrUpdate(dept);
           ChangeLog.addChange(
                   null, 
                   sessionContext, 
                   location, 
                   ChangeLog.Source.ROOM_PREF_EDIT, 
                   ChangeLog.Operation.UPDATE, 
                   null, 
                   dept);
	}
       
}
 
Example 19
Source File: ExcludeVMPlugin.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ResourcePool transform(ResourcePool in, ResourcePoolBuilder out) {
    ResourcePoolModule javaBase = in.moduleView().findModule("java.base").get();
    String[] jvmlibs = jvmlibs(javaBase);
    TreeSet<Jvm> existing = new TreeSet<>(new JvmComparator());
    TreeSet<Jvm> removed = new TreeSet<>(new JvmComparator());
    if (!keepAll) {
        // First retrieve all available VM names and removed VM
        List<ResourcePoolEntry> jvms = getVMs(javaBase, jvmlibs);
        for (Jvm jvm : Jvm.values()) {
            for (ResourcePoolEntry md : jvms) {
                String mdPath = md.path();
                for (String jvmlib : jvmlibs) {
                    if (mdPath.endsWith("/" + jvm.getName() + "/" + jvmlib)) {
                        existing.add(jvm);
                        if (isRemoved(md)) {
                            removed.add(jvm);
                        }
                    }
                }
            }
        }
    }
    // Check that target exists
    if (!keepAll) {
        if (!existing.contains(target)) {
            throw new PluginException("Selected VM " + target.getName() + " doesn't exist.");
        }
    }

    // Rewrite the jvm.cfg file.
    in.transformAndCopy((file) -> {
        if (!keepAll) {
            if (file.type().equals(ResourcePoolEntry.Type.NATIVE_LIB)) {
                if (file.path().endsWith(JVM_CFG)) {
                    try {
                        file = handleJvmCfgFile(file, existing, removed);
                    } catch (IOException ex) {
                        throw new UncheckedIOException(ex);
                    }
                }
            }
            file = isRemoved(file) ? null : file;
        }
        return file;
    }, out);

    return out.build();
}
 
Example 20
Source File: CronExpression.java    From cyclops with Apache License 2.0 4 votes vote down vote up
protected void buildExpression(final String expression) throws ParseException {
    expressionParsed = true;

    try {

        if (seconds == null) {
            seconds = new TreeSet<Integer>();
        }
        if (minutes == null) {
            minutes = new TreeSet<Integer>();
        }
        if (hours == null) {
            hours = new TreeSet<Integer>();
        }
        if (daysOfMonth == null) {
            daysOfMonth = new TreeSet<Integer>();
        }
        if (months == null) {
            months = new TreeSet<Integer>();
        }
        if (daysOfWeek == null) {
            daysOfWeek = new TreeSet<Integer>();
        }
        if (years == null) {
            years = new TreeSet<Integer>();
        }

        int exprOn = SECOND;

        final StringTokenizer exprsTok = new StringTokenizer(
                                                             expression, " \t", false);

        while (exprsTok.hasMoreTokens() && exprOn <= YEAR) {
            final String expr = exprsTok.nextToken()
                                        .trim();

            // throw an exception if L is used with other days of the month
            if (exprOn == DAY_OF_MONTH && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) {
                throw new ParseException(
                                         "Support for specifying 'L' and 'LW' with other days of the month is not implemented", -1);
            }
            // throw an exception if L is used with other days of the week
            if (exprOn == DAY_OF_WEEK && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) {
                throw new ParseException(
                                         "Support for specifying 'L' with other days of the week is not implemented", -1);
            }
            if (exprOn == DAY_OF_WEEK && expr.indexOf('#') != -1 && expr.indexOf('#', expr.indexOf('#') + 1) != -1) {
                throw new ParseException(
                                         "Support for specifying multiple \"nth\" days is not implemented.", -1);
            }

            final StringTokenizer vTok = new StringTokenizer(
                                                             expr, ",");
            while (vTok.hasMoreTokens()) {
                final String v = vTok.nextToken();
                storeExpressionVals(0, v, exprOn);
            }

            exprOn++;
        }

        if (exprOn <= DAY_OF_WEEK) {
            throw new ParseException(
                                     "Unexpected take of expression.", expression.length());
        }

        if (exprOn <= YEAR) {
            storeExpressionVals(0, "*", YEAR);
        }

        final TreeSet<Integer> dow = getSet(DAY_OF_WEEK);
        final TreeSet<Integer> dom = getSet(DAY_OF_MONTH);

        // Copying the logic from the UnsupportedOperationException below
        final boolean dayOfMSpec = !dom.contains(NO_SPEC);
        final boolean dayOfWSpec = !dow.contains(NO_SPEC);

        if (!dayOfMSpec || dayOfWSpec) {
            if (!dayOfWSpec || dayOfMSpec) {
                throw new ParseException(
                                         "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.", 0);
            }
        }
    } catch (final ParseException pe) {
        throw pe;
    } catch (final Exception e) {
        throw new ParseException(
                                 "Illegal cron expression format (" + e.toString() + ")", 0);
    }
}