List of usage examples for java.lang Integer compare
public static int compare(int x, int y)
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java
@PostConstruct public void init() { Collections.sort(fieldPersistenceProviders, new Comparator<FieldPersistenceProvider>() { @Override//from ww w.ja v a 2s . c o m public int compare(FieldPersistenceProvider o1, FieldPersistenceProvider o2) { return Integer.compare(o1.getOrder(), o2.getOrder()); } }); Collections.sort(populateValidators, new Comparator<PopulateValueRequestValidator>() { @Override public int compare(PopulateValueRequestValidator o1, PopulateValueRequestValidator o2) { return Integer.compare(o1.getOrder(), o2.getOrder()); } }); }
From source file:tds.student.sql.repositorysp.ItemBankRepository.java
public AccList getTestAccommodations(String testKey) throws ReturnStatusException { AccList accList = new AccList(); final String CMD_GET_TEST_PROPERTIES = "BEGIN; SET NOCOUNT ON; exec IB_GetTestAccommodations ${testKey}; end;"; try (SQLConnection connection = getSQLConnection()) { SqlParametersMaps parametersQuery = new SqlParametersMaps(); parametersQuery.put("testKey", testKey); MultiDataResultSet results = executeStatement(connection, CMD_GET_TEST_PROPERTIES, parametersQuery, false);// w w w . j a v a 2 s. co m Iterator<SingleDataResultSet> iterSingleDataResultSet = results.getResultSets(); SingleDataResultSet firstResultSet = iterSingleDataResultSet.next(); ReturnStatusException.getInstanceIfAvailable(firstResultSet); Iterator<DbResultRecord> records = firstResultSet.getRecords(); while (records.hasNext()) { DbResultRecord record = records.next(); Data accData = AccListParseData.parseData(record); // HACK: Skip loading non-functional accommodations if (!accData.isFunctional()) continue; accList.add(accData); } SingleDataResultSet secondResultSet = iterSingleDataResultSet.next(); records = secondResultSet.getRecords(); while (records.hasNext()) { DbResultRecord record = records.next(); accList.getDependencies().add(AccListParseData.parseDependency(record)); } Collections.sort(accList.getData(), new Comparator<Data>() { @Override public int compare(Data acc1, Data acc2) { if (acc1.getSegmentPosition() != acc2.getSegmentPosition()) return Integer.compare(acc1.getSegmentPosition(), acc2.getSegmentPosition()); if (acc1.getToolTypeSortOrder() != acc2.getToolTypeSortOrder()) return Integer.compare(acc1.getToolTypeSortOrder(), acc2.getToolTypeSortOrder()); if (acc1.getToolValueSortOrder() != acc2.getToolValueSortOrder()) return Integer.compare(acc1.getToolValueSortOrder(), acc2.getToolValueSortOrder()); return 0; } }); } catch (SQLException e) { _logger.error(e.getMessage()); throw new ReturnStatusException(e); } return accList; }
From source file:com.wrmsr.wava.TestOutlining.java
public static Pair<Function, Function> inlineThatOneSwitch(Function function, int num) { Node body = function.getBody(); LocalAnalysis loa = LocalAnalysis.analyze(body); ControlTransferAnalysis cfa = ControlTransferAnalysis.analyze(body); ValueTypeAnalysis vta = ValueTypeAnalysis.analyze(body, false); Map<Node, Optional<Node>> parentsByNode = Analyses.getParents(body); Map<Node, Integer> totalChildrenByNode = Analyses.getChildCounts(body); Map<Name, Node> nodesByName = Analyses.getNamedNodes(body); Node maxNode = body;//from w w w . j av a 2s. c o m int maxDiff = 0; Node cur = body; while (true) { Optional<Node> maxChild = cur.getChildren().stream() .max((l, r) -> Integer.compare(totalChildrenByNode.get(l), totalChildrenByNode.get(r))); if (!maxChild.isPresent()) { break; } int diff = totalChildrenByNode.get(cur) - totalChildrenByNode.get(maxChild.get()); if (diff > maxDiff) { maxNode = cur; maxDiff = diff; } cur = maxChild.get(); } List<Node> alsdfj = new ArrayList<>(maxNode.getChildren()); Collections.sort(alsdfj, (l, r) -> -Integer.compare(totalChildrenByNode.get(l), totalChildrenByNode.get(r))); Index externalRetControl; Index externalRetValue; List<Local> localList; if (function.getLocals().getLocalsByName().containsKey(Name.of("_external$control"))) { externalRetControl = function.getLocals().getLocal(Name.of("_external$control")).getIndex(); externalRetValue = function.getLocals().getLocal(Name.of("_external$value")).getIndex(); localList = function.getLocals().getList(); } else { externalRetControl = Index.of(function.getLocals().getList().size()); externalRetValue = Index.of(function.getLocals().getList().size() + 1); localList = ImmutableList.<Local>builder().addAll(function.getLocals().getList()) .add(new Local(Name.of("_external$control"), externalRetControl, Type.I32)) .add(new Local(Name.of("_external$value"), externalRetValue, Type.I64)).build(); } Node node = maxNode; if (maxNode instanceof Switch) { Switch switchNode = (Switch) node; Optional<Switch.Entry> maxEntry = switchNode.getEntries().stream().max((l, r) -> Integer .compare(totalChildrenByNode.get(l.getBody()), totalChildrenByNode.get(r.getBody()))); node = maxEntry.get().getBody(); } Outlining.OutlinedFunction of = Outlining.outlineFunction(function, node, Name.of(function.getName().get() + "$outlined$" + num), externalRetControl, externalRetValue, loa, cfa, vta, parentsByNode, nodesByName); Function newFunc = new Function(function.getName(), function.getResult(), function.getArgCount(), new Locals(localList), Transforms.replaceNode(function.getBody(), node, of.getCallsite(), true)); return ImmutablePair.of(newFunc, of.getFunction()); }
From source file:ch.kanti_baden.pu_marc_14b.traffictimewaste.SORT_TYPE.java
private static Post[] sortPosts(Post[] posts) { Comparator<Post> comparator = null; switch (SORT_TYPE.values()[sortType]) { case NEWEST:// ww w . j ava2s.c om comparator = new Comparator<Post>() { @Override public int compare(Post post, Post t1) { return Long.compare(t1.postedAtMillis, post.postedAtMillis); } }; break; case OLDEST: comparator = new Comparator<Post>() { @Override public int compare(Post post, Post t1) { return Long.compare(post.postedAtMillis, t1.postedAtMillis); } }; break; case UPVOTES: comparator = new Comparator<Post>() { @Override public int compare(Post post, Post t1) { return Integer.compare(t1.votesUp - t1.votesDown, post.votesUp - post.votesDown); } }; break; case DOWNVOTES: comparator = new Comparator<Post>() { @Override public int compare(Post post, Post t1) { return Integer.compare(t1.votesDown - t1.votesUp, post.votesDown - post.votesUp); } }; break; } Arrays.sort(posts, comparator); return posts; }
From source file:serposcope.controllers.google.GoogleTargetController.java
public Result jsonVariation(Context context, @PathParam("targetId") Integer targetId, @Param("endDate") String endDateStr) { GoogleTarget target = getTarget(context, targetId); List<GoogleSearch> searches = context.getAttribute("searches", List.class); Group group = context.getAttribute("group", Group.class); final LocalDate endDate; try {//www . j a va2 s .c o m endDate = LocalDate.parse(endDateStr); } catch (Exception ex) { return Results.json().renderRaw("[[],[],[]]"); } Run lastRun = baseDB.run.findLast(group.getModule(), RunDB.STATUSES_DONE, endDate); List<TargetVariation> ranksUp = new ArrayList<>(); List<TargetVariation> ranksDown = new ArrayList<>(); List<TargetVariation> ranksSame = new ArrayList<>(); Map<Integer, GoogleSearch> searchesById = searches.stream() .collect(Collectors.toMap(GoogleSearch::getId, Function.identity())); List<GoogleRank> ranks = googleDB.rank.list(lastRun.getId(), group.getId(), target.getId()); for (GoogleRank rank : ranks) { GoogleSearch search = searchesById.get(rank.googleSearchId); if (search == null) { continue; } if (rank.diff > 0) { ranksDown.add(new TargetVariation(search, rank)); } else if (rank.diff < 0) { ranksUp.add(new TargetVariation(search, rank)); } else { ranksSame.add(new TargetVariation(search, rank)); } } Collections.sort(ranksUp, (TargetVariation o1, TargetVariation o2) -> Integer.compare(o1.rank.diff, o2.rank.diff)); Collections.sort(ranksDown, (TargetVariation o1, TargetVariation o2) -> -Integer.compare(o1.rank.diff, o2.rank.diff)); Collections.sort(ranksSame, (TargetVariation o1, TargetVariation o2) -> Integer.compare(o1.rank.rank, o2.rank.rank)); return Results.ok().json().render((Context context0, Result result) -> { PrintWriter writer = null; OutputStream os = null; try { String acceptEncoding = context0.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.contains("gzip")) { result.addHeader("Content-Encoding", "gzip"); } ResponseStreams response = context0.finalizeHeaders(result); os = response.getOutputStream(); if (acceptEncoding != null && acceptEncoding.contains("gzip")) { os = new GZIPOutputStream(os); } writer = new PrintWriter(os); writer.append("["); int id = 0; writer.append("["); for (int i = 0; i < ranksUp.size(); i++) { TargetVariation var = ranksUp.get(i); writer.append("{").append("\"id\":").append(Integer.toString(id++)).append(",\"search\":") .append(searchToJson(var.search)).append(",\"now\":") .append(Integer.toString(var.rank.rank)).append(",\"prv\":") .append(Integer.toString(var.rank.previousRank)).append(",\"diff\":") .append(Integer.toString(var.rank.diff)).append("}"); if (i != ranksUp.size() - 1) { writer.append(','); } } writer.append("],["); for (int i = 0; i < ranksDown.size(); i++) { TargetVariation var = ranksDown.get(i); writer.append("{").append("\"id\":").append(Integer.toString(id++)).append(",\"search\":") .append(searchToJson(var.search)).append(",\"now\":") .append(Integer.toString(var.rank.rank)).append(",\"prv\":") .append(Integer.toString(var.rank.previousRank)).append(",\"diff\":") .append(Integer.toString(var.rank.diff)).append("}"); if (i != ranksDown.size() - 1) { writer.append(','); } } writer.append("],["); for (int i = 0; i < ranksSame.size(); i++) { TargetVariation var = ranksSame.get(i); writer.append("{").append("\"id\":").append(Integer.toString(id++)).append(",\"search\":") .append(searchToJson(var.search)).append(",\"now\":") .append(Integer.toString(var.rank.rank)).append("}"); if (i != ranksSame.size() - 1) { writer.append(','); } } writer.append("]]"); } catch (Exception ex) { LOG.warn("HTTP error", ex); } finally { if (os != null) { try { writer.close(); os.close(); } catch (Exception ex) { } } } }); }
From source file:tds.student.performance.services.impl.ItemBankServiceImpl.java
/** * <p>/* w ww .j av a 2 s . c om*/ * NOTE: Caching is NOT implemented because the call to itemBankDao.getTestGrades() has a date check in the SQL that utilizes now() * </p> */ public List<String> getGrades() throws ReturnStatusException { List<TestGrade> testGrades = itemBankDao.getTestGrades(getTdsSettings().getClientName(), null, getTdsSettings().getSessionType()); Collections.<TestGrade>sort(testGrades, new Comparator<TestGrade>() { @Override public int compare(TestGrade o1, TestGrade o2) { int compare = Integer.compare(o1.getInteger(), o2.getInteger()); if (compare == 0) return o1.getText().compareTo(o2.getText()); return compare; } }); return (List<String>) ((CollectionUtils.collect(testGrades, new Transformer() { public Object transform(Object each) { return ((TestGrade) each).getText(); } }, new ArrayList<String>()))); }
From source file:burstcoin.observer.service.PoolService.java
private List<PoolBean> onRewardAssignmentLookup(Map<String, Set<String>> assignmentLookup) { // generatorRs -> foundBlocks Map<String, Integer> countLookup = new HashMap<>(); // generatorRS -> reward+fee Map<String, Long> rewardLookup = new HashMap<>(); for (Block block : blocks) { String generatorId = block.getGenerator(); Long reward = Long.valueOf(block.getBlockReward() + "00000000"); Long fee = Long.valueOf(block.getTotalFeeNQT()); // one id for all solo miners if (assignmentLookup.get(SOLO_KEY).contains(generatorId)) { generatorId = SOLO_KEY;//w w w. j ava 2 s .c o m } if (!countLookup.containsKey(generatorId)) { countLookup.put(generatorId, 1); rewardLookup.put(generatorId, reward + fee); } else { Integer count = countLookup.get(generatorId) + 1; countLookup.put(generatorId, count); Long rewards = rewardLookup.get(generatorId) + reward + fee; rewardLookup.put(generatorId, rewards); } } Map<String, Account> accountLookup = new HashMap<>(); for (String poolAccount : assignmentLookup.keySet()) { if (!SOLO_KEY.equals(poolAccount)) { Account account = getAccount(poolAccount); accountLookup.put(account.getAccount(), account); } } List<PoolBean> pools = new ArrayList<>(); // create models for (String poolAccountId : assignmentLookup.keySet()) { if (SOLO_KEY.equals(poolAccountId)) { pools.add(new PoolBean(poolAccountId, poolAccountId, "Solo-Miners", "", "0", assignmentLookup.get(poolAccountId).size(), countLookup.get(SOLO_KEY), assignmentLookup.get(poolAccountId).size(), formatAmountNQT(rewardLookup.get(SOLO_KEY)))); } else { Account account = accountLookup.get(poolAccountId); Integer minedBlocks = 0; int numberOfPoolBlockFinder = 0; Long earnedReward = 0L; for (String poolMinerAccountId : assignmentLookup.get(poolAccountId)) { if (countLookup.containsKey(poolMinerAccountId)) { numberOfPoolBlockFinder += 1; minedBlocks += countLookup.get(poolMinerAccountId); earnedReward += rewardLookup.get(poolMinerAccountId); } } pools.add(new PoolBean(poolAccountId, account.getAccountRS(), account.getName(), account.getDescription(), formatAmountNQT(Long.valueOf(account.getBalanceNQT())), assignmentLookup.get(poolAccountId).size(), minedBlocks, numberOfPoolBlockFinder, formatAmountNQT(earnedReward))); } } Collections.sort(pools, new Comparator<PoolBean>() { @Override public int compare(PoolBean o1, PoolBean o2) { return Integer.compare(o2.getFoundBlocks(), o1.getFoundBlocks()); } }); return pools; }
From source file:com.linkedin.pinot.routing.builder.KafkaLowLevelConsumerRoutingTableBuilder.java
@Override public List<ServerToSegmentSetMap> computeRoutingTableFromExternalView(String tableName, ExternalView externalView, List<InstanceConfig> instanceConfigList) { // We build the routing table based off the external view here. What we want to do is to make sure that we uphold // the guarantees clients expect (no duplicate records, eventual consistency) and spreading the load as equally as // possible between the servers. ///*from w w w . j a va 2 s. co m*/ // Each Kafka partition contains a fraction of the data, so we need to make sure that we query all partitions. // Because in certain unlikely degenerate scenarios, we can consume overlapping data until segments are flushed (at // which point the overlapping data is discarded during the reconciliation process with the controller), we need to // ensure that the query that is sent has only one partition in CONSUMING state in order to avoid duplicate records. // // Because we also want to want to spread the load as equally as possible between servers, we use a weighted random // replica selection that favors picking replicas with fewer segments assigned to them, thus having an approximately // equal distribution of load between servers. // // For example, given three replicas with 1, 2 and 3 segments assigned to each, the replica with one segment should // have a weight of 2, which is the maximum segment count minus the segment count for that replica. Thus, each // replica other than the replica(s) with the maximum segment count should have a chance of getting a segment // assigned to it. This corresponds to alternative three below: // // Alternative 1 (weight is sum of segment counts - segment count in that replica): // (6 - 1) = 5 -> P(0.4166) // (6 - 2) = 4 -> P(0.3333) // (6 - 3) = 3 -> P(0.2500) // // Alternative 2 (weight is max of segment counts - segment count in that replica + 1): // (3 - 1) + 1 = 3 -> P(0.5000) // (3 - 2) + 1 = 2 -> P(0.3333) // (3 - 3) + 1 = 1 -> P(0.1666) // // Alternative 3 (weight is max of segment counts - segment count in that replica): // (3 - 1) = 2 -> P(0.6666) // (3 - 2) = 1 -> P(0.3333) // (3 - 3) = 0 -> P(0.0000) // // Of those three weighting alternatives, the third one has the smallest standard deviation of the number of // segments assigned per replica, so it corresponds to the weighting strategy used for segment assignment. Empirical // testing shows that for 20 segments and three replicas, the standard deviation of each alternative is respectively // 2.112, 1.496 and 0.853. // // This algorithm works as follows: // 1. Gather all segments and group them by Kafka partition, sorted by sequence number // 2. Ensure that for each partition, we have at most one partition in consuming state // 3. Sort all the segments to be used during assignment in ascending order of replicas // 4. For each segment to be used during assignment, pick a random replica, weighted by the number of segments // assigned to each replica. // 1. Gather all segments and group them by Kafka partition, sorted by sequence number Map<String, SortedSet<SegmentName>> sortedSegmentsByKafkaPartition = new HashMap<String, SortedSet<SegmentName>>(); for (String helixPartitionName : externalView.getPartitionSet()) { // Ignore segments that are not low level consumer segments if (!SegmentNameBuilder.Realtime.isRealtimeV2Name(helixPartitionName)) { continue; } final LLCSegmentName segmentName = new LLCSegmentName(helixPartitionName); String kafkaPartitionName = segmentName.getPartitionRange(); SortedSet<SegmentName> segmentsForPartition = sortedSegmentsByKafkaPartition.get(kafkaPartitionName); // Create sorted set if necessary if (segmentsForPartition == null) { segmentsForPartition = new TreeSet<SegmentName>(); sortedSegmentsByKafkaPartition.put(kafkaPartitionName, segmentsForPartition); } segmentsForPartition.add(segmentName); } // 2. Ensure that for each Kafka partition, we have at most one Helix partition (Pinot segment) in consuming state Map<String, SegmentName> allowedSegmentInConsumingStateByKafkaPartition = new HashMap<String, SegmentName>(); for (String kafkaPartition : sortedSegmentsByKafkaPartition.keySet()) { SortedSet<SegmentName> sortedSegmentsForKafkaPartition = sortedSegmentsByKafkaPartition .get(kafkaPartition); SegmentName lastAllowedSegmentInConsumingState = null; for (SegmentName segmentName : sortedSegmentsForKafkaPartition) { Map<String, String> helixPartitionState = externalView.getStateMap(segmentName.getSegmentName()); boolean allInConsumingState = true; int replicasInConsumingState = 0; // Only keep the segment if all replicas have it in CONSUMING state for (String externalViewState : helixPartitionState.values()) { // Ignore ERROR state if (externalViewState.equalsIgnoreCase( CommonConstants.Helix.StateModel.RealtimeSegmentOnlineOfflineStateModel.ERROR)) { continue; } // Not all segments are in CONSUMING state, therefore don't consider the last segment assignable to CONSUMING // replicas if (externalViewState.equalsIgnoreCase( CommonConstants.Helix.StateModel.RealtimeSegmentOnlineOfflineStateModel.ONLINE)) { allInConsumingState = false; break; } // Otherwise count the replica as being in CONSUMING state if (externalViewState.equalsIgnoreCase( CommonConstants.Helix.StateModel.RealtimeSegmentOnlineOfflineStateModel.CONSUMING)) { replicasInConsumingState++; } } // If all replicas have this segment in consuming state (and not all of them are in ERROR state), then pick this // segment to be the last allowed segment to be in CONSUMING state if (allInConsumingState && 0 < replicasInConsumingState) { lastAllowedSegmentInConsumingState = segmentName; break; } } if (lastAllowedSegmentInConsumingState != null) { allowedSegmentInConsumingStateByKafkaPartition.put(kafkaPartition, lastAllowedSegmentInConsumingState); } } // 3. Sort all the segments to be used during assignment in ascending order of replicas // PriorityQueue throws IllegalArgumentException when given a size of zero int segmentCount = Math.max(externalView.getPartitionSet().size(), 1); PriorityQueue<Pair<String, Set<String>>> segmentToReplicaSetQueue = new PriorityQueue<Pair<String, Set<String>>>( segmentCount, new Comparator<Pair<String, Set<String>>>() { @Override public int compare(Pair<String, Set<String>> firstPair, Pair<String, Set<String>> secondPair) { return Integer.compare(firstPair.getRight().size(), secondPair.getRight().size()); } }); RoutingTableInstancePruner instancePruner = new RoutingTableInstancePruner(instanceConfigList); for (Map.Entry<String, SortedSet<SegmentName>> entry : sortedSegmentsByKafkaPartition.entrySet()) { String kafkaPartition = entry.getKey(); SortedSet<SegmentName> segmentNames = entry.getValue(); // The only segment name which is allowed to be in CONSUMING state or null SegmentName validConsumingSegment = allowedSegmentInConsumingStateByKafkaPartition.get(kafkaPartition); for (SegmentName segmentName : segmentNames) { Set<String> validReplicas = new HashSet<String>(); Map<String, String> externalViewState = externalView.getStateMap(segmentName.getSegmentName()); for (Map.Entry<String, String> instanceAndStateEntry : externalViewState.entrySet()) { String instance = instanceAndStateEntry.getKey(); String state = instanceAndStateEntry.getValue(); // Skip pruned replicas (shutting down or otherwise disabled) if (instancePruner.isInactive(instance)) { continue; } // Replicas in ONLINE state are always allowed if (state.equalsIgnoreCase( CommonConstants.Helix.StateModel.RealtimeSegmentOnlineOfflineStateModel.ONLINE)) { validReplicas.add(instance); continue; } // Replicas in CONSUMING state are only allowed on the last segment if (state.equalsIgnoreCase( CommonConstants.Helix.StateModel.RealtimeSegmentOnlineOfflineStateModel.CONSUMING) && segmentName.equals(validConsumingSegment)) { validReplicas.add(instance); } } segmentToReplicaSetQueue .add(new ImmutablePair<String, Set<String>>(segmentName.getSegmentName(), validReplicas)); // If this segment is the segment allowed in CONSUMING state, don't process segments after it in that Kafka // partition if (segmentName.equals(validConsumingSegment)) { break; } } } // 4. For each segment to be used during assignment, pick a random replica, weighted by the number of segments // assigned to each replica. List<ServerToSegmentSetMap> routingTables = new ArrayList<ServerToSegmentSetMap>(routingTableCount); for (int i = 0; i < routingTableCount; ++i) { Map<String, Set<String>> instanceToSegmentSetMap = new HashMap<String, Set<String>>(); PriorityQueue<Pair<String, Set<String>>> segmentToReplicaSetQueueCopy = new PriorityQueue<Pair<String, Set<String>>>( segmentToReplicaSetQueue); while (!segmentToReplicaSetQueueCopy.isEmpty()) { Pair<String, Set<String>> segmentAndValidReplicaSet = segmentToReplicaSetQueueCopy.poll(); String segment = segmentAndValidReplicaSet.getKey(); Set<String> validReplicaSet = segmentAndValidReplicaSet.getValue(); String replica = pickWeightedRandomReplica(validReplicaSet, instanceToSegmentSetMap); if (replica != null) { Set<String> segmentsForInstance = instanceToSegmentSetMap.get(replica); if (segmentsForInstance == null) { segmentsForInstance = new HashSet<String>(); instanceToSegmentSetMap.put(replica, segmentsForInstance); } segmentsForInstance.add(segment); } } routingTables.add(new ServerToSegmentSetMap(instanceToSegmentSetMap)); } return routingTables; }
From source file:contestTabulation.Setup.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity contestInfo = Retrieve.contestInfo(); GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory) .setTransport(httpTransport) .setClientSecrets((String) contestInfo.getProperty("OAuth2ClientId"), (String) contestInfo.getProperty("OAuth2ClientSecret")) .build().setFromTokenResponse(new JacksonFactory().fromString( ((Text) contestInfo.getProperty("OAuth2Token")).getValue(), GoogleTokenResponse.class)); String docName = null, docLevel = null; for (Level level : Level.values()) { docName = req.getParameter("doc" + level.getName()); if (docName != null) { docLevel = level.toString(); break; }//from w w w. j a v a2 s . c o m } if (docLevel == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Spreadsheet creation request must have paramater document name parameter set"); return; } Query query = new Query("registration") .setFilter(new FilterPredicate("schoolLevel", FilterOperator.EQUAL, docLevel)) .addSort("schoolName", SortDirection.ASCENDING); List<Entity> registrations = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults()); Map<String, List<JSONObject>> studentData = new HashMap<String, List<JSONObject>>(); for (Entity registration : registrations) { String regSchoolName = ((String) registration.getProperty("schoolName")).trim(); String regStudentDataJSON = unescapeHtml4(((Text) registration.getProperty("studentData")).getValue()); JSONArray regStudentData = null; try { regStudentData = new JSONArray(regStudentDataJSON); } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } for (int i = 0; i < regStudentData.length(); i++) { if (!studentData.containsKey(regSchoolName)) { studentData.put(regSchoolName, new ArrayList<JSONObject>()); } try { studentData.get(regSchoolName).add(regStudentData.getJSONObject(i)); } catch (JSONException e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); e.printStackTrace(); return; } } } for (List<JSONObject> students : studentData.values()) { Collections.sort(students, new Comparator<JSONObject>() { @Override public int compare(JSONObject a, JSONObject b) { try { return a.getString("name").compareTo(b.getString("name")); } catch (JSONException e) { e.printStackTrace(); return 0; } } }); } Workbook workbook = new XSSFWorkbook(); XSSFCellStyle boldStyle = (XSSFCellStyle) workbook.createCellStyle(); Font boldFont = workbook.createFont(); boldFont.setBoldweight(Font.BOLDWEIGHT_BOLD); boldStyle.setFont(boldFont); Map<Subject, XSSFCellStyle> subjectCellStyles = new HashMap<Subject, XSSFCellStyle>(); for (Subject subject : Subject.values()) { final double ALPHA = .144; String colorStr = (String) contestInfo.getProperty("color" + subject.getName()); byte[] backgroundColor = new byte[] { Integer.valueOf(colorStr.substring(1, 3), 16).byteValue(), Integer.valueOf(colorStr.substring(3, 5), 16).byteValue(), Integer.valueOf(colorStr.substring(5, 7), 16).byteValue() }; // http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending byte[] borderColor = new byte[] { (byte) ((backgroundColor[0] & 0xff) * (1 - ALPHA)), (byte) ((backgroundColor[1] & 0xff) * (1 - ALPHA)), (byte) ((backgroundColor[2] & 0xff) * (1 - ALPHA)) }; XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle(); style.setFillBackgroundColor(new XSSFColor(backgroundColor)); style.setFillPattern(CellStyle.ALIGN_FILL); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(new XSSFColor(borderColor)); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(new XSSFColor(borderColor)); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(new XSSFColor(borderColor)); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(new XSSFColor(borderColor)); subjectCellStyles.put(subject, style); } Entry<String, List<JSONObject>>[] studentDataEntries = studentData.entrySet().toArray(new Entry[] {}); Arrays.sort(studentDataEntries, Collections.reverseOrder(new Comparator<Entry<String, List<JSONObject>>>() { @Override public int compare(Entry<String, List<JSONObject>> arg0, Entry<String, List<JSONObject>> arg1) { return Integer.compare(arg0.getValue().size(), arg1.getValue().size()); } })); for (Entry<String, List<JSONObject>> studentDataEntry : studentDataEntries) { Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(studentDataEntry.getKey())); Row row = sheet.createRow((short) 0); String[] columnNames = { "Name", "Grade", "N", "C", "M", "S" }; for (int i = 0; i < columnNames.length; i++) { String columnName = columnNames[i]; Cell cell = row.createCell(i); cell.setCellValue(columnName); cell.setCellStyle(boldStyle); CellUtil.setAlignment(cell, workbook, CellStyle.ALIGN_CENTER); } int longestNameLength = 7; int rowNum = 1; for (JSONObject student : studentDataEntry.getValue()) { try { row = sheet.createRow((short) rowNum); row.createCell(0).setCellValue(student.getString("name")); row.createCell(1).setCellValue(student.getInt("grade")); for (Subject subject : Subject.values()) { String value = student.getBoolean(subject.toString()) ? "" : "X"; Cell cell = row.createCell(Arrays.asList(columnNames).indexOf(subject.toString())); cell.setCellValue(value); cell.setCellStyle(subjectCellStyles.get(subject)); } if (student.getString("name").length() > longestNameLength) { longestNameLength = student.getString("name").length(); } rowNum++; } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } sheet.createFreezePane(0, 1, 0, 1); // sheet.autoSizeColumn((short) 0); Not supported by App Engine sheet.setColumnWidth((short) 0, (int) (256 * longestNameLength * 1.1)); } Drive drive = new Drive.Builder(httpTransport, jsonFactory, credential) .setApplicationName("contestTabulation").build(); File body = new File(); body.setTitle(docName); body.setMimeType("application/vnd.google-apps.spreadsheet"); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); workbook.write(outStream); ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray()); InputStreamContent content = new InputStreamContent( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", inStream); drive.files().insert(body, content).execute(); workbook.close(); }
From source file:net.sf.maltcms.chromaui.chromatogram1Dviewer.ui.panel.Chromatogram1DViewPanel.java
public void setPlot(final XYPlot plot) { removeAxisListener();//from w w w .j a va 2s . c om ADataset1D<?, IScan> dataset = null; if (plot.getDataset() instanceof ADataset1D) { dataset = (ADataset1D<?, IScan>) plot.getDataset(); } else { throw new IllegalArgumentException("Requires a plot with ADataset1D!"); } this.plot = plot; if (selectionOverlay != null) { content.remove(selectionOverlay); selectionOverlay = null; } if (selectionOverlay == null) { selectionOverlay = new SelectionOverlay(Color.BLUE, Color.RED, 1.75f, 1.75f, 0.66f); chartPanel.addOverlay(selectionOverlay); selectionOverlay.addChangeListener(chartPanel); content.add(selectionOverlay); } else { for (ISelection selection : selectionOverlay.getMouseClickSelection()) { selection.setDataset(dataset); } ISelection selection = selectionOverlay.getMouseHoverSelection(); if (selection != null) { selection.setDataset(dataset); } } if (selectionHandler == null) { selectionHandler = new InstanceContentSelectionHandler(this.content, selectionOverlay, InstanceContentSelectionHandler.Mode.ON_CLICK, dataset, 1); } else { selectionHandler.setDataset(dataset); } if (mouseSelectionHandler == null) { mouseSelectionHandler = new XYMouseSelectionHandler<>(dataset); mouseSelectionHandler.addSelectionChangeListener(selectionOverlay); mouseSelectionHandler.addSelectionChangeListener(selectionHandler); chartPanel.addChartMouseListener(mouseSelectionHandler); } else { mouseSelectionHandler.setDataset(dataset); } AxisChangeListener listener = selectionOverlay; ValueAxis domain = this.plot.getDomainAxis(); ValueAxis range = this.plot.getRangeAxis(); if (domain != null) { domain.addChangeListener(listener); } if (range != null) { range.addChangeListener(listener); } this.plot.setNoDataMessage("Loading Data..."); this.plot.setDomainPannable(true); this.plot.setRangePannable(true); chart = new JFreeChart(this.plot); chartPanel.setChart(chart); XYItemRenderer r = this.plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { ((XYLineAndShapeRenderer) r).setDrawSeriesLineAsPath(true); ((XYLineAndShapeRenderer) r).setBaseShapesVisible(false); ((XYLineAndShapeRenderer) r).setBaseShapesFilled(true); } else if (r instanceof XYAreaRenderer) { ((XYAreaRenderer) r).setOutline(true); ((XYAreaRenderer) r).setBaseCreateEntities(true, false); } else if (r instanceof EntityAwareSamplingXYLineRenderer) { ((EntityAwareSamplingXYLineRenderer) r).setBaseCreateEntities(true, false); } ChartCustomizer.setSeriesColors(this.plot, 0.8f); ChartCustomizer.setSeriesStrokes(this.plot, 2.0f); dmkl = new DomainMarkerKeyListener(this.plot); dmkl.setPlot(this.plot); chartPanel.addKeyListener(dmkl); addAxisListener(); //add available chart overlays ArrayList<? extends Overlay> overlays = new ArrayList<>(getLookup().lookupAll(Overlay.class)); Collections.sort(overlays, new Comparator<Overlay>() { @Override public int compare(Overlay o1, Overlay o2) { if (o1 instanceof ChartOverlay && o2 instanceof ChartOverlay) { ChartOverlay co1 = (ChartOverlay) o1; ChartOverlay co2 = (ChartOverlay) o2; return Integer.compare(co1.getLayerPosition(), co2.getLayerPosition()); } else { return 0; } } }); for (Overlay overlay : overlays) { if (!(overlay instanceof SelectionOverlay)) { chartPanel.removeOverlay(overlay); if (overlay instanceof AxisChangeListener) { AxisChangeListener axisChangeListener = (AxisChangeListener) overlay; if (domain != null) { domain.addChangeListener(axisChangeListener); } if (range != null) { range.addChangeListener(axisChangeListener); } } if (overlay instanceof ISelectionChangeListener) { ISelectionChangeListener isl = (ISelectionChangeListener) overlay; mouseSelectionHandler.addSelectionChangeListener(isl); mouseSelectionHandler.addSelectionChangeListener(selectionHandler); selectionOverlay.addChangeListener(chartPanel); } chartPanel.addOverlay(overlay); overlay.addChangeListener(chartPanel); } } //add selection overlay last chartPanel.removeOverlay(selectionOverlay); chartPanel.addOverlay(selectionOverlay); if (range != null) { range.setAutoRange(true); range.setDefaultAutoRange(DatasetUtilities.findRangeBounds(dataset)); } if (domain != null) { domain.setAutoRange(true); domain.setDefaultAutoRange(DatasetUtilities.findDomainBounds(dataset)); } }