answer
stringlengths 17
10.2M
|
|---|
package com.toomasr.sgf4j.parser;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Computes the visual depth for the game nodes. The visual
* depth designates as how deep in the tree should the line be
* shown if a GUI is being used. I should move this helper to
* sgf4j-gui project but haven't done it yet.
*/
public class VisualDepthHelper {
private List<List<Integer>> depthMatrix;
/*
* We'll start iterating over the nodes from last to first and
* calculate how "deep" should they be displayed in the tree. The
* mainline is on depth 0.
*
* @param variationDepth depth of the variation for the first level child
* of the line of play.
*/
public void calculateVisualDepth(GameNode lastNode, int variationDepth) {
// if there are no moves, for example we are just
// looking at a problem then we can skip calculating
// the visual depth
if (lastNode == null) {
return;
}
// a XyZ matrix that we'll fill with 1s and 0s based
// on whether a square is occupied or not
List<List<Integer>> depthMatrix = new ArrayList<>();
initializeMainLine(lastNode, depthMatrix);
GameNode activeNode = lastNode;
do {
if (activeNode.hasChildren()) {
for (Iterator<GameNode> ite = activeNode.getChildren().iterator(); ite.hasNext();) {
// the do/while iterates over the main line that has depth 0
// all other branches have to be at least depth 1
variationDepth = variationDepth + 1;
calculateVisualDepthFor(ite.next(), depthMatrix, 1, variationDepth);
}
}
}
while ((activeNode = activeNode.getPrevNode()) != null);
this.depthMatrix = depthMatrix;
}
private void calculateVisualDepthFor(GameNode node, List<List<Integer>> depthMatrix, int minDepth, int variationDepth) {
int depth = findVisualDepthForNode(node, depthMatrix, minDepth, variationDepth);
GameNode lastNodeInLine = setVisualDepthForLine(node, depth);
GameNode activeNode = lastNodeInLine;
do {
if (activeNode.hasChildren()) {
for (Iterator<GameNode> ite = activeNode.getChildren().iterator(); ite.hasNext();) {
calculateVisualDepthFor(ite.next(), depthMatrix, depth + 1, variationDepth);
}
}
if (activeNode.equals(node)) {
break;
}
}
while ((activeNode = activeNode.getPrevNode()) != null);
}
private void initializeMainLine(GameNode lastNode, List<List<Integer>> depthMatrix) {
// initialize the first line with 0s
List<Integer> firstLine = new ArrayList<>();
for (int i = 0; i <= lastNode.getMoveNo(); i++) {
firstLine.add(i, 0);
}
depthMatrix.add(0, firstLine);
// initialize the first line actual moves with 1s
GameNode node = lastNode;
do {
if (node.isMove()) {
firstLine.set(node.getMoveNo(), 1);
// main line will be at depth 0
node.setVisualDepth(0);
}
}
while ((node = node.getPrevNode()) != null);
}
protected GameNode setVisualDepthForLine(GameNode child, int depth) {
GameNode node = child;
GameNode rtrn = child;
do {
node.setVisualDepth(depth);
rtrn = node;
}
while ((node = node.getNextNode()) != null);
return rtrn;
}
protected int findVisualDepthForNode(GameNode node, List<List<Integer>> depthMatrix, int minDepth, int variationDepth) {
int length = findLengthOfLine(node);
int depthDelta = minDepth;
do {
// init the matrix at this depth if not yet done
if (depthMatrix.size() <= depthDelta) {
for (int i = depthMatrix.size(); i <= depthDelta; i++) {
depthMatrix.add(i, new ArrayList<Integer>());
}
}
boolean available = isAvailableForLineOfPlay(node, length, depthMatrix, depthDelta, variationDepth);
if (available) {
bookForLineOfPlay(node, length, depthMatrix, depthDelta, variationDepth);
break;
}
depthDelta++;
}
while (true);
return depthDelta;
}
/*
* Iterates over the depthMatrix and marks all the needed cells as booked (the number 1).
*/
protected void bookForLineOfPlay(GameNode node, int length, List<List<Integer>> depthMatrix, int listIndex, int variationDepth) {
List<Integer> levelList = depthMatrix.get(listIndex);
int start = 0;
if (node.getMoveNo() > 0) {
start = node.getMoveNo() - 1;
}
// book the line of play (horizontal line)
for (int i = start; i < (node.getMoveNo() + length); i++) {
levelList.set(i, 1);
}
// book the "glue" pieces (vertical lines for the connection lines)
for (int i = 1; i < listIndex; i++) {
List<Integer> tmpLevelList = depthMatrix.get(i);
expandListIfNeeded(tmpLevelList, start);
tmpLevelList.set(start, 1);
}
}
private void expandListIfNeeded(List<Integer> tmpLevelList, int upperBound) {
if (tmpLevelList.size() > upperBound) {
return;
}
for (int i = tmpLevelList.size(); i <= upperBound; i++) {
tmpLevelList.add(i, 0);
}
}
/*
* Iterates over the depthMatrix and checks whether we can put the variation on this particular line.
*
* Each variation needs room for the actual moves and also one spot for the glue piece (the line designating
* the parent move). If the variation is quite deep then it will need a glue code piece for each row.
*
* This method will analyse the matrix for the availability for these. If found they can be "booked"
* with the bookForLineOfPlay(). If not found we can just look a level deeper.
*/
protected boolean isAvailableForLineOfPlay(GameNode node, int length, List<List<Integer>> depthMatrix, int listIndex, int variationDepth) {
// if the marker row is not initialized yet then lets fill with 0s
List<Integer> levelList = depthMatrix.get(listIndex);
if (levelList.size() <= node.getMoveNo()) {
for (int i = levelList.size(); i <= node.getMoveNo() + length; i++) {
levelList.add(i, 0);
}
}
// we'll start the search one move earlier as we also
// want to show to "glue stone"
Integer marker = 0;
if (node.getMoveNo() > 1) {
marker = levelList.get(node.getMoveNo() - 1);
}
// we'll look at the array and make sure nobody has booked anything yet
for (int i = marker; i < node.getMoveNo() + length; i++) {
Integer localMarker = levelList.get(i);
if (localMarker == 1) {
return false;
}
}
// now lets look at whether there is room for the glue piece
// the glue piece should run up to the depth of the
// variation it came from
for (int i = variationDepth; i < listIndex; i++) {
List<Integer> tmpLevelList = depthMatrix.get(i);
if (tmpLevelList.get(marker) == 1)
return false;
}
return true;
}
/*
* Helper to print out the matrix for debugging purposes.
*/
public void printDepthMatrix() {
for (Iterator<List<Integer>> ite = depthMatrix.iterator(); ite.hasNext();) {
List<Integer> list = ite.next();
System.out.println(list);
}
}
/**
* Returns the length of this game line. This is the length with
* no branch taken into account except the main line for this branch.
*
* @param node
* @return no of moves in the main line from this node
*/
protected int findLengthOfLine(final GameNode node) {
GameNode tmpNode = node;
int i = 0;
do {
i++;
}
while ((tmpNode = tmpNode.getNextNode()) != null);
return i;
}
}
|
package de.berlin.hu.uima.ae.normalizer;
import de.berlin.hu.chemspot.ChemSpotConfiguration;
import de.berlin.hu.chemspot.ChemSpotConfiguration.Component;
import de.berlin.hu.util.Constants;
import de.berlin.hu.util.Constants.ChemicalID;
import groovyNormalizerBeans.NameNormalizer;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
import org.u_compare.shared.semantic.NamedEntity;
import org.uimafit.util.JCasUtil;
import uk.ac.cam.ch.wwmm.opsin.NameToInchi;
import uk.ac.cam.ch.wwmm.opsin.NameToStructureException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Normalizer extends JCasAnnotator_ImplBase {
private static Map<String,String[]> ids = new HashMap<String,String[]>();
private static Map<String,String[]> normalizedIds = new HashMap<String,String[]>();
private NameToInchi nameToInChi;
private static final String PATH_TO_IDS = "PathToIDs";
private NameNormalizer nameNormalizer = null;
private Map<String, String> fdaIds = null;
private Map<String, String> fdaDates = null;
private void loadFDAData(String pathToFile) throws IOException {
fdaIds = new HashMap<String, String>();
fdaDates = new HashMap<String, String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(pathToFile)));
String line = null;
while((line = reader.readLine()) != null) {
String[] data = line.split("\t");
String id = data[0];
String drug = data[1];
String date = data[2];
fdaIds.put(drug, id);
fdaDates.put(id, date);
}
reader.close();
}
private void writePrefixSuffixLists() throws IOException {
int prefixLength = 3;
int suffixLength = 3;
Map<String, Integer> prefixes = new HashMap<String, Integer>();
Map<String, Integer> suffixes = new HashMap<String, Integer>();
System.out.println("Writing prefix and suffix lists...");
for (String chemical : ids.keySet()) {
if (chemical.startsWith("(")) chemical = chemical.substring(1, chemical.length());
if (chemical.endsWith(")")) chemical = chemical.substring(0, chemical.length() - 1);
String prefix = chemical.length() >= prefixLength ? chemical.substring(0, prefixLength) : null;
String suffix = chemical.length() >= suffixLength ? chemical.substring(chemical.length() - suffixLength, chemical.length()) : null;
if (prefix != null) {
if (!prefixes.containsKey(prefix)) {
prefixes.put(prefix, 0);
}
prefixes.put(prefix, prefixes.get(prefix)+1);
}
if (suffix != null) {
if (!suffixes.containsKey(suffix)) {
suffixes.put(suffix, 0);
}
suffixes.put(suffix, suffixes.get(suffix)+1);
}
}
List<String> prefixList = new ArrayList<String>(prefixes.keySet());
List<String> suffixList = new ArrayList<String>(suffixes.keySet());
class IntegerMapComparator implements Comparator<String> {
private Map<String, Integer> map = null;
public IntegerMapComparator(Map<String, Integer> map) {
this.map = map;
}
public int compare(String o1, String o2) {
return map.get(o1) - map.get(o2);
}
};
Collections.sort(prefixList, Collections.reverseOrder(new IntegerMapComparator(prefixes)));
Collections.sort(suffixList, Collections.reverseOrder(new IntegerMapComparator(suffixes)));
BufferedWriter writer = new BufferedWriter(new FileWriter("prefixes.txt"));
for (String prefix : prefixList) {
writer.write(String.format("%s\t%d%n", prefix, prefixes.get(prefix)));
}
writer.close();
writer = new BufferedWriter(new FileWriter("suffixes.txt"));
for (String suffix : suffixList) {
writer.write(String.format("%s\t%d%n", suffix, suffixes.get(suffix)));
}
writer.close();
writer = new BufferedWriter(new FileWriter("suffixes-filtered.txt"));
for (String suffix : suffixList) {
if (suffix.matches(String.format("[a-z]{%d}", suffixLength))) {
writer.write(String.format("%s\t%d%n", suffix, suffixes.get(suffix)));
}
}
writer.close();
System.out.println("Done.");
}
public static Map<String, String[]> readIdsFile(InputStream in) throws IOException {
Map<String, String[]> result = new HashMap<String, String[]>();
Map<String, List<String>> normalizedChems = new HashMap<String, List<String>>();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
while (line != null) {
int splitAt = line.indexOf('\t');
String chem = line.substring(0, splitAt).toLowerCase();
String identifiers = line.substring(splitAt+1);
result.put(chem, identifiers.split("\t"));
/*nameNormalizer.setName(chem);
String normalizedChem = nameNormalizer.getNormName();
if (!normalizedChems.containsKey(normalizedChem)) {
normalizedChems.put(normalizedChem, new ArrayList<String>());
} else {
String equal = Arrays.equals(identifiers.split("\t"), ids.get(normalizedChem)) ? "equal" : "not equal";
System.out.println("conflict for '" + chem + "' and " + normalizedChems.get(normalizedChem) + ". Ids are " + equal + ".");
if ("not equal".equals(equal)) {
System.out.println(" " + identifiers.replaceAll("\t", ", ") + " vs." + Arrays.toString(ids.get(normalizedChem)).replace('[', ' ').replace(']', ' '));
}
}
normalizedChems.get(normalizedChem).add(chem);
result.put(normalizedChem, identifiers.split("\t"));*/
line = reader.readLine();
}
return result;
}
public static Map<String, String[]> loadIdsFromFile(String file) throws IOException {
Map<String, String[]> ids = new HashMap<String, String[]>();
if (file.endsWith(".zip")) {
ZipFile zipFile = new ZipFile(file);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
InputStream in = zipFile.getInputStream(entry);
ids.putAll(readIdsFile(in));
in.close();
}
} else {
InputStream in = new FileInputStream(file);
ids.putAll(readIdsFile(in));
in.close();
}
return ids;
}
public static void writeIDs(String pathToFile, Map<String, String[]> ids) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(pathToFile));
for (String chem : ids.keySet()) {
String[] chemIds = ids.get(chem);
String idString = "";
for (ChemicalID type : ChemicalID.values()) {
String id = "";
if (type.ordinal() < chemIds.length) {
id = chemIds[type.ordinal()];
if (id == null) id = "";
}
idString += "\t" + id;
}
writer.write(chem + idString);
writer.newLine();
}
writer.close();
}
public static Map<String, String[]> getIds() {
return ids;
}
@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
super.initialize(aContext);
System.out.println("Initializing normalizer...");
try {
loadFDAData("/resources/fda/approved_drugs.tsv");
} catch (IOException e) {
e.printStackTrace();
}
if (ChemSpotConfiguration.useComponent(Component.CHEMHITS)) {
System.out.println(" Initializing ChemHits...");
nameNormalizer = new NameNormalizer();
}
String idsFile = aContext.getConfigParameterValue(PATH_TO_IDS).toString();
try {
if (idsFile.endsWith(".zip")) {
ZipFile zipFile = new ZipFile(idsFile);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
InputStream in = zipFile.getInputStream(entry);
if (entry.getName().contains("normalized")) {
if (ChemSpotConfiguration.useComponent(Component.CHEMHITS)) {
System.out.print(" Loading ChemHits normalized ids... ");
normalizedIds.putAll(readIdsFile(in));
System.out.println("Done.");
}
} else if (ChemSpotConfiguration.useComponent(Component.NORMALIZER)) {
System.out.print(" Loading ids... ");
ids.putAll(readIdsFile(in));
System.out.println("Done.");
}
in.close();
}
} else {
ids = loadIdsFromFile(idsFile);
}
} catch (IOException e) {
throw new ResourceInitializationException(e);
}
if (ChemSpotConfiguration.useComponent(Component.OPSIN)) {
try {
//initializing OPSIN
nameToInChi = new NameToInchi();
} catch (NameToStructureException e) {
e.printStackTrace();
}
}
/*try {
writePrefixSuffixLists();
} catch (IOException e) {
e.printStackTrace();
}*/
}
private String[] getBestMatch(String chemical, Map<String, String[]> ids) {
String[] result = null;
List<String> substringMatches = new ArrayList<String>();
String bestMatch = null;
float bestScore = 0;
int i = 0;
for (String key : ids.keySet()) {
if (Math.abs(chemical.length() - key.length()) < 3){
}
float score = StringComparator.diceCoefficient(StringComparator.getNGrams(chemical, 2), StringComparator.getNGrams(key, 2));
if (score > bestScore) {
bestMatch = key;
bestScore = score;
}
if (chemical.contains(key)) {
substringMatches.add(key);
}
if (++i % 10000 == 0) {
System.out.print(".");
}
}
if (bestScore > 0.7) {
result = ids.get(bestMatch);
} else if (!substringMatches.isEmpty()) {
Comparator<String> comparator = new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
};
Collections.sort(substringMatches, Collections.reverseOrder(comparator));
String bestSubstringMatch = substringMatches.get(0);
if (bestSubstringMatch.length() > 3) {
result = ids.get(bestMatch);
}
}
return result;
}
private static int chemHitsDifferent = 0;
private static int chemHitsEqual = 0;
private static int chemHitsIdFound = 0;
private static int chemHitsIdFoundExclusively = 0;
private static int chemHitsIdNotFoundExclusively = 0;
private static int chemHitsIdFoundBoth = 0;
private static int chemHitsIdNotFound = 0;
private static int chemHitsdifferentIdFound = 0;
@Override
public void process(JCas jCas) throws AnalysisEngineProcessException {
Iterator<NamedEntity> entities = JCasUtil.iterator(jCas, NamedEntity.class);
int nE = 0;
int nN = 0;
int fda = 0;
List<NamedEntity> entiti = new ArrayList<NamedEntity>();
while (entities.hasNext()) {
NamedEntity entity = entities.next();
String inchi = nameToInChi != null ? nameToInChi.parseToStdInchi(entity.getCoveredText()) : null;
if (Constants.GOLDSTANDARD.equals(entity.getSource())) {
nE++;
String[] normalized = ids.get(entity.getCoveredText().toLowerCase());
if (nameNormalizer != null) {
nameNormalizer.setName(entity.getCoveredText());
String chemHitsnormalizedString = nameNormalizer.getNormName();
if (entity.getCoveredText().replace("-", " ").equalsIgnoreCase(chemHitsnormalizedString.replace("-", " "))) {
chemHitsEqual++;
} else {
chemHitsDifferent++;
}
//System.out.println(entity.getCoveredText() + " - > " + chemHitsnormalizedString);
String[] chemhitsNormalized = normalizedIds.get(chemHitsnormalizedString);
if (normalized != null && (normalized[Constants.ChemicalID.CHEB.ordinal()] == null || normalized[Constants.ChemicalID.CHEB.ordinal()].isEmpty())) {
normalized = null;
}
if (chemhitsNormalized != null && (chemhitsNormalized[Constants.ChemicalID.CHEB.ordinal()] == null || chemhitsNormalized[Constants.ChemicalID.CHEB.ordinal()].isEmpty())) {
chemhitsNormalized = null;
}
if (normalized == null && chemhitsNormalized == null) {
chemHitsIdNotFound++;
} else if (normalized == null && chemhitsNormalized != null) {
chemHitsIdFoundExclusively++;
} else if (normalized != null && chemhitsNormalized == null) {
chemHitsIdNotFoundExclusively++;
} else if (normalized != null && chemhitsNormalized != null) {
chemHitsIdFoundBoth++;
}
if (normalized != null && chemhitsNormalized != null) {
if (chemhitsNormalized.length != normalized.length) {
chemHitsdifferentIdFound++;
} else {
for (int i = 0; i < chemhitsNormalized.length; i++) {
if (
(normalized[i] != null && !normalized[i].equals(chemhitsNormalized[i]))
|| (chemhitsNormalized[i] != null && !chemhitsNormalized[i].equals(normalized[i]))
) {
chemHitsdifferentIdFound++;
break;
}
}
}
}
if (normalized == null && chemhitsNormalized != null) {
normalized = chemhitsNormalized;
System.out.println("replacing id with the one found by ChemHits: " + entity.getCoveredText() + " -> " + chemHitsnormalizedString);
}
}
/*if (normalized == null) {
normalized = getBestMatch(entity.getCoveredText().toLowerCase(), ids);
}*/
//if entity is contained in dictionary
if (normalized != null) {
//FIXME: use a UIMA field instead of a String here
if (normalized.length > ChemicalID.INCH.ordinal()) {
if (normalized[ChemicalID.INCH.ordinal()].isEmpty() && inchi != null) normalized[ChemicalID.INCH.ordinal()] = inchi;
} else {
if (inchi != null) {
String[] normalizedTemp = Arrays.copyOf(normalized, ChemicalID.INCH.ordinal() + 1);
normalizedTemp[ChemicalID.INCH.ordinal()] = inchi;
normalized = normalizedTemp;
}
}
nN++;
} else {
if (inchi != null) {
String[] normalizedTemp = new String[ChemicalID.INCH.ordinal() + 1];
normalizedTemp[ChemicalID.INCH.ordinal()] = inchi;
normalized = normalizedTemp;
nN++;
}
}
if (fdaIds != null && fdaIds.containsKey(entity.getCoveredText().toLowerCase())) {
fda++;
//System.out.println(entity.getCoveredText().toLowerCase());
if (normalized == null) normalized = new String[Constants.ChemicalID.values().length];
normalized = Arrays.copyOf(normalized, Constants.ChemicalID.values().length);
normalized[ChemicalID.FDA.ordinal()] = fdaIds.get(entity.getCoveredText().toLowerCase());
if (fdaDates.containsKey(fdaIds.get(entity.getCoveredText().toLowerCase()))) {
normalized[ChemicalID.FDA_DATE.ordinal()] = fdaDates.get(fdaIds.get(entity.getCoveredText().toLowerCase()));
}
}
NamedEntity e = (NamedEntity)entity.clone();
e.setId(Arrays.toString(normalized));
e.setSource("Test");
entiti.add(e);
}
}
for (NamedEntity e : entiti) {
e.addToIndexes();
}
if (nameNormalizer != null) printChemHitsStatistic();
//System.out.println(fda);
//System.out.println(nN + "/" + nE);
}
private void printChemHitsStatistic() {
System.out.printf("%nChemHits statistics:%n identifed %d new terms after normalization (of %d / %.2f %%)%n", chemHitsDifferent, chemHitsDifferent + chemHitsEqual, chemHitsDifferent + chemHitsEqual > 0 ? (float)chemHitsDifferent / (float)(chemHitsDifferent + chemHitsEqual) * 100 : 0);
System.out.printf(" found only by ChemHits: %d, only by ChemSpot: %d, by neither: %d, by both: %d (%d of those differently / %.2f %%)%n%n", chemHitsIdFoundExclusively, chemHitsIdNotFoundExclusively, chemHitsIdNotFound, chemHitsIdFoundBoth , chemHitsdifferentIdFound, chemHitsIdFoundBoth > 0 ? (float)chemHitsdifferentIdFound / (float)chemHitsIdFoundBoth * 100 : 0);
}
}
|
package de.codescape.bitvunit.ruleset;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import de.codescape.bitvunit.rule.Rule;
import de.codescape.bitvunit.rule.Violation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BasicRuleSet implements RuleSet {
private List<Rule> rules = new ArrayList<Rule>();
public void addRule(Rule rule) {
rules.add(rule);
}
@Override
public List<Rule> getRules() {
return Collections.unmodifiableList(rules);
}
@Override
public List<Violation> applyTo(HtmlPage htmlPage) {
List<Violation> violations = new ArrayList<Violation>();
for (Rule rule : rules) {
violations.addAll(rule.applyTo(htmlPage));
}
return violations;
}
}
|
package de.fau.cs.mad.kwikshop.common;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import de.fau.cs.mad.kwikshop.common.interfaces.DomainObject;
import de.fau.cs.mad.kwikshop.common.util.NamedQueryConstants;
import javax.persistence.*;
//Hibernate
@Entity(name = "Location")
@Table(name = "Location")
@NamedQueries({
@NamedQuery(
name = NamedQueryConstants.LOCATION_GET_BY_ID,
query = "SELECT l FROM Location l WHERE l.ownerId = :" + NamedQueryConstants.USER_ID +
" AND l.serverId = :" + NamedQueryConstants.LOCATION_ID
)
})
//ORMLite
@DatabaseTable(tableName = "location")
public class LastLocation implements DomainObject {
//Hibernate : ignore client id
@Transient
//ORMLite
@DatabaseField(generatedId = true)
private int id;
//Hibernate
@Id
@GeneratedValue
@Column(name = "id")
//ORMLite
@DatabaseField
private int serverId;
//Hibernate
@Column(name = "latitude")
//ORMLite
@DatabaseField
private double latitude = 0.0;
//Hibernate
@Column(name = "longitude")
//ORMLite
@DatabaseField
private double longitude = 0.0;
//Hibernate
@Column(name = "address")
//ORMLite
@DatabaseField
private String address;
//Hibernate
@Column(name = "name")
//ORMLite
@DatabaseField
private String name;
//Hibernate
@Column(name = "accuracy")
//ORMLite
@DatabaseField
private double accuracy;
//@Column(name="ownerId")
private String ownerId;
@DatabaseField(columnName = "placeId")
private String placeId;
@JsonProperty
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
@JsonProperty
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
@JsonProperty
public String getAddress() {return address; }
public void setAddress(String address) { this.address = address; }
@JsonProperty
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAccuracy() { return accuracy; }
public void setAccuracy(double accuracy) { this.accuracy = accuracy;}
@JsonProperty("id")
public int getServerId() {
return this.serverId;
}
@JsonProperty("id")
public void setServerId(int value) {
this.serverId = value;
}
@JsonIgnore
@Override
public int getId() {
return this.id;
}
@JsonIgnore
public String getOwnerId() {
return this.ownerId;
}
@JsonIgnore
public void setOwnerId(String value) {
this.ownerId = value;
}
@JsonIgnore
@Override
public int getPredefinedId() {
return 0; // always return o (there are no predefined locations)
}
public String getPlaceId() {
return this.placeId;
}
public void setPlaceId(String value) {
this.placeId = value;
}
}
|
package de.haw.rnp.messageticker.view;
import de.haw.rnp.messageticker.model.Message;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.awt.event.ActionListener;
/**
* The view for displaying all messages and the basic chat functionality.
*/
public class MessagesView extends JFrame {
private String[] messageTypes;
private JLabel messageLabel;
private JTextField messageInput;
private JComboBox messageTypesSelector;
private JButton send;
private JButton pauseThreads;
private JTextArea messageOutput;
private JScrollPane scrollPane;
private JPanel statusBar;
private JLabel statusLabel;
private JPanel inputContainer;
private DefaultCaret messageOutputCaret;
/**
* Constructs the view.
* @param messageTypes establishes the messageTypes
*/
public MessagesView(String[] messageTypes) {
super("Nachrichten-Ticker");
this.messageTypes = messageTypes;
this.messageLabel = new JLabel("Nachricht:");
this.messageInput = new JTextField(20);
this.messageTypesSelector = new JComboBox(this.messageTypes);
this.send = new JButton("absenden");
this.pauseThreads = new JButton("Threads pausieren");
this.messageOutput = new JTextArea(40, 100);
this.messageOutputCaret = (DefaultCaret) this.messageOutput.getCaret();
this.scrollPane = new JScrollPane(this.messageOutput);
this.messageOutput.setEditable(false);
this.statusBar = new JPanel();
this.statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
this.statusLabel = new JLabel("STATUS HAR HAR");
this.statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
this.statusBar.setPreferredSize(new Dimension(this.getWidth(),35));
this.inputContainer = new JPanel();
initForm();
}
/**
* Initializes the view and its components.
*/
private void initForm() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(0, 0, 1200, 800);
Container container = this.getContentPane();
container.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
this.messageOutputCaret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
this.scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
gc.fill = GridBagConstraints.HORIZONTAL;
gc.gridx = 0;
gc.gridy = 0;
container.add(inputContainer, gc);
gc.fill = GridBagConstraints.BOTH;
gc.gridx = 0;
gc.gridy = 1;
container.add(scrollPane, gc);
gc.fill = GridBagConstraints.HORIZONTAL;
gc.gridx = 0;
gc.gridy = 2;
gc.anchor = GridBagConstraints.PAGE_END;
container.add(statusBar, gc);
this.statusBar.add(statusLabel);
this.inputContainer.setLayout(new FlowLayout());
this.inputContainer.add(messageLabel);
this.inputContainer.add(messageInput);
this.inputContainer.add(messageTypesSelector);
this.inputContainer.add(send);
this.inputContainer.add(pauseThreads);
}
public void addMessage(Message message) {
this.messageOutput.append(message.toString() + "\n");
}
public String getMessageInput() {
return messageInput.getText();
}
public JButton getSend() {
return this.send;
}
public JButton getPauseThreads() {
return this.pauseThreads;
}
public JLabel getStatusLabel(){return this.statusLabel;}
public String getMessageTypesSelector() {
return messageTypesSelector.getSelectedItem().toString();
}
public void registerSendButtonListener(ActionListener l) {
this.send.addActionListener(l);
}
public void registerThreadButtonListener(ActionListener l) {
this.pauseThreads.addActionListener(l);
}
}
|
package org.fedoraproject.fedmsg;
import org.zeromq.ZMQ;
import java.io.IOException;
/**
* Connect to a fedmsg bus.
*
* @author Ricky Elrod
* @version 1.0.0
*/
public final class FedmsgConnection {
private final String endpoint;
private final int linger;
private ZMQ.Socket sock;
private ZMQ.Context context;
public FedmsgConnection(
String endpoint,
int linger
) {
this.endpoint = endpoint;
this.linger = linger;
}
public String getEndpoint() {
return this.endpoint;
}
public int getLinger() {
return this.linger;
}
public FedmsgConnection connect() {
this.context = ZMQ.context(1);
this.sock = context.socket(ZMQ.PUB);
this.sock.setLinger(this.linger);
this.sock.connect(this.endpoint);
return this;
}
public boolean disconnect() {
return this.sock.disconnect(this.endpoint);
}
public void send(FedmsgMessage msg) throws IOException {
this.sock.send(msg.getTopic(), ZMQ.SNDMORE | ZMQ.NOBLOCK);
this.sock.send(msg.toJson().toString(), ZMQ.NOBLOCK);
}
}
|
package edu.hm.hafner.analysis.parser;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import edu.hm.hafner.analysis.Issue;
import edu.hm.hafner.analysis.IssueBuilder;
import edu.hm.hafner.analysis.IssueParser;
import edu.hm.hafner.analysis.ParsingCanceledException;
import edu.hm.hafner.analysis.ReaderFactory;
import edu.hm.hafner.analysis.Report;
import edu.hm.hafner.analysis.Severity;
import static edu.hm.hafner.analysis.Categories.*;
public class RfLintParser extends IssueParser {
/**
* Map of Robot Framework severity to the analysis model severity.
*/
private enum RfLintSeverity {
ERROR(Severity.WARNING_HIGH),
E(ERROR),
WARNING(Severity.WARNING_NORMAL),
W(WARNING),
IGNORE(Severity.WARNING_LOW),
I(IGNORE);
private final Severity severityLevel;
RfLintSeverity(final Severity level) {
this.severityLevel = level;
}
RfLintSeverity(final RfLintSeverity e) {
this(e.severityLevel);
}
public Severity getSeverityLevel() {
return this.severityLevel;
}
/**
* Determines the RfLintSeverity based on the provided character.
*
* @param violationSeverity
* The character presentiting the violation severity
*
* @return An instance of RfLintSeverity matching the character. `WARNING` as the default if the severity
* character is not valid.
*/
public static RfLintSeverity fromCharacter(final char violationSeverity) {
if (EnumUtils.isValidEnum(RfLintSeverity.class, String.valueOf(violationSeverity))) {
return RfLintSeverity.valueOf(String.valueOf(violationSeverity));
}
return WARNING;
}
}
/**
* The possible categories.
*/
private enum RfLintCategory {
SUITE("Suite"),
KEYWORD("Keyword"),
TEST_CASE("Test Case"),
OTHER("Other"),
CUSTOM("Custom");
private String name;
RfLintCategory(final String name) {
this.name = name;
}
public String getName() {
return this.name;
}
/**
* Determines the RfLint category based on the provided rule name.
*
* @param ruleName
* The rule name
*
* @return An instance of the RfLintCategory associated with the rule name.
*/
public static RfLintCategory fromRuleName(final String ruleName) {
if (EnumUtils.isValidEnum(RfLintRuleName.class, ruleName)) {
RfLintRuleName rule = RfLintRuleName.valueOf(ruleName);
return rule.getCategory();
}
return RfLintCategory.CUSTOM;
}
}
/**
* The list of the rule names built into rflint.
*/
private enum RfLintRuleName {
DUPLICATE_KEYWORD_NAMES(RfLintCategory.SUITE),
DUPLICATE_TEST_NAMES(RfLintCategory.SUITE),
FILE_TOO_LONG(RfLintCategory.OTHER),
INVALID_TABLE(RfLintCategory.SUITE),
LINE_TOO_LONG(RfLintCategory.OTHER),
PERIOD_IN_SUITE_NAME(RfLintCategory.SUITE),
PERIOD_IN_TEST_NAME(RfLintCategory.TEST_CASE),
REQUIRE_KEYWORD_DOCUMENTATION(RfLintCategory.KEYWORD),
REQUIRE_SUITE_DOCUMENTATION(RfLintCategory.SUITE),
REQUIRE_TEST_DOCUMENTATION(RfLintCategory.SUITE),
TAG_WITH_SPACES(RfLintCategory.TEST_CASE),
TOO_FEW_KEYWORD_STEPS(RfLintCategory.KEYWORD),
TOO_MANY_TEST_CASES(RfLintCategory.SUITE),
TOO_FEW_TEST_STEPS(RfLintCategory.TEST_CASE),
TOO_MANY_TEST_STEPS(RfLintCategory.TEST_CASE),
TRAILING_BLANK_LINES(RfLintCategory.OTHER),
TRAILING_WHITESPACE(RfLintCategory.OTHER);
private RfLintCategory category;
RfLintRuleName(final RfLintCategory category) {
this.category = category;
}
public RfLintCategory getCategory() {
return this.category;
}
}
private static final long serialVersionUID = -7903991158616386226L;
private String fileName = StringUtils.EMPTY;
private static final Pattern WARNING_PATTERN = Pattern.compile(
"(?<severity>[WEI]): (?<lineNumber>\\d+), (?<columnNumber>\\d+): (?<message>.*) \\((?<ruleName>.*)\\)");
private static final Pattern FILE_PATTERN = Pattern.compile("\\+\\s(?<filename>.*)");
@Override
public Report parse(final ReaderFactory readerFactory) {
try (Stream<String> lines = readerFactory.readStream()) {
Report warnings = new Report();
lines.forEach(line -> {
Matcher fileMatcher = FILE_PATTERN.matcher(line);
if (fileMatcher.find()) {
fileName = fileMatcher.group(1);
}
Matcher matcher = WARNING_PATTERN.matcher(line);
if (matcher.find()) {
warnings.add(createIssue(matcher, new IssueBuilder()));
}
if (Thread.interrupted()) {
throw new ParsingCanceledException();
}
});
return warnings;
}
}
private Issue createIssue(final Matcher matcher, final IssueBuilder builder) {
String message = matcher.group("message");
String severityStr = guessCategoryIfEmpty(matcher.group("severity"), message);
String ruleName = matcher.group("ruleName");
char severityCharacter = severityStr.charAt(0);
RfLintCategory category = RfLintCategory.fromRuleName(ruleName);
Severity priority = RfLintSeverity.fromCharacter(severityCharacter).getSeverityLevel();
return builder.setFileName(fileName)
.setPackageName(Objects.toString(Paths.get(fileName).getParent()))
.setLineStart(matcher.group("lineNumber"))
.setColumnStart(matcher.group("columnNumber"))
.setCategory(category.getName())
.setType(ruleName)
.setMessage(message)
.setSeverity(priority)
.build();
}
}
|
package fi.helsinki.cs.tmc.cli.command;
import fi.helsinki.cs.tmc.cli.Application;
import fi.helsinki.cs.tmc.cli.core.AbstractCommand;
import fi.helsinki.cs.tmc.cli.core.CliContext;
import fi.helsinki.cs.tmc.cli.core.Command;
import fi.helsinki.cs.tmc.cli.core.CommandFactory;
import fi.helsinki.cs.tmc.cli.io.Io;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@Command(name = "help", desc = "List every command")
public class HelpCommand extends AbstractCommand {
private int longestNameLength;
private CliContext context;
private Io io;
@Override
public String[] getUsages() {
return new String[] {"[category]"};
}
@Override
public void getOptions(Options options) {}
@Override
public void run(CliContext context, CommandLine args) {
Application app = context.getApp();
this.context = context;
this.io = context.getIo();
String category = handleArgs(args);
if (category == null) {
return;
}
StringBuilder sb = new StringBuilder();
if (category.equals("")) {
sb.append("TMC commands:\n");
} else {
sb.append("TMC commands in ").append(category).append(":\n");
}
List<String> commandStrings = getCommandStrings(category);
Collections.sort(commandStrings);
for (String commandString : commandStrings) {
sb.append(commandString).append("\n");
}
app.printHelp(sb.toString());
}
private String handleArgs(CommandLine args) {
String[] stringArguments = args.getArgs();
if (stringArguments.length > 1) {
io.errorln("Too many arguments.");
printUsage(context);
return null;
}
String category = "";
if (stringArguments.length == 1) {
category = stringArguments[0];
}
if (category.equals("all")) {
return category;
}
Set<String> helpCategories = CommandFactory.getCommandCategories();
if(!helpCategories.contains(category)) {
io.errorln("Unknown command category \"" + category + "\".");
return null;
}
return category;
}
private List<String> getCommandStrings(String category) {
List<String> strings = new ArrayList<>();
List<Class<Command>> commands;
if (category.equals("all")) {
commands = CommandFactory.getCommands();
} else {
commands = CommandFactory.getCategoryCommands(category);
}
longestNameLength = longestName(commands);
for (Class<Command> commandClass : commands) {
Command command = CommandFactory.getCommand(commandClass);
strings.add(createCommandString(command));
}
longestNameLength = Math.max(longestNameLength, 8);
return strings;
}
@SuppressWarnings("unchecked")
private Class<Command> castToCommandClass(Class klass) {
return (Class<Command>) klass;
}
private String createCommandString(Command command) {
StringBuilder builder = new StringBuilder();
builder.append(" ").append(command.name());
for (int i = 0; i < longestNameLength - command.name().length() + 1; i++) {
builder.append(" ");
}
builder.append(command.desc());
return builder.toString();
}
private int longestName(List<Class<Command>> commandList) {
int longest = 0;
for (Class<Command> commandClass : commandList) {
Command command = CommandFactory.getCommand(commandClass);
longest = Math.max(longest, command.name().length());
}
return longest;
}
}
|
package org.jvalue.ceps.esper;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.jvalue.ceps.utils.Assert;
import org.jvalue.ceps.utils.Log;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.EventType;
import com.espertech.esper.client.UpdateListener;
import com.espertech.esper.client.util.JSONEventRenderer;
import com.espertech.esper.client.util.JSONRenderingOptions;
import com.espertech.esper.event.util.JSONRendererImpl;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
final class EsperUpdateListener implements UpdateListener {
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
}
private final JsonUpdateListener listener;
private final String eplStmtId;
public EsperUpdateListener(JsonUpdateListener listener, String eplStmtId) {
Assert.assertNotNull(listener, eplStmtId);
this.listener = listener;
this.eplStmtId = eplStmtId;
}
@Override
public void update(EventBean[] newEvents, EventBean[] oldEvents) {
listener.onNewEvents(eplStmtId, toJson(newEvents), toJson(oldEvents));
}
private List<JsonNode> toJson(EventBean[] events) {
List<JsonNode> jsonList = new LinkedList<JsonNode>();
if (events == null) return jsonList;
for (EventBean event : events) {
EventType eventType = event.getEventType();
JSONEventRenderer renderer = new JSONRendererImpl(eventType, new JSONRenderingOptions());
String json = renderer.render("someEvent", event);
Log.info(json);
try {
JsonNode node = mapper.readTree(json);
jsonList.add(node);
// jsonList.add(mapper.valueToTree(event.getUnderlying()));
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
return jsonList;
}
}
|
package fr.insee.rmes.modeles.operations;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import fr.insee.rmes.modeles.StringWithLang;
import fr.insee.rmes.utils.Lang;
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "Objet représentant une opération statistique")
public class Operation {
private String id = null;
private List<StringWithLang> label = new ArrayList<>();
@Schema(example = "http://id.insee.fr/operations/operation/s1")
private String uri = null;
@Schema(example = "1011")
@JsonInclude(Include.NON_EMPTY)
private String simsId = null;
@JsonInclude(Include.NON_NULL)
private List<StringWithLang> altLabel;
public Operation(String uri, String id, String labelFr, String labelEn, String simsId) {
super();
this.id = id;
label.add(new StringWithLang(labelFr, Lang.FR));
if ( ! labelEn.equals("")) {
label.add(new StringWithLang(labelEn, Lang.EN));
}
if ( ! simsId.equals("")) {
this.simsId = simsId;
}
this.uri = uri;
}
public Operation() {
super();
}
@JacksonXmlProperty(isAttribute = true, localName = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JsonInclude(Include.NON_EMPTY)
@JsonProperty(value = "idRapportQualite")
@JacksonXmlProperty(localName = "IdRapportQualite")
public String getSimsId() {
return simsId;
}
@JsonProperty(value="simsId")
public void setSimsId(String simsId) {
if (StringUtils.isNotEmpty(simsId)) {
this.simsId = simsId;
}
}
@JacksonXmlProperty(isAttribute = true, localName = "uri")
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
@JacksonXmlProperty(localName = "Label")
@JacksonXmlElementWrapper(useWrapping = false)
public List<StringWithLang> getLabel() {
return label;
}
public void setLabel(List<StringWithLang> label) {
this.label = label;
}
public void setLabelFr(String labelFr) {
if (StringUtils.isNotEmpty(labelFr)) {
label.add(new StringWithLang(labelFr, Lang.FR));
}
}
public void setLabelEn(String labelEn) {
if (StringUtils.isNotEmpty(labelEn)) {
label.add(new StringWithLang(labelEn, Lang.EN));
}
}
@JacksonXmlProperty(localName = "AltLabel")
@JacksonXmlElementWrapper(useWrapping = false)
public List<StringWithLang> getAltLabel() {
return altLabel;
}
public void setAltLabel(String altLabelLg1, String altLabelLg2) {
if ( ! altLabelLg1.equals("")) {
if (altLabel == null) {
altLabel = new ArrayList<>();
}
altLabel.add(new StringWithLang(altLabelLg1, Lang.FR));
}
if ( ! altLabelLg2.equals("")) {
if (altLabel == null) {
altLabel = new ArrayList<>();
}
altLabel.add(new StringWithLang(altLabelLg2, Lang.EN));
}
}
}
|
package info.gehrels.voting;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableSet;
import info.gehrels.voting.AmbiguityResolver.AmbiguityResolverResult;
import org.apache.commons.math3.fraction.BigFraction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import static com.google.common.collect.Collections2.transform;
import static com.google.common.collect.ImmutableSet.copyOf;
import static com.google.common.collect.Lists.newArrayList;
import static info.gehrels.voting.VoteWeightRedistributionMethod.VoteWeightRedistributor;
import static java.util.Arrays.asList;
public class STVElectionCalculation {
private final ImmutableCollection<Ballot> ballots;
private final QuorumCalculation quorumCalculation;
private final ElectionCalculationListener electionCalculationListener;
private final Election election;
private final AmbiguityResolver ambiguityResolver;
private final VoteWeightRedistributionMethod voteWeightRedistributionMethod;
public STVElectionCalculation(ImmutableCollection<Ballot> ballots,
QuorumCalculation quorumCalculation,
ElectionCalculationListener electionCalculationListener,
Election election, AmbiguityResolver ambiguityResolver,
VoteWeightRedistributionMethod redistributionMethod) {
this.ballots = ballots;
this.quorumCalculation = quorumCalculation;
this.electionCalculationListener = electionCalculationListener;
this.election = election;
this.ambiguityResolver = ambiguityResolver;
voteWeightRedistributionMethod = redistributionMethod;
}
public ImmutableSet<Candidate> calculate(ImmutableSet<? extends Candidate> qualifiedCandidates, int numberOfSeats) {
VoteWeightRedistributor redistributor = voteWeightRedistributionMethod.redistributorFor();
int numberOfValidBallots = ballots.size();
// Runden oder nicht runden?
BigFraction quorum = quorumCalculation.calculateQuorum(numberOfValidBallots, numberOfSeats);
electionCalculationListener.quorumHasBeenCalculated(numberOfValidBallots, numberOfSeats, quorum);
ImmutableMap<Candidate, CandidateState> candidateStates = constructCandidateStates(qualifiedCandidates);
ImmutableCollection<BallotState> ballotStates = constructBallotStates(candidateStates);
int numberOfElectedCandidates = 0;
electionCalculationListener
.calculationStarted(election, calculateVotesByCandidate(candidateStates, ballotStates));
while (notAllSeatsFilled(numberOfElectedCandidates, numberOfSeats) && anyCandidateIsHopeful(
candidateStates)) {
Candidate winner = bestCandidateThatReachedTheQuorum(quorum, candidateStates, ballotStates);
if (winner != null) {
electionCalculationListener
.candidateIsElected(winner, calculateVotesForCandidate(winner, ballotStates), quorum);
numberOfElectedCandidates++;
ballotStates = redistributor.redistributeExceededVoteWeight(winner, quorum, ballotStates);
candidateStates.get(winner).setElected();
ballotStates = createBallotStatesPointingAtNextHopefulCandidate(ballotStates, candidateStates);
electionCalculationListener.voteWeightRedistributionCompleted(
calculateVotesByCandidate(candidateStates, ballotStates));
} else {
electionCalculationListener.nobodyReachedTheQuorumYet(quorum);
ballotStates = strikeWeakestCandidate(candidateStates, ballotStates);
}
}
ImmutableSet<Candidate> electedCandidates = getElectedCandidates(candidateStates);
electionCalculationListener.electedCandidates(electedCandidates);
return electedCandidates;
}
private ImmutableMap<Candidate, CandidateState> constructCandidateStates(
ImmutableSet<? extends Candidate> qualifiedCandidates) {
Builder<Candidate, CandidateState> builder = ImmutableMap.builder();
for (Candidate candidate : qualifiedCandidates) {
builder.put(candidate, new CandidateState(candidate));
}
return builder.build();
}
private ImmutableCollection<BallotState> constructBallotStates(final Map<Candidate, CandidateState> candidateStates) {
ImmutableList.Builder<BallotState> builder = ImmutableList.builder();
return builder.addAll(transform(ballots, new Function<Ballot, BallotState>() {
@Override
public BallotState apply(Ballot ballot) {
return createBallotStatePointingAtNextHopefulCandidate(candidateStates, new BallotState(ballot, election));
}
})).build();
}
private Map<Candidate, BigFraction> calculateVotesByCandidate(Map<Candidate, CandidateState> candidateStates,
Collection<BallotState> ballotStates) {
Map<Candidate, BigFraction> votesByCandidateDraft = new HashMap<>();
for (BallotState ballotState : ballotStates) {
Candidate preferredHopefulCandidate = ballotState.getPreferredCandidate();
if (preferredHopefulCandidate == null) {
continue;
}
BigFraction votes = votesByCandidateDraft.get(preferredHopefulCandidate);
if (votes == null) {
votesByCandidateDraft.put(preferredHopefulCandidate, ballotState.getVoteWeight());
} else {
votesByCandidateDraft.put(preferredHopefulCandidate, votes.add(ballotState.getVoteWeight()));
}
}
Builder<Candidate, BigFraction> builder = ImmutableMap.builder();
for (Candidate candidate : candidateStates.keySet()) {
CandidateState candidateState = candidateStates.get(candidate);
if (candidateState != null && !candidateState.isHopeful()) {
continue;
}
BigFraction votes = votesByCandidateDraft.get(candidate);
builder.put(candidate, votes == null ? BigFraction.ZERO : votes);
}
return builder.build();
}
private boolean notAllSeatsFilled(int numberOfElectedCandidates, int numberOfSeatsToElect) {
boolean notAllSeatsFilled = numberOfElectedCandidates < numberOfSeatsToElect;
electionCalculationListener.numberOfElectedPositions(numberOfElectedCandidates, numberOfSeatsToElect);
return notAllSeatsFilled;
}
private boolean anyCandidateIsHopeful(ImmutableMap<Candidate, CandidateState> candidateStates) {
for (CandidateState candidateState : candidateStates.values()) {
if (candidateState.isHopeful()) {
return true;
}
}
electionCalculationListener.noCandidatesAreLeft();
return false;
}
private Candidate bestCandidateThatReachedTheQuorum(BigFraction quorum,
ImmutableMap<Candidate, CandidateState> candidateStates,
ImmutableCollection<BallotState> ballotStates) {
Map<Candidate, BigFraction> votesByCandidate = calculateVotesByCandidate(candidateStates, ballotStates);
BigFraction numberOfVotesOfBestCandidate = BigFraction.MINUS_ONE;
Collection<Candidate> bestCandidates = newArrayList();
for (Entry<Candidate, BigFraction> votesForCandidate : votesByCandidate.entrySet()) {
if (votesForCandidate.getValue().compareTo(quorum) >= 0) {
if (votesForCandidate.getValue().compareTo(numberOfVotesOfBestCandidate) > 0 ) {
numberOfVotesOfBestCandidate = votesForCandidate.getValue();
bestCandidates = new ArrayList<>(asList(votesForCandidate.getKey()));
} else if (votesForCandidate.getValue().equals(numberOfVotesOfBestCandidate)) {
bestCandidates.add(votesForCandidate.getKey());
}
}
}
return chooseOneOutOfManyCandidates(copyOf(bestCandidates));
}
private BigFraction calculateVotesForCandidate(Candidate candidate, Collection<BallotState> ballotStates) {
BigFraction votes = BigFraction.ZERO;
for (BallotState ballotState : ballotStates) {
if (ballotState.getPreferredCandidate() == candidate) {
votes = votes.add(ballotState.getVoteWeight());
}
}
return votes;
}
private ImmutableCollection<BallotState> strikeWeakestCandidate(ImmutableMap<Candidate, CandidateState> candidateStates,
ImmutableCollection<BallotState> ballotStates) {
Map<Candidate, BigFraction> votesByCandidateBeforeStriking = calculateVotesByCandidate(candidateStates,
ballotStates);
Candidate weakestCandidate = calculateWeakestCandidate(votesByCandidateBeforeStriking);
candidateStates.get(weakestCandidate).setLooser();
ballotStates = createBallotStatesPointingAtNextHopefulCandidate(ballotStates, candidateStates);
Map<Candidate, BigFraction> votesByCandidateAfterStriking = calculateVotesByCandidate(candidateStates, ballotStates);
electionCalculationListener.candidateDropped(
votesByCandidateBeforeStriking,
weakestCandidate.name,
votesByCandidateBeforeStriking.get(weakestCandidate),
votesByCandidateAfterStriking);
return ballotStates;
}
private ImmutableCollection<BallotState> createBallotStatesPointingAtNextHopefulCandidate(
ImmutableCollection<BallotState> ballotStates,
ImmutableMap<Candidate, CandidateState> candidateStates) {
ImmutableList.Builder<BallotState> resultBuilder = ImmutableList.builder();
for (BallotState ballotState : ballotStates) {
resultBuilder.add(createBallotStatePointingAtNextHopefulCandidate(candidateStates, ballotState));
}
return resultBuilder.build();
}
private ImmutableSet<Candidate> getElectedCandidates(ImmutableMap<Candidate, CandidateState> candidateStates) {
ImmutableSet.Builder<Candidate> builder = ImmutableSet.builder();
for (CandidateState candidateState : candidateStates.values()) {
if (candidateState.elected) {
builder.add(candidateState.candidate);
}
}
return builder.build();
}
private Candidate chooseOneOutOfManyCandidates(ImmutableSet<Candidate> candidates) {
Candidate winner = null;
if (candidates.size() == 1) {
return candidates.iterator().next();
} else if (candidates.size() > 1) {
electionCalculationListener.delegatingToExternalAmbiguityResolution(candidates);
AmbiguityResolverResult ambiguityResolverResult = ambiguityResolver.chooseOneOfMany(candidates);
electionCalculationListener.externalyResolvedAmbiguity(ambiguityResolverResult);
winner = ambiguityResolverResult.choosenCandidate;
}
return winner;
}
private Candidate calculateWeakestCandidate(Map<Candidate, BigFraction> votesByCandidate) {
BigFraction numberOfVotesOfBestCandidate = new BigFraction(Integer.MAX_VALUE, 1);
Collection<Candidate> weakestCandidates = newArrayList();
for (Entry<Candidate, BigFraction> votesForCandidate : votesByCandidate.entrySet()) {
if (votesForCandidate.getValue().compareTo(numberOfVotesOfBestCandidate)< 0) {
numberOfVotesOfBestCandidate = votesForCandidate.getValue();
weakestCandidates = new ArrayList<>(asList(votesForCandidate.getKey()));
} else if (votesForCandidate.getValue().equals(numberOfVotesOfBestCandidate)) {
weakestCandidates.add(votesForCandidate.getKey());
}
}
return chooseOneOutOfManyCandidates(copyOf(weakestCandidates));
}
private BallotState createBallotStatePointingAtNextHopefulCandidate(
Map<Candidate, CandidateState> candidateStates, BallotState ballotState) {
BallotState result = ballotState;
Candidate preferredCandidate = result.getPreferredCandidate();
while (preferredCandidate != null) {
CandidateState candidateState = candidateStates.get(preferredCandidate);
if (candidateState != null && candidateState.isHopeful()) {
return result;
}
result = result.withNextPreference();
preferredCandidate = result.getPreferredCandidate();
}
return result;
}
private class CandidateState {
private final Candidate candidate;
private boolean elected = false;
private boolean looser = false;
public CandidateState(Candidate candidate) {
this.candidate = candidate;
}
public boolean isHopeful() {
return !elected && !looser;
}
public void setElected() {
this.elected = true;
}
public void setLooser() {
this.looser = true;
}
@Override
public String toString() {
return candidate.toString() + ": " + (elected ? "" : "not ") + "elected, " + (looser ? "" : "no ") + "looser";
}
}
}
|
package org.lantern;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.ConcurrentHashMap;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.traffic.GlobalTrafficShapingHandler;
import org.jboss.netty.util.Timer;
import org.lantern.event.Events;
import org.lantern.event.IncomingPeerEvent;
import org.lantern.util.Netty3LanternTrafficCounterHandler;
import org.lastbamboo.common.offer.answer.IceConfig;
import org.littleshoot.proxy.HandshakeHandler;
import org.littleshoot.proxy.HandshakeHandlerFactory;
import org.littleshoot.proxy.SslHandshakeHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
/**
* This class handles intercepting incoming SSL connections to the HTTP proxy
* server, associating incoming client certificates with their associated
* peers. Any incoming connections from non-trusted peers with non-trusted
* certificates will be rejected.
*/
@Singleton
public class CertTrackingSslHandlerFactory implements HandshakeHandlerFactory,
Shutdownable {
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* This is the ID used for the per-peer counters in the pipeline.
*/
public static final String PIPELINE_ID = "trafficHandler";
private final ConcurrentHashMap<InetAddress, Netty3LanternTrafficCounterHandler> handlers =
new ConcurrentHashMap<InetAddress, Netty3LanternTrafficCounterHandler>();
private final LanternTrustStore trustStore;
private final Timer timer;
private final LanternKeyStoreManager keyStoreManager;
@Inject
public CertTrackingSslHandlerFactory(final Timer timer,
final LanternTrustStore trustStore,
final LanternKeyStoreManager keyStoreManager) {
this.timer = timer;
this.trustStore = trustStore;
this.keyStoreManager = keyStoreManager;
}
@Override
public void stop() {
for (final GlobalTrafficShapingHandler handler : this.handlers.values()) {
handler.releaseExternalResources();
}
}
/**
* This method is called for every new pipeline that's created -- i.e.
* for every new incoming connection to the server. We need to reload
* the trust store each time to make sure we take into account all the last
* certificates from peers.
*/
@Override
public HandshakeHandler newHandshakeHandler() {
log.debug("Creating new handshake handler...");
final CertTrackingTrustManager certTracker =
new CertTrackingTrustManager();
final SSLEngine engine = newSslEngine(certTracker);
final SslHandlerInterceptor handler = new SslHandlerInterceptor(engine);
certTracker.setSslHandler(handler);
return new SslHandshakeHandler("ssl", handler);
}
public SSLEngine newSslEngine(final TrustManager trustManager) {
if (LanternUtils.isFallbackProxy()) {
return fallbackProxySslEngine();
} else {
return standardSslEngine(trustManager);
}
}
private SSLEngine fallbackProxySslEngine() {
log.debug("Using fallback proxy context");
final String PASS = "Be Your Own Lantern";
try {
final KeyStore ks = KeyStore.getInstance("JKS");
final File keystore = new File(LanternUtils.getKeystorePath());
final InputStream is = new FileInputStream(keystore);
ks.load(is, PASS.toCharArray());
// Set up key manager factory to use our key store
final KeyManagerFactory kmf =
KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, PASS.toCharArray());
// Initialize the SSLContext to work with our key managers.
final SSLContext serverContext = SSLContext.getInstance("TLS");
// NO CLIENT AUTH!!
serverContext.init(kmf.getKeyManagers(), null, null);
final SSLEngine engine = serverContext.createSSLEngine();
engine.setUseClientMode(false);
configureCipherSuites(engine);
return engine;
} catch (final Exception e) {
throw new Error(
"Failed to initialize the server-side SSLContext", e);
}
}
private SSLEngine standardSslEngine(final TrustManager trustManager) {
log.debug("Using standard SSL context");
try {
final SSLContext context = SSLContext.getInstance("TLS");
context.init(this.keyStoreManager.getKeyManagerFactory().getKeyManagers(),
new TrustManager[]{trustManager}, null);
final SSLEngine engine = context.createSSLEngine();
engine.setUseClientMode(false);
engine.setNeedClientAuth(true);
configureCipherSuites(engine);
return engine;
} catch (final Exception e) {
throw new Error(
"Failed to initialize the client-side SSLContext", e);
}
}
private void configureCipherSuites(final SSLEngine engine) {
final String[] suites = IceConfig.getCipherSuites();
if (suites != null && suites.length > 0) {
engine.setEnabledCipherSuites(suites);
} else {
// Can be null in tests.
log.warn("No cipher suites?");
}
}
private class CertTrackingTrustManager implements X509TrustManager {
private final Logger loggger = LoggerFactory.getLogger(getClass());
private SslHandlerInterceptor handler;
public void setSslHandler(final SslHandlerInterceptor handler) {
this.handler = handler;
}
@Override
public void checkClientTrusted(final X509Certificate[] chain, String arg1)
throws CertificateException {
loggger.debug("Checking client trusted...");
final X509Certificate cert = chain[0];
if (!LanternUtils.isFallbackProxy() &&
!trustStore.containsCertificate(cert)) {
loggger.warn("Certificate is not trusted!!");
throw new CertificateException("not trusted");
}
loggger.debug("Certificate trusted");
Events.asyncEventBus().post(
new IncomingPeerEvent(handler.channel, handler.trafficCounter, cert));
// We should already know about the peer at this point, and it's just
// a matter of correlating that peer with this certificate and
// connection.
}
@Override
public void checkServerTrusted(final X509Certificate[] chain, String arg1)
throws CertificateException {
throw new CertificateException(
"Should never be checking server trust from the server");
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// We don't accept any issuers.
return new X509Certificate[]{};
}
}
private final class SslHandlerInterceptor extends SslHandler {
private Channel channel;
private Netty3LanternTrafficCounterHandler trafficCounter;
public SslHandlerInterceptor(final SSLEngine engine) {
super(engine);
}
@Override
public void channelConnected(final ChannelHandlerContext ctx,
final ChannelStateEvent e) throws Exception {
log.debug("Got channel connected...");
try {
// We basically want to add separate traffic handlers per IP,
// and we do that here. We have a new incoming socket and
// check for an existing handler. If it's there, we use it.
// Otherwise we add and use a new one.
final InetSocketAddress isa =
(InetSocketAddress) ctx.getChannel().getRemoteAddress();
final InetAddress address = isa.getAddress();
final Netty3LanternTrafficCounterHandler newHandler =
new Netty3LanternTrafficCounterHandler(timer);
final Netty3LanternTrafficCounterHandler existingHandler =
handlers.putIfAbsent(address, newHandler);
final Netty3LanternTrafficCounterHandler toUse;
if (existingHandler == null) {
toUse = newHandler;
} else {
log.debug("Using existing traffic counter...");
toUse = existingHandler;
}
toUse.incrementSockets();
this.channel = ctx.getChannel();
this.trafficCounter = toUse;
this.channel.getPipeline().addFirst(PIPELINE_ID, toUse);
} finally {
// The message is then just passed to the next handler
super.channelConnected(ctx, e);
}
}
}
}
|
package ru.artyushov.jmhPlugin.configuration;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiIdentifier;
import com.intellij.psi.PsiMethod;
import org.jetbrains.annotations.NotNull;
public class ConfigurationUtils {
public static final String SETUP_ANNOTATION = "org.openjdk.jmh.annotations.Setup";
public static final String TEAR_DOWN_ANNOTATION = "org.openjdk.jmh.annotations.TearDown";
public static final String JMH_ANNOTATION_NAME = "org.openjdk.jmh.annotations.Benchmark";
public static boolean hasBenchmarkAnnotation(@NotNull PsiMethod method) {
return method.hasAnnotation(JMH_ANNOTATION_NAME);
}
public static boolean hasSetupOrTearDownAnnotation(@NotNull PsiMethod method) {
return method.hasAnnotation(SETUP_ANNOTATION) ||
method.hasAnnotation(TEAR_DOWN_ANNOTATION);
}
public static boolean isBenchmarkMethod(@NotNull PsiElement element) {
if (!(element instanceof PsiIdentifier))
return false;
element = element.getParent();
if (!(element instanceof PsiMethod))
return false;
return isBenchmarkMethod((PsiMethod) element);
}
public static boolean isBenchmarkMethod(@NotNull PsiMethod method) {
return method.hasModifierProperty("public") && hasBenchmarkAnnotation(method);
}
public static boolean isBenchmarkClass(@NotNull PsiElement psiElement) {
if (!(psiElement instanceof PsiIdentifier))
return false;
final PsiElement element = psiElement.getParent();
if (!(element instanceof PsiClass)) {
return false;
}
return containsBenchmarkMethod((PsiClass) element);
}
public static boolean containsBenchmarkMethod(@NotNull PsiClass aClass) {
final PsiMethod[] methods = aClass.getMethods();
for (final PsiMethod method : methods) {
if (isBenchmarkMethod(method)) return true;
}
return false;
}
}
|
package net.afterlifelochie.fontbox.render;
import net.afterlifelochie.fontbox.api.data.IBookProperties;
import net.afterlifelochie.fontbox.api.layout.IIndexed;
import net.afterlifelochie.fontbox.api.formatting.PageMode;
import net.afterlifelochie.fontbox.api.formatting.layout.Layout;
import net.afterlifelochie.fontbox.api.layout.IElement;
import net.afterlifelochie.fontbox.api.layout.IPage;
import net.afterlifelochie.fontbox.api.layout.IPageIndex;
import net.afterlifelochie.fontbox.api.tracer.ITracer;
import net.afterlifelochie.fontbox.layout.DocumentProcessor;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.Tuple;
import net.minecraft.util.math.MathHelper;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.OpenGLException;
import org.lwjgl.opengl.Util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class BookGUI extends GuiScreen implements IIndexed {
/**
* The renderer's PageMode
*/
private final PageMode mode;
/**
* The list of pages
*/
private List<? extends IPage> pages;
/**
* The data index
*/
private IPageIndex index;
/**
* The current page pointer
*/
private int ptr = 0;
/**
* The current opengl display list state
*/
private boolean useDisplayList = false;
/**
* The current opengl buffer list
*/
private int[] glDisplayLists;
/**
* The current buffer dirty state
*/
private boolean glBufferDirty[];
/**
* The underlying bookProperties properties
*/
private final IBookProperties bookProperties;
private int guiLeft, guiTop;
/**
* <p>
* Create a new Book rendering context on top of the existing Minecraft GUI
* system. The bookProperties rendering properties are set through the constructor and
* control how many and where pages are rendered.
* </p>
*
* @param bookProperties The underlying {@link IBookProperties}
*/
public BookGUI(IBookProperties bookProperties, ITracer tracer) {
if (bookProperties == null)
throw new IllegalArgumentException("IBookProperties cannot be null!");
if (bookProperties.getPageMode() == null)
throw new IllegalArgumentException("Mode cannot be null!");
if (bookProperties.getPageMode().layouts == null)
throw new IllegalArgumentException("Layout cannot be null!");
this.bookProperties = bookProperties;
this.mode = bookProperties.getPageMode();
prepareGraphics(tracer);
}
/**
* <p>
* Updates the pages currently being rendered.
* </p>
* <p>
* If the page read pointer is currently beyond the end of the new page
* count (ie, the number of pages has reduced), the pointer will be reset to
* the beginning of the bookProperties.
* </p>
*
* @param pages The new list of pages
* @param index The new page index
*/
public void changePages(List<? extends IPage> pages, IPageIndex index) {
if (ptr >= pages.size()) {
ptr = 0;
}
this.pages = pages;
this.index = index;
internalOnPageChanged(this, ptr);
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
@Override
public void initGui() {
super.initGui();
this.guiLeft = (width - bookProperties.getBookWidth()) / 2;
this.guiTop = (height - bookProperties.getBookHeight()) / 2;
}
@Override
public void onGuiClosed() {
if (useDisplayList) {
useDisplayList = false;
GlStateManager.glDeleteLists(glDisplayLists[0], glDisplayLists.length);
for (int i = 0; i < glDisplayLists.length; i++)
glDisplayLists[i] = -1;
}
}
@Override
public void updateScreen() {
super.updateScreen();
}
@Override
public void drawScreen(int mx, int my, float frames) {
super.drawScreen(mx, my, frames);
drawBackground(mx, my, frames);
try {
if (pages != null) {
List<Tuple<Layout, IPage>> toRender = new ArrayList<>(2);
int i;
for (i = 0; i < mode.pages; i++) {
int what = ptr + i;
if (pages.size() <= what)
break;
toRender.add(new Tuple<>(mode.layouts[i], pages.get(ptr + i)));
}
i = 0;
for (Tuple<Layout, IPage> page : toRender)
if (useDisplayList)
renderPageStaticsBuffered(i++, page.getSecond(), page.getFirst().x, page.getFirst().y, zLevel, mx, my, frames);
else
renderPageStaticsImmediate(page.getSecond(), page.getFirst().x, page.getFirst().y, zLevel, mx, my, frames);
for (Tuple<Layout, IPage> page : toRender)
renderPageDynamics(page.getSecond(), page.getFirst().x, page.getFirst().y, zLevel, mx, my, frames);
}
} catch (RenderException err) {
err.printStackTrace();
}
drawForeground(mx, my, frames);
}
/**
* <p>
* Draw the background layer of the interface. You must leave the opengl
* state such that the layout (0, 0) will be drawn in the current place.
* </p>
*
* @param mx The mouse x-coordinate
* @param my The mouse y-coordinate
* @param frame The partial frames rendered
*/
public void drawBackground(int mx, int my, float frame) {
GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
GlStateManager.translate(guiLeft, guiTop, 0.0f);
GlStateManager.pushMatrix();
bookProperties.drawBackground(width, height, mx, my, frame, zLevel);
GlStateManager.popMatrix();
}
/**
* <p>
* Draw the foreground layer of the interface. The opengl state is such that
* the layout coordinates (0, 0) are in the top-left corner of the written
* text.
* </p>
*
* @param mx The mouse x-coordinate
* @param my The mouse y-coordinate
* @param frame The partial frames rendered
*/
public void drawForeground(int mx, int my, float frame) {
GlStateManager.pushMatrix();
bookProperties.drawForeground(width, height, mx, my, frame, zLevel);
GlStateManager.popMatrix();
}
/**
* Called internally when the page is changed.
*
* @param gui The bookProperties GUI
* @param whatPtr The new page pointer
*/
private void internalOnPageChanged(BookGUI gui, int whatPtr) {
for (int i = 0; i < mode.pages; i++)
glBufferDirty[i] = true;
bookProperties.onPageChanged(gui, whatPtr, pages.size() - 1);
}
/**
* Called internally to set up the display lists.
*/
protected void prepareGraphics(ITracer tracer) {
try {
Util.checkGLError();
} catch (OpenGLException glex) {
tracer.warn("BookGUI.prepareGraphics", "Bad OpenGL operation detected, check GL history!");
glex.printStackTrace();
return;
}
glDisplayLists = new int[mode.pages];
glBufferDirty = new boolean[mode.pages];
int glList = GlStateManager.glGenLists(glDisplayLists.length);
try {
Util.checkGLError();
} catch (OpenGLException glex) {
tracer.warn("BookGUI.prepareGraphics",
"Unable to allocate display-list buffers, using immediate mode.");
return;
}
if (glList <= 0)
tracer.warn("BookGUI.prepareGraphics", "No display-lists available, using immediate mode.");
else {
for (int i = 0; i < glDisplayLists.length; i++) {
glDisplayLists[i] = glList + i;
glBufferDirty[i] = true;
}
tracer.trace("BookGUI.prepareGraphics", "Displaylist initialized.", glList, glDisplayLists.length);
useDisplayList = true;
}
}
/**
* Advance to the next page
*/
@Override
public void next() {
if (ptr + mode.pages < pages.size()) {
ptr += mode.pages;
internalOnPageChanged(this, ptr);
}
}
/**
* Go to a page in the index; if the item doesn't exist, no navigation
* occurs
*
* @param id The ID of the anchor to go to
*/
@Override
public void go(String id) {
int where = index.find(id);
if (where != -1)
go(where);
}
/**
* Go to a page
*
* @param where The page pointer
*/
@Override
public void go(int where) {
where = where - (where % mode.pages);
if (ptr != where && where >= 0 && where + mode.pages - 1 <= pages.size()) {
ptr = where;
internalOnPageChanged(this, ptr);
}
}
/**
* Reverse to the previous page
*/
@Override
public void previous() {
if (0 <= ptr - mode.pages) {
ptr -= mode.pages;
internalOnPageChanged(this, ptr);
}
}
@Override
public GuiScreen getGuiScreen() {
return this;
}
@Override
protected void keyTyped(char val, int code) throws IOException {
super.keyTyped(val, code);
if (code == Keyboard.KEY_LEFT)
previous();
if (code == Keyboard.KEY_RIGHT)
next();
}
@Override
protected void mouseClicked(int mx, int my, int button) throws IOException {
super.mouseClicked(mx, my, button);
for (int i = 0; i < mode.pages; i++) {
Layout where = mode.layouts[i];
int which = ptr + i;
if (pages.size() <= which)
break;
IPage page = pages.get(ptr + i);
int mouseX = MathHelper.ceil((mx - guiLeft - where.x) / IBookProperties.SCALE), mouseY = MathHelper.ceil((my - guiTop - where.y) / IBookProperties.SCALE);
float thresholdX = page.getWidth() / 10.0F, thresholdY = page.getHeight() / 10.0F;
if (mouseX >= 0 && mouseY >= 0 && mouseX <= page.getWidth() && mouseY <= page.getHeight()) {
IElement elem = DocumentProcessor.getElementAt(page, mouseX, mouseY);
if (elem != null) {
elem.clicked(this, mouseX, mouseY);
return;
}
}
if (mouseX >= -thresholdX && mouseY >= page.getHeight() - thresholdY && mouseX <= thresholdX && mouseY <= page.getHeight() + thresholdY) {
previous();
return;
} else if (mouseX >= page.getWidth() - thresholdX && mouseY >= page.getHeight() - thresholdY && mouseX <= page.getWidth() + thresholdX && mouseY <= page.getHeight() + thresholdY) {
next();
return;
}
}
}
@Override
protected void mouseReleased(int mouseX, int mouseY, int state) {
super.mouseReleased(mouseX, mouseY, state);
}
@Override
protected void mouseClickMove(int mx, int my, int button, long ticks) {
super.mouseClickMove(mx, my, button, ticks);
}
@Override
public void handleMouseInput() throws IOException {
super.handleMouseInput();
int scroll = Mouse.getEventDWheel();
if (scroll > 0) {
previous();
} else if (scroll < 0) {
next();
}
}
private void renderPageDynamics(IPage page, float x, float y, float z, int mx, int my, float frame) throws RenderException {
GlStateManager.pushMatrix();
GlStateManager.translate(x, y, z);
renderElementGroupImmediate(page.dynamicElements(), mx, my, frame);
GlStateManager.popMatrix();
}
private void renderPageStaticsImmediate(IPage page, float x, float y, float z, int mx, int my, float frame) throws RenderException {
GlStateManager.pushMatrix();
GlStateManager.translate(x, y, z);
renderElementGroupImmediate(page.staticElements(), mx, my, frame);
GlStateManager.popMatrix();
}
private void renderPageStaticsBuffered(int index, IPage page, float x, float y, float z, int mx, int my, float frame) throws RenderException {
if (glBufferDirty[index]) {
GlStateManager.glNewList(glDisplayLists[index], GL11.GL_COMPILE);
renderPageStaticsImmediate(page, x, y, z, mx, my, frame);
GlStateManager.glEndList();
glBufferDirty[index] = false;
}
GlStateManager.callList(glDisplayLists[index]);
}
private void renderElementGroupImmediate(Iterable<? extends IElement> elements, int mx, int my, float frame) throws RenderException {
for (IElement element : elements)
element.render(this, mx, my, frame);
}
}
|
package org.lifenoodles.jargparse;
import org.lifenoodles.jargparse.parsers.OptionParser;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
class OptionValidator {
private final String description;
private final List<String> names;
private final OptionParser optionParser;
private final Predicate<String> predicate;
public OptionValidator(final List<String> names,
final String description,
final OptionParser optionParser,
final Predicate<String> predicate) {
this.names = new ArrayList<>(names);
this.description = description;
this.optionParser = optionParser;
this.predicate = predicate;
}
public String getName() {
return names.get(0);
}
/**
* @return return the full list of names of this option
*/
public List<String> getNames() {
return new ArrayList<>(names);
}
/**
* @return the description of this option
*/
public String getDescription() {
return description;
}
public boolean isArgumentListLegal(final List<String> arguments) {
return extractArguments(Utility.dropN(1, arguments)).stream()
.allMatch(predicate);
}
public boolean isArgumentCountCorrect(final List<String> arguments) {
return optionParser.isCountCorrect(Utility.dropN(1, arguments));
}
public List<String> extractArguments(final List<String> arguments) {
return optionParser.extractArguments(Utility.dropN(1, arguments));
}
public List<String> restOfArguments(final List<String> arguments) {
return optionParser.restOfArguments(Utility.dropN(1, arguments));
}
}
|
package org.minimalj.repository.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.minimalj.model.Code;
import org.minimalj.model.Keys;
import org.minimalj.model.ViewUtil;
import org.minimalj.model.annotation.NotEmpty;
import org.minimalj.model.annotation.TechnicalField;
import org.minimalj.model.annotation.TechnicalField.TechnicalFieldType;
import org.minimalj.model.properties.FlatProperties;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.security.Subject;
import org.minimalj.util.EqualsHelper;
import org.minimalj.util.IdUtils;
import org.minimalj.util.LoggingRuntimeException;
import org.minimalj.util.StringUtils;
/**
* Minimal-J internal<p>
*
* Base class of all table representing classes in this persistence layer.
* Normally you should not need to extend from this class directly. Use
* the existing subclasses or only the methods in SqlRepository.
*
*/
public abstract class AbstractTable<T> {
public static final Logger sqlLogger = Logger.getLogger("SQL");
protected final SqlRepository sqlRepository;
protected final Class<T> clazz;
protected final LinkedHashMap<String, PropertyInterface> columns;
protected final String name;
protected final List<String> indexes = new ArrayList<>();
protected final List<String> constraints = new ArrayList<>();
protected final String selectByIdQuery;
protected final String insertQuery;
protected final String updateQuery;
protected final String deleteQuery;
protected final String clearQuery;
protected AbstractTable(SqlRepository sqlRepository, String name, Class<T> clazz) {
this.sqlRepository = sqlRepository;
this.name = buildTableName(sqlRepository, name, clazz);
this.clazz = clazz;
this.columns = sqlRepository.findColumns(clazz);
sqlRepository.getTableByName().put(this.name, this);
this.selectByIdQuery = selectByIdQuery();
this.insertQuery = insertQuery();
this.updateQuery = updateQuery();
this.deleteQuery = deleteQuery();
this.clearQuery = clearQuery();
findCodes();
findDependables();
findIndexes();
}
protected String buildTableName(SqlRepository repository, String name, Class<T> clazz) {
if (name == null) {
name = StringUtils.toSnakeCase(clazz.getSimpleName());
}
name = repository.sqlIdentifier.table(name, repository.getTableByName().keySet());
// the repository adds the table name too late. For subtables it's important to add the table name here.
repository.getTableByName().put(name, this);
return name;
}
public boolean isHistorized() {
return false;
}
protected LinkedHashMap<String, PropertyInterface> getColumns() {
return columns;
}
protected Collection<String> getIndexes() {
return indexes;
}
public static PreparedStatement createStatement(Connection connection, String query, boolean returnGeneratedKeys) throws SQLException {
int autoGeneratedKeys = returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS;
if (sqlLogger.isLoggable(Level.FINE)) {
return new LoggingPreparedStatement(connection, query, autoGeneratedKeys, sqlLogger);
} else {
return connection.prepareStatement(query, autoGeneratedKeys);
}
}
protected void execute(String s) {
try (PreparedStatement statement = createStatement(sqlRepository.getConnection(), s, false)) {
statement.execute();
} catch (SQLException x) {
throw new LoggingRuntimeException(x, sqlLogger, "Statement failed: \n" + s);
}
}
protected void createTable(SqlDialect dialect) {
StringBuilder s = new StringBuilder();
dialect.addCreateStatementBegin(s, getTableName());
addSpecialColumns(dialect, s);
addFieldColumns(dialect, s);
addPrimaryKey(dialect, s);
dialect.addCreateStatementEnd(s);
execute(s.toString());
}
protected void dropTable(SqlDialect dialect) {
StringBuilder s = new StringBuilder();
s.append("DROP TABLE ").append(getTableName());
execute(s.toString());
}
protected void dropConstraints(SqlDialect dialect) {
for (String constraint : constraints) {
execute("ALTER TABLE " + getTableName() + " DROP CONSTRAINT " + constraint);
}
}
protected abstract void addSpecialColumns(SqlDialect dialect, StringBuilder s);
protected void addFieldColumns(SqlDialect dialect, StringBuilder s) {
for (Map.Entry<String, PropertyInterface> column : getColumns().entrySet()) {
s.append(",\n ").append(column.getKey()).append(' ');
PropertyInterface property = column.getValue();
dialect.addColumnDefinition(s, property);
boolean isNotEmpty = property.getAnnotation(NotEmpty.class) != null;
s.append(isNotEmpty ? " NOT NULL" : " DEFAULT NULL");
}
}
protected void addPrimaryKey(SqlDialect dialect, StringBuilder s) {
dialect.addPrimaryKey(s, "ID");
}
protected void createIndexes(SqlDialect dialect) {
for (String indexedColumn : indexes) {
String indexName = sqlRepository.sqlIdentifier.index(getTableName(), indexedColumn);
String s = sqlRepository.sqlDialect.createIndex(indexName, getTableName(), indexedColumn, isHistorized());
execute(s);
}
}
protected void createConstraints(SqlDialect dialect) {
for (Map.Entry<String, PropertyInterface> column : getColumns().entrySet()) {
PropertyInterface property = column.getValue();
if (IdUtils.hasId(property.getClazz())) {
Class<?> fieldClass = property.getClazz();
fieldClass = ViewUtil.resolve(fieldClass);
AbstractTable<?> referencedTable = sqlRepository.getAbstractTable(fieldClass);
if (referencedTable.isHistorized()) {
continue;
}
createConstraint(dialect, column.getKey(), referencedTable);
}
}
}
protected final void createConstraint(SqlDialect dialect, String column, AbstractTable<?> referencedTable) {
String constraintName = sqlRepository.sqlIdentifier.constraint(getTableName(), column, referencedTable.getTableName());
String constraint = dialect.createConstraint(constraintName, getTableName(), column, referencedTable.getTableName());
if (constraint != null) {
constraints.add(constraintName);
execute(constraint);
}
}
public void clear() {
try (PreparedStatement statement = createStatement(sqlRepository.getConnection(), clearQuery, false)) {
statement.execute();
} catch (SQLException x) {
throw new LoggingRuntimeException(x, sqlLogger, "Clear of Table " + getTableName() + " failed");
}
}
protected String findColumn(String fieldPath) {
for (Map.Entry<String, PropertyInterface> entry : columns.entrySet()) {
if (entry.getValue().getPath().equals(fieldPath)) {
return entry.getKey();
}
}
return null;
}
public String column(PropertyInterface property) {
return findColumn(property.getPath());
}
public String column(Object key) {
return column(Keys.getProperty(key));
}
public String getTableName() {
return name;
}
public Class<T> getClazz() {
return clazz;
}
private void findCodes() {
for (Map.Entry<String, PropertyInterface> column : getColumns().entrySet()) {
PropertyInterface property = column.getValue();
Class<?> fieldClazz = property.getClazz();
if (Code.class.isAssignableFrom(fieldClazz) && fieldClazz != clazz) {
sqlRepository.addClass(ViewUtil.resolve(fieldClazz));
}
}
}
private void findDependables() {
for (Map.Entry<String, PropertyInterface> column : getColumns().entrySet()) {
PropertyInterface property = column.getValue();
Class<?> fieldClazz = property.getClazz();
if (isDependable(property) && fieldClazz != clazz) {
sqlRepository.addClass(ViewUtil.resolve(fieldClazz));
}
}
for (PropertyInterface property : FlatProperties.getListProperties(getClazz())) {
Class<?> listType = property.getGenericClass();
if (IdUtils.hasId(listType)) {
sqlRepository.addClass(ViewUtil.resolve(listType));
}
}
}
protected void findIndexes() {
for (Map.Entry<String, PropertyInterface> column : columns.entrySet()) {
PropertyInterface property = column.getValue();
if (IdUtils.hasId(property.getClazz())) {
addIndex(property, property.getPath());
}
}
}
// execution helpers
protected long executeSelectCount(PreparedStatement preparedStatement) {
try (ResultSet resultSet = preparedStatement.executeQuery()) {
resultSet.next();
return resultSet.getLong(1);
} catch (SQLException x) {
throw new RuntimeException(x.getMessage());
}
}
protected T executeSelect(PreparedStatement preparedStatement) {
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
return sqlRepository.readResultSetRow(clazz, resultSet);
} else {
return null;
}
} catch (SQLException x) {
throw new RuntimeException(x.getMessage());
}
}
protected T executeSelect(PreparedStatement preparedStatement, Map<Class<?>, Map<Object, Object>> loadedReferences) {
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
return sqlRepository.readResultSetRow(clazz, resultSet, loadedReferences);
} else {
return null;
}
} catch (SQLException x) {
throw new RuntimeException(x.getMessage());
}
}
protected List<T> executeSelectAll(PreparedStatement preparedStatement) {
List<T> result = new ArrayList<>();
try (ResultSet resultSet = preparedStatement.executeQuery()) {
Map<Class<?>, Map<Object, Object>> loadedReferences = new HashMap<>();
while (resultSet.next()) {
T object = sqlRepository.readResultSetRow(clazz, resultSet, loadedReferences);
if (this instanceof Table) {
((Table<T>) this).loadLists(object);
}
result.add(object);
}
} catch (SQLException x) {
throw new RuntimeException(getTableName() + " / " + x.getMessage());
}
return result;
}
protected enum ParameterMode {
INSERT, UPDATE, HISTORIZE, INSERT_AUTO_INCREMENT;
}
protected int setParameters(PreparedStatement statement, T object, ParameterMode mode, Object id) throws SQLException {
int parameterPos = 1;
boolean insert = mode == ParameterMode.INSERT || mode == ParameterMode.INSERT_AUTO_INCREMENT;
for (Map.Entry<String, PropertyInterface> column : columns.entrySet()) {
PropertyInterface property = column.getValue();
Object value = property.getValue(object);
if (value instanceof Code) {
value = findId((Code) value);
} else if (IdUtils.hasId(property.getClazz())) {
if (value != null) {
Object referencedId = IdUtils.getId(value);
if (referencedId != null) {
value = referencedId;
} else {
Table referencedTable = sqlRepository.getTable(property.getClazz());
value = referencedTable.insert(value);
}
}
} else if (isDependable(property)) {
Table dependableTable = sqlRepository.getTable(property.getClazz());
if (insert) {
if (value != null) {
value = dependableTable.insert(value);
}
} else {
// update
String dependableColumnName = column.getKey();
Object dependableId = getDependableId(id, dependableColumnName);
if (value != null) {
value = updateDependable(dependableTable, dependableId, value, mode);
} else {
if (mode == ParameterMode.UPDATE) {
// to delete a dependable the value where its used has to be set
// to null first. This problem could also be solved by setting the
// reference constraint to 'deferred'. But this 'deferred' is more
// expensive for database and doesn't work with maria db (TODO: really?)
setColumnToNull(id, dependableColumnName);
dependableTable.deleteById(dependableId);
}
}
}
} else {
TechnicalField technicalField = property.getAnnotation(TechnicalField.class);
if (technicalField != null) {
TechnicalFieldType type = technicalField.value();
if (type == TechnicalFieldType.EDIT_DATE || type == TechnicalFieldType.CREATE_DATE && insert) {
value = LocalDateTime.now();
} else if (type == TechnicalFieldType.EDIT_USER || type == TechnicalFieldType.CREATE_USER && insert) {
Subject subject = Subject.getCurrent();
if (subject != null) {
value = subject.getName();
}
}
}
}
if (value != null) {
sqlRepository.getSqlDialect().setParameter(statement, parameterPos++, value);
} else {
sqlRepository.getSqlDialect().setParameterNull(statement, parameterPos++, property.getClazz());
}
}
if (mode != ParameterMode.INSERT_AUTO_INCREMENT) {
statement.setObject(parameterPos++, id);
}
return parameterPos;
}
protected Object updateDependable(Table dependableTable, Object dependableId, Object dependableObject, ParameterMode mode) {
if (dependableId != null) {
Object objectInDb = dependableTable.read(dependableId);
if (!EqualsHelper.equals(dependableObject, objectInDb)) {
if (mode == ParameterMode.HISTORIZE) {
IdUtils.setId(dependableObject, null);
dependableId = dependableTable.insert(dependableObject);
} else {
dependableTable.updateWithId(dependableObject, dependableId);
}
}
} else {
dependableId = dependableTable.insert(dependableObject);
}
return dependableId;
}
// TODO multiple dependables could be get with one (prepared) statement
private Object getDependableId(Object id, String column) {
String query = "SELECT " + column + " FROM " + getTableName() + " WHERE ID = ?";
if (isHistorized()) {
query += " AND VERSION = 0";
}
try (PreparedStatement preparedStatement = createStatement(sqlRepository.getConnection(), query, false)) {
preparedStatement.setObject(1, id);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getObject(1);
} else {
return null;
}
}
} catch (SQLException x) {
throw new RuntimeException(x.getMessage());
}
}
private void setColumnToNull(Object id, String column) {
String update = "UPDATE " + getTableName() + " SET " + column + " = NULL WHERE ID = ?";
try (PreparedStatement preparedStatement = createStatement(sqlRepository.getConnection(), update, false)) {
preparedStatement.setObject(1, id);
preparedStatement.execute();
} catch (SQLException x) {
throw new RuntimeException(x.getMessage());
}
}
private Object findId(Code code) {
Object id = IdUtils.getId(code);
if (id != null) {
return id;
}
List<?> codes = sqlRepository.getCodes(code.getClass());
for (Object c : codes) {
if (code.equals(c)) {
return IdUtils.getId(c);
}
}
return null;
}
protected abstract String insertQuery();
protected abstract String updateQuery();
protected abstract String deleteQuery();
protected abstract String selectByIdQuery();
protected String clearQuery() {
return "DELETE FROM " + getTableName();
}
protected final Object getOrCreateId(Object object) {
Object id = IdUtils.getId(object);
if (id == null) {
id = sqlRepository.insert(object);
}
return id;
}
private void addIndex(PropertyInterface property, String fieldPath) {
Map.Entry<String, PropertyInterface> entry = findX(fieldPath);
if (indexes.contains(entry.getKey())) {
return;
}
String myFieldPath = entry.getValue().getPath();
if (fieldPath.length() > myFieldPath.length()) {
String rest = fieldPath.substring(myFieldPath.length() + 1);
AbstractTable<?> innerTable = sqlRepository.getAbstractTable(entry.getValue().getClazz());
innerTable.addIndex(property, rest);
}
indexes.add(entry.getKey());
}
private Entry<String, PropertyInterface> findX(String fieldPath) {
while (true) {
for (Map.Entry<String, PropertyInterface> entry : columns.entrySet()) {
String columnFieldPath = entry.getValue().getPath();
if (columnFieldPath.equals(fieldPath)) {
return entry;
}
}
int index = fieldPath.lastIndexOf('.');
if (index < 0) throw new IllegalArgumentException();
fieldPath = fieldPath.substring(0, index);
}
}
/**
* @param property the property to check
* @return true if property isn't a base object like String, Integer, Date, enum but a dependable
*/
public static boolean isDependable(PropertyInterface property) {
if (property.getClazz().getName().startsWith("java")) return false;
if (Enum.class.isAssignableFrom(property.getClazz())) return false;
if (property.isFinal()) return false;
if (property.getClazz().isArray()) return false;
return true;
}
}
|
package net.dean.jraw.pagination;
import net.dean.jraw.*;
import net.dean.jraw.models.Sorting;
import net.dean.jraw.models.core.Listing;
import net.dean.jraw.models.core.Thing;
import java.util.HashMap;
import java.util.Map;
/**
* Represents the basic concept of a paginator
*
* @param <T> The type that the listing will contain
*/
public abstract class AbstractPaginator<T extends Thing> {
/** Maximum number of things returned by the Reddit API */
public static final int LIMIT_MAX = 100;
/** Default number of things returned by the Reddit API */
public static final int LIMIT_DEFAULT = 25;
protected Sorting sorting;
protected TimePeriod timePeriod;
/** From 1 to {@value #LIMIT_MAX} */
protected int limit;
/** Current listing. Will get the next listing based on this one's "after" value */
protected Listing<T> current;
/** The client that created this */
protected RedditClient creator;
private Class<T> thingType;
/**
* Instantiates a new AbstractPaginator
*
* @param creator The client that created this
* @param thingType The type of thing that will be created
*/
protected AbstractPaginator(RedditClient creator, Class<T> thingType) {
this.creator = creator;
this.thingType = thingType;
// Reddit API default settings
this.limit = LIMIT_DEFAULT;
this.sorting = Sorting.HOT;
this.timePeriod = TimePeriod.DAY;
}
/**
* Gets a listing of things
*
* @param forwards If true, this method will return the next listing. If false, it will return the first listing.
* @return
* @throws net.dean.jraw.NetworkException
*/
protected Listing<T> getListing(boolean forwards) throws NetworkException {
String path = getBaseUri();
Map<String, String> args = new HashMap<>();
args.put("limit", Integer.toString(limit));
if (current != null) {
if (forwards && current.getAfter() != null)
args.put("after", current.getAfter());
}
if (timePeriod != null && (sorting == Sorting.CONTROVERSIAL || sorting == Sorting.TOP)) {
// Time period only applies to controversial and top listings
args.put("t", timePeriod.name().toLowerCase());
}
Listing<T> listing = creator.execute(new RestRequest(HttpVerb.GET, path, args)).asListing(thingType);
this.current = listing;
return listing;
}
/**
* Gets the next listing. If a setter method is called (that is not ${@link #setLimit(int)}), then this method is
* going to return the same thing that ${@link #first()} would.
*
* @return The next listing of submissions
* @throws NetworkException
*/
public Listing<T> next() throws NetworkException {
return getListing(true);
}
/**
* Gets the first listing
*
* @return The first listing
* @throws NetworkException
*/
public Listing<T> first() throws NetworkException {
return getListing(false);
}
/**
* Generates the base URI. Parameters will be stacked after this URI to form a query. For example, SimplePaginator
* will return something like "/r/pics/new.json"
*
* @return The base URI that will be used in queries
*/
protected abstract String getBaseUri();
/**
* How the Reddit API will choose to return the listing. If the sorting is ${@link net.dean.jraw.models.Sorting#TOP},
* then the time period will default to the last requested time period. If there was none, Reddit will use DAY.
*/
public Sorting getSorting() {
return sorting;
}
/**
* Sets the new sorting and invalidates the current listing
*
* @param sorting The new sorting
*/
public void setSorting(Sorting sorting) {
this.sorting = sorting;
invalidate();
}
/**
* The time period to get the submissions from
*
* @return The time period
*/
public TimePeriod getTimePeriod() {
return timePeriod;
}
/**
* Sets the new time period and invalidates the current time period
*
* @param timePeriod The new time period
*/
public void setTimePeriod(TimePeriod timePeriod) {
this.timePeriod = timePeriod;
invalidate();
}
/**
* Gets the maximum amount of submissions the listing will return. Default is {@value #LIMIT_DEFAULT}, maximum is
* {@value #LIMIT_MAX}.
*
* @return The maximum amount submissions returned in each call
*/
public int getLimit() {
return limit;
}
/**
* Sets the amount of posts returned by the Reddit API. Must be at least 1 and no greater than {@value #LIMIT_MAX}
*
* @param limit The new limit
*/
public void setLimit(int limit) {
if (limit > LIMIT_MAX) {
throw new IllegalArgumentException("Limit cannot be over " + LIMIT_MAX);
}
this.limit = limit;
}
/**
* Notifies {@link #getListing(boolean)} that some piece of data (such as sorting or time period) has changed, so we
* need to start over
*/
protected void invalidate() {
if (current != null)
current = null;
}
}
|
package org.nusco.narjillos.core.utilities;
import java.lang.reflect.Field;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
/**
* Generates numbers (mostly pseudo-random ones).
* <p>
* A bit like java.math.Random, but strictly deterministic. You must give it a
* seed during construction, and it will spew out the same exact numbers given
* the same sequence of calls.
* <p>
* You cannot call the same instance of this class from multiple threads,
* because multithreading and deterministic behavior don't mix. If you try,
* the NumGen will complain loudly.
*/
public class NumGen {
private final TransparentRanGen random = new TransparentRanGen();
private long serial = 0;
private transient Thread authorizedThread;
public NumGen(long seed) {
random.setSeed(seed);
authorizedThread = Thread.currentThread();
}
/**
* Returns a value between 0.0 (inclusive) and 1.0 (exclusive).
*/
public double nextDouble() {
checkThreadIsAuthorized();
return random.nextDouble();
}
public int nextInt() {
checkThreadIsAuthorized();
return random.nextInt();
}
public int nextByte() {
return Math.abs(nextInt()) % 256;
}
public long nextSerial() {
checkThreadIsAuthorized();
return ++serial;
}
public long getSeed() {
return random.getSeed();
}
private synchronized void checkThreadIsAuthorized() {
// I apologize for this slightly paranoid defensive code. Bugs with
// non-deterministic random generators are hard to find, so I have to be
// extra careful here.
if (authorizedThread == null) {
// If the RanGen has been deserialized, the authorized thread
// could still be null. In this case, the first thread that
// accesses it wins the role.
authorizedThread = Thread.currentThread();
return;
}
if (Thread.currentThread() != authorizedThread)
throw new RuntimeException("RanGen accessed from multiple threads. " + getExplanation());
}
private static String getExplanation() {
return "(Don't do that, or else there is no guarantee that the same " + "seed will generate the same sequence of numbers.)";
}
// A Random that allows you to get/set the current seed.
private static class TransparentRanGen extends Random {
private static final long serialVersionUID = 1L;
@Override
public void setSeed(long seed) {
extractSeed().set(seed);
}
long getSeed() {
return extractSeed().get();
}
private AtomicLong extractSeed() {
// Put on your gloves - this is going to be dirty.
try {
Field seedField = Random.class.getDeclaredField("seed");
seedField.setAccessible(true);
return (AtomicLong) seedField.get(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
|
package org.nustaq.offheap.bytez.onheap;
import org.nustaq.offheap.bytez.BasicBytez;
import org.nustaq.offheap.bytez.Bytez;
import org.nustaq.offheap.bytez.malloc.MallocBytez;
import org.nustaq.serialization.util.FSTUtil;
import sun.misc.Unsafe;
/**
* byte array abstraction based on heap byte arrays
*/
public class HeapBytez implements Bytez {
static Unsafe unsafe = FSTUtil.getUnsafe();
static long byteoff = FSTUtil.bufoff;
static long caoff = FSTUtil.choff;
static long saoff = FSTUtil.choff;
static long iaoff = FSTUtil.intoff;
static long laoff = FSTUtil.longoff;
static long daoff = FSTUtil.doubleoff;
static long faoff = FSTUtil.floatoff;
byte[] base;
long off;
long len;
private void checkIndex(long index, int len ) {
// if ( index >= base.length || index < off-byteoff ) {
// throw new RuntimeException("aua");
// index += len-1;
// if ( index >= base.length || index < off-byteoff ) {
// throw new RuntimeException("aua 1");
}
public HeapBytez(byte[] base) {
this(base,0);
}
public HeapBytez(byte[] base, long offIndex) {
this(base,offIndex, base.length-offIndex);
}
public HeapBytez(byte[] base, long offIndex, long len) {
setBase(base, offIndex, len);
}
public void setBase(byte[] base, long offIndex, long len) {
this.base = base;
this.off = byteoff+offIndex;
this.len = len;
}
public HeapBytez slice(long off, int len) {
if (off+len >= base.length)
throw new RuntimeException("invalid slice "+off+":"+len+" mylen:"+base.length);
return new HeapBytez(base,off,len);
}
@Override
public byte get(long byteIndex) {
checkIndex(byteIndex,1);
return unsafe.getByte(base,off+byteIndex);
}
@Override
public boolean getBool(long byteIndex) {
checkIndex(byteIndex,1);
return unsafe.getByte(base,off+byteIndex) != 0;
}
@Override
public char getChar(long byteIndex) {
checkIndex(byteIndex,2);
return unsafe.getChar(base, off + byteIndex);
}
@Override
public short getShort(long byteIndex) {
checkIndex(byteIndex,2);
return unsafe.getShort(base, off + byteIndex);
}
@Override
public int getInt(long byteIndex) {
checkIndex(byteIndex,4);
int res = unsafe.getInt(base, off + byteIndex);
return res;
}
@Override
public long getLong(long byteIndex) {
checkIndex(byteIndex,8);
return unsafe.getLong(base, off + byteIndex);
}
@Override
public float getFloat(long byteIndex) {
checkIndex(byteIndex,4);
return unsafe.getFloat(base, off + byteIndex);
}
@Override
public double getDouble(long byteIndex) {
checkIndex(byteIndex,8);
return unsafe.getDouble(base, off + byteIndex);
}
@Override
public void put(long byteIndex, byte value) {
checkIndex(byteIndex,1);
unsafe.putByte(base,off+byteIndex,value);
}
@Override
public void putBool(long byteIndex, boolean val) {
checkIndex(byteIndex,1);
put(byteIndex,(byte) (val ? 1 : 0) );
}
@Override
public void putChar(long byteIndex, char c) {
checkIndex(byteIndex,2);
unsafe.putChar(base, off + byteIndex, c);
}
@Override
public void putShort(long byteIndex, short s) {
checkIndex(byteIndex,2);
unsafe.putShort(base, off + byteIndex, s);
}
@Override
public void putInt(long byteIndex, int i) {
checkIndex(byteIndex,4);
unsafe.putInt(base, off + byteIndex, i);
}
@Override
public void putLong(long byteIndex, long l) {
checkIndex(byteIndex,8);
unsafe.putLong(base, off + byteIndex, l);
}
@Override
public void putFloat(long byteIndex, float f) {
checkIndex(byteIndex,4);
unsafe.putFloat(base, off + byteIndex, f);
}
@Override
public void putDouble(long byteIndex, double d) {
checkIndex(byteIndex,8);
unsafe.putDouble(base, off + byteIndex, d);
}
@Override
public long length() {
return len;
}
@Override
public void getArr(long byteIndex, byte[] target, int elemoff, int numElems) {
unsafe.copyMemory(base,off+byteIndex,target,off+elemoff,numElems);
}
@Override
public void getCharArr(long byteIndex, char[] target, int elemoff, int numElems) {
unsafe.copyMemory(base,off+byteIndex,target,caoff+elemoff*2+off-byteoff,numElems*2);
}
@Override
public void getShortArr(long byteIndex, short[] target, int elemoff, int numElems) {
unsafe.copyMemory(base,off+byteIndex,target,saoff+elemoff*2+off-byteoff,numElems*2);
}
@Override
public void getIntArr(long byteIndex, int[] target, int elemoff, int numElems) {
unsafe.copyMemory(base,off+byteIndex,target,iaoff+elemoff*4+off-byteoff,numElems*4);
}
@Override
public void getLongArr(long byteIndex, long[] target, int elemoff, int numElems) {
unsafe.copyMemory(base,off+byteIndex,target,laoff+elemoff*8+off-byteoff,numElems*8);
}
@Override
public void getFloatArr(long byteIndex, float[] target, int elemoff, int numElems) {
unsafe.copyMemory(base,off+byteIndex,target,faoff+elemoff*4+off-byteoff,numElems*4);
}
@Override
public void getDoubleArr(long byteIndex, double[] target, int elemoff, int numElems) {
unsafe.copyMemory(base,off+byteIndex,target,daoff+elemoff*4+off-byteoff,numElems*8);
}
@Override
public void getBooleanArr(long byteIndex, boolean[] target, int elemoff, int numElems) {
for ( int i = 0; i < numElems; i++) {
target[elemoff+i] = getBool(byteIndex+i);
}
}
@Override
public void set(long byteIndex, byte[] source, int elemoff, int numElems) {
checkIndex(byteIndex,numElems);
unsafe.copyMemory(source,off+elemoff,base,off+byteIndex,numElems);
}
@Override
public void setChar(long byteIndex, char[] source, int elemoff, int numElems) {
checkIndex(byteIndex,numElems*2);
unsafe.copyMemory(source,caoff+off-byteoff+elemoff*2,base,off+byteIndex,numElems*2);
}
@Override
public void setShort(long byteIndex, short[] source, int elemoff, int numElems) {
checkIndex(byteIndex,numElems*2);
unsafe.copyMemory(source,caoff+off-byteoff+elemoff*2,base,off+byteIndex,numElems*2);
}
@Override
public void setInt(long byteIndex, int[] source, int elemoff, int numElems) {
checkIndex(byteIndex,numElems*4);
unsafe.copyMemory(source,iaoff+off-byteoff+elemoff*4,base,off+byteIndex,numElems*4);
}
@Override
public void setLong(long byteIndex, long[] source, int elemoff, int numElems) {
checkIndex(byteIndex,numElems*8);
unsafe.copyMemory(source,laoff+off-byteoff+elemoff*8,base,off+byteIndex,numElems*8);
}
@Override
public void setFloat(long byteIndex, float[] source, int elemoff, int numElems) {
checkIndex(byteIndex,numElems*4);
unsafe.copyMemory(source,faoff+off-byteoff+elemoff*4,base,off+byteIndex,numElems*4);
}
@Override
public void setDouble(long byteIndex, double[] source, int elemoff, int numElems) {
checkIndex(byteIndex,numElems*8);
unsafe.copyMemory(source,daoff+off-byteoff+elemoff*8,base,off+byteIndex,numElems*8);
}
@Override
public void setBoolean(long byteIndex, boolean[] o, int elemoff, int numElems) {
checkIndex(byteIndex,numElems);
for ( int i = 0; i < numElems; i++) {
put(byteIndex+i, (byte) (o[i+elemoff] ? 1 : 0));
}
}
@Override
public void copyTo(BasicBytez other, long otherByteIndex, long myByteIndex, long lenBytes) {
if ( lenBytes == 0 )
return;
checkIndex(myByteIndex, (int) lenBytes);
if ( other instanceof HeapBytez) {
HeapBytez hp = (HeapBytez) other;
unsafe.copyMemory(base,off+myByteIndex,hp.base,hp.off+otherByteIndex,lenBytes);
} else if (other instanceof MallocBytez ) {
MallocBytez mb = (MallocBytez) other;
unsafe.copyMemory(base,off+myByteIndex,null,otherByteIndex+mb.getBaseAdress(),lenBytes);
} else {
for ( long i = 0; i < lenBytes; i++ ) {
other.put(otherByteIndex+i,get(myByteIndex+i));
}
}
}
@Override
public Bytez newInstance(long size) {
return new HeapBytez(new byte[(int) size]);
}
@Override
public boolean compareAndSwapInt(long offset, int expect, int newVal) {
return unsafe.compareAndSwapInt(base,off+offset,expect,newVal);
}
@Override
public boolean compareAndSwapLong(long offset, long expect, long newVal) {
return unsafe.compareAndSwapLong(base, off + offset, expect, newVal);
}
@Override
public byte[] toBytes(long startIndex, int len) {
byte res[] = new byte[len];
System.arraycopy(base, (int) (off-FSTUtil.bufoff)+(int)startIndex,res,0,len);
return res;
}
@Override
public byte[] asByteArray() {
return base;
}
/**
* @return the start index inside the byte array returned by asByteArray, not supported by MallocBytez
*/
@Override
public int getBAOffsetIndex() {
return (int) (off- FSTUtil.bufoff);
}
/**
* @return the length inside the byte array returned by asByteArray, not supported by MallocBytez
*/
@Override
public int getBALength() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public int hashCode() {
return base.hashCode();
}
@Override
public boolean equals(Object obj) {
if ( obj instanceof HeapBytez)
return base == ((HeapBytez) obj).base;
return false;
}
@Override
public boolean getBoolVolatile(long byteIndex) {
return getVolatile(byteIndex) != 0;
}
@Override
public byte getVolatile(long byteIndex) {
return unsafe.getByteVolatile(base, off + byteIndex);
}
@Override
public char getCharVolatile(long byteIndex) {
return unsafe.getCharVolatile(base, off + byteIndex);
}
@Override
public short getShortVolatile(long byteIndex) {
return unsafe.getShortVolatile(base, off + byteIndex);
}
@Override
public int getIntVolatile(long byteIndex) {
return unsafe.getIntVolatile(base, off + byteIndex);
}
@Override
public long getLongVolatile(long byteIndex) {
return unsafe.getLongVolatile(base, off + byteIndex);
}
@Override
public float getFloatVolatile(long byteIndex) {
return unsafe.getFloatVolatile(base, off + byteIndex);
}
@Override
public double getDoubleVolatile(long byteIndex) {
return unsafe.getDoubleVolatile(base, off + byteIndex);
}
@Override
public void putBoolVolatile(long byteIndex, boolean value) {
putVolatile(byteIndex, (byte) (value?1:0));
}
@Override
public void putVolatile(long byteIndex, byte value) {
unsafe.putByteVolatile(base, off + byteIndex, value);
}
@Override
public void putCharVolatile(long byteIndex, char c) {
unsafe.putCharVolatile(base, off + byteIndex, c);
}
@Override
public void putShortVolatile(long byteIndex, short s) {
unsafe.putShortVolatile(base, off + byteIndex, s);
}
@Override
public void putIntVolatile(long byteIndex, int i) {
unsafe.putIntVolatile(base, off + byteIndex, i);
}
@Override
public void putLongVolatile(long byteIndex, long l) {
unsafe.putLongVolatile(base, off + byteIndex, l);
}
@Override
public void putFloatVolatile(long byteIndex, float f) {
unsafe.putFloatVolatile(base, off + byteIndex, f);
}
@Override
public void putDoubleVolatile(long byteIndex, double d) {
unsafe.putDoubleVolatile(base, off + byteIndex, d);
}
public byte[] getBase() {
return base;
}
/**
* @return offset to byte array INCLUDING native bytearray header
*/
public long getOff() {
return off;
}
/**
* @return offset to byte array EXCLUDING native bytearray header
*/
public long getOffsetIndex() {
return off-byteoff;
}
}
|
package org.b3log.symphony.processor;
import com.qiniu.util.Auth;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.ioc.inject.Inject;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.model.User;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.After;
import org.b3log.latke.servlet.annotation.Before;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer;
import org.b3log.latke.util.CollectionUtils;
import org.b3log.latke.util.Paginator;
import org.b3log.latke.util.Requests;
import org.b3log.latke.util.Strings;
import org.b3log.symphony.model.*;
import org.b3log.symphony.processor.advice.*;
import org.b3log.symphony.processor.advice.stopwatch.StopwatchEndAdvice;
import org.b3log.symphony.processor.advice.stopwatch.StopwatchStartAdvice;
import org.b3log.symphony.processor.advice.validate.*;
import org.b3log.symphony.service.*;
import org.b3log.symphony.util.*;
import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
@RequestProcessor
public class UserProcessor {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(UserProcessor.class);
/**
* User management service.
*/
@Inject
private UserMgmtService userMgmtService;
/**
* Article management service.
*/
@Inject
private ArticleQueryService articleQueryService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* Comment query service.
*/
@Inject
private CommentQueryService commentQueryService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Follow query service.
*/
@Inject
private FollowQueryService followQueryService;
/**
* Emotion query service.
*/
@Inject
private EmotionQueryService emotionQueryService;
/**
* Emotion management service.
*/
@Inject
private EmotionMgmtService emotionMgmtService;
/**
* Data model service.
*/
@Inject
private DataModelService dataModelService;
/**
* Avatar query service.
*/
@Inject
private AvatarQueryService avatarQueryService;
/**
* Pointtransfer query service.
*/
@Inject
private PointtransferQueryService pointtransferQueryService;
/**
* Pointtransfer management service.
*/
@Inject
private PointtransferMgmtService pointtransferMgmtService;
/**
* Notification management service.
*/
@Inject
private NotificationMgmtService notificationMgmtService;
/**
* Post export service.
*/
@Inject
private PostExportService postExportService;
/**
* Option query service.
*/
@Inject
private OptionQueryService optionQueryService;
/**
* Invitecode management service.
*/
@Inject
private InvitecodeMgmtService invitecodeMgmtService;
/**
* Invitecode query service.
*/
@Inject
private InvitecodeQueryService invitecodeQueryService;
/**
* Link forge query service.
*/
@Inject
private LinkForgeQueryService linkForgeQueryService;
/**
* Role query service.
*/
@Inject
private RoleQueryService roleQueryService;
/**
* Updates user i18n.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
*/
@RequestProcessing(value = "/settings/i18n", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class})
public void updateI18n(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) {
context.renderJSON();
JSONObject requestJSONObject;
try {
requestJSONObject = Requests.parseRequestJSONObject(request, response);
request.setAttribute(Keys.REQUEST, requestJSONObject);
} catch (final Exception e) {
LOGGER.warn(e.getMessage());
requestJSONObject = new JSONObject();
}
String userLanguage = requestJSONObject.optString(UserExt.USER_LANGUAGE, Locale.SIMPLIFIED_CHINESE.toString());
if (!Languages.getAvailableLanguages().contains(userLanguage)) {
userLanguage = Locale.US.toString();
}
String userTimezone = requestJSONObject.optString(UserExt.USER_TIMEZONE, TimeZone.getDefault().getID());
if (!Arrays.asList(TimeZone.getAvailableIDs()).contains(userTimezone)) {
userTimezone = TimeZone.getDefault().getID();
}
try {
final JSONObject user = userQueryService.getCurrentUser(request);
user.put(UserExt.USER_LANGUAGE, userLanguage);
user.put(UserExt.USER_TIMEZONE, userTimezone);
userMgmtService.updateUser(user.optString(Keys.OBJECT_ID), user);
context.renderTrueResult();
} catch (final ServiceException e) {
context.renderMsg(e.getMessage());
}
}
/**
* Shows user link forge.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}/forge/link", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showLinkForge(final HTTPRequestContext context, final HttpServletRequest request,
final HttpServletResponse response, final String userName) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("/home/link-forge.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
fillHomeUser(dataModel, user);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
if (isLoggedIn) {
final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
}
final List<JSONObject> tags = linkForgeQueryService.getUserForgedLinks(user.optString(Keys.OBJECT_ID));
dataModel.put(Tag.TAGS, (Object) tags);
dataModel.put(Common.TYPE, "linkForge");
}
/**
* Queries invitecode state.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/invitecode/state", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class})
public void queryInvitecode(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final JSONObject ret = Results.falseResult();
context.renderJSON(ret);
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, context.getResponse());
String invitecode = requestJSONObject.optString(Invitecode.INVITECODE);
if (StringUtils.isBlank(invitecode)) {
ret.put(Keys.STATUS_CODE, -1);
ret.put(Keys.MSG, invitecode + " " + langPropsService.get("notFoundInvitecodeLabel"));
return;
}
invitecode = invitecode.trim();
final JSONObject result = invitecodeQueryService.getInvitecode(invitecode);
if (null == result) {
ret.put(Keys.STATUS_CODE, -1);
ret.put(Keys.MSG, langPropsService.get("notFoundInvitecodeLabel"));
} else {
final int status = result.optInt(Invitecode.STATUS);
ret.put(Keys.STATUS_CODE, status);
switch (status) {
case Invitecode.STATUS_C_USED:
ret.put(Keys.MSG, langPropsService.get("invitecodeUsedLabel"));
break;
case Invitecode.STATUS_C_UNUSED:
String msg = langPropsService.get("invitecodeOkLabel");
msg = msg.replace("${time}", DateFormatUtils.format(result.optLong(Keys.OBJECT_ID)
+ Symphonys.getLong("invitecode.expired"), "yyyy-MM-dd HH:mm"));
ret.put(Keys.MSG, msg);
break;
case Invitecode.STATUS_C_STOPUSE:
ret.put(Keys.MSG, langPropsService.get("invitecodeStopLabel"));
break;
default:
ret.put(Keys.MSG, langPropsService.get("notFoundInvitecodeLabel"));
}
}
}
/**
* Point buy invitecode.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/point/buy-invitecode", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class, PermissionCheck.class})
public void pointBuy(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final JSONObject ret = Results.falseResult();
context.renderJSON(ret);
final String allowRegister = optionQueryService.getAllowRegister();
if (!"2".equals(allowRegister)) {
return;
}
final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
final String fromId = currentUser.optString(Keys.OBJECT_ID);
final String userName = currentUser.optString(User.USER_NAME);
final String invitecode = invitecodeMgmtService.userGenInvitecode(fromId, userName);
final String transferId = pointtransferMgmtService.transfer(fromId, Pointtransfer.ID_C_SYS,
Pointtransfer.TRANSFER_TYPE_C_BUY_INVITECODE, Pointtransfer.TRANSFER_SUM_C_BUY_INVITECODE,
invitecode, System.currentTimeMillis());
final boolean succ = null != transferId;
ret.put(Keys.STATUS_CODE, succ);
if (!succ) {
ret.put(Keys.MSG, langPropsService.get("exchangeFailedLabel"));
} else {
String msg = langPropsService.get("expireTipLabel");
msg = msg.replace("${time}", DateFormatUtils.format(System.currentTimeMillis()
+ Symphonys.getLong("invitecode.expired"), "yyyy-MM-dd HH:mm"));
ret.put(Keys.MSG, invitecode + " " + msg);
}
}
/**
* Shows settings pages.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
/**
* Shows user home anonymous comments page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}/comments/anonymous", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHomeAnonymousComments(final HTTPRequestContext context, final HttpServletRequest request,
final HttpServletResponse response, final String userName) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("/home/comments.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
JSONObject currentUser = null;
if (isLoggedIn) {
currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
}
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
if (null == currentUser || (!currentUser.optString(Keys.OBJECT_ID).equals(user.optString(Keys.OBJECT_ID)))
&& !Role.ROLE_ID_C_ADMIN.equals(currentUser.optString(User.USER_ROLE))) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
final int pageSize = Symphonys.getInt("userHomeCmtsCnt");
final int windowSize = Symphonys.getInt("userHomeCmtsWindowSize");
fillHomeUser(dataModel, user);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
if (isLoggedIn) {
currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
}
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
final List<JSONObject> userComments = commentQueryService.getUserComments(
avatarViewMode, user.optString(Keys.OBJECT_ID), Comment.COMMENT_ANONYMOUS_C_ANONYMOUS,
pageNum, pageSize, currentUser);
dataModel.put(Common.USER_HOME_COMMENTS, userComments);
int recordCount = 0;
int pageCount = 0;
if (!userComments.isEmpty()) {
final JSONObject first = userComments.get(0);
pageCount = first.optInt(Pagination.PAGINATION_PAGE_COUNT);
recordCount = first.optInt(Pagination.PAGINATION_RECORD_COUNT);
}
final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModel.put(Pagination.PAGINATION_RECORD_COUNT, recordCount);
dataModel.put(Common.TYPE, "commentsAnonymous");
}
/**
* Shows user home anonymous articles page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}/articles/anonymous", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showAnonymousArticles(final HTTPRequestContext context, final HttpServletRequest request,
final HttpServletResponse response, final String userName) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("/home/home.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
JSONObject currentUser = null;
if (isLoggedIn) {
currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
}
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
if (null == currentUser || (!currentUser.optString(Keys.OBJECT_ID).equals(user.optString(Keys.OBJECT_ID)))
&& !Role.ROLE_ID_C_ADMIN.equals(currentUser.optString(User.USER_ROLE))) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
dataModel.put(User.USER, user);
fillHomeUser(dataModel, user);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
if (isLoggedIn) {
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
}
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
final int pageSize = Symphonys.getInt("userHomeArticlesCnt");
final int windowSize = Symphonys.getInt("userHomeArticlesWindowSize");
final List<JSONObject> userArticles = articleQueryService.getUserArticles(avatarViewMode,
user.optString(Keys.OBJECT_ID), Article.ARTICLE_ANONYMOUS_C_ANONYMOUS, pageNum, pageSize);
dataModel.put(Common.USER_HOME_ARTICLES, userArticles);
int recordCount = 0;
int pageCount = 0;
if (!userArticles.isEmpty()) {
final JSONObject first = userArticles.get(0);
pageCount = first.optInt(Pagination.PAGINATION_PAGE_COUNT);
recordCount = first.optInt(Pagination.PAGINATION_RECORD_COUNT);
}
final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModel.put(Pagination.PAGINATION_RECORD_COUNT, recordCount);
dataModel.put(Common.IS_MY_ARTICLE, userName.equals(currentUser.optString(User.USER_NAME)));
dataModel.put(Common.TYPE, "articlesAnonymous");
}
/**
* Exports posts(article/comment) to a file.
*
* @param context the specified context
* @param request the specified request
*/
@RequestProcessing(value = "/export/posts", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class})
public void exportPosts(final HTTPRequestContext context, final HttpServletRequest request) {
context.renderJSON();
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
final String userId = user.optString(Keys.OBJECT_ID);
final String downloadURL = postExportService.exportPosts(userId);
if ("-1".equals(downloadURL)) {
context.renderJSONValue(Keys.MSG, langPropsService.get("insufficientBalanceLabel"));
} else if (StringUtils.isBlank(downloadURL)) {
return;
}
context.renderJSON(true).renderJSONValue("url", downloadURL);
}
/**
* Shows user home page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHome(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response,
final String userName) throws Exception {
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
int pageNum = 1;
try {
pageNum = Integer.valueOf(pageNumStr);
} catch (final Exception e) {
pageNum = 1;
}
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
renderer.setTemplateName("/home/home.ftl");
dataModel.put(User.USER, user);
fillHomeUser(dataModel, user);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
if (isLoggedIn) {
final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
}
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
final int pageSize = Symphonys.getInt("userHomeArticlesCnt");
final int windowSize = Symphonys.getInt("userHomeArticlesWindowSize");
final List<JSONObject> userArticles = articleQueryService.getUserArticles(avatarViewMode,
user.optString(Keys.OBJECT_ID), Article.ARTICLE_ANONYMOUS_C_PUBLIC, pageNum, pageSize);
dataModel.put(Common.USER_HOME_ARTICLES, userArticles);
int recordCount = 0;
int pageCount = 0;
if (!userArticles.isEmpty()) {
final JSONObject first = userArticles.get(0);
pageCount = first.optInt(Pagination.PAGINATION_PAGE_COUNT);
recordCount = first.optInt(Pagination.PAGINATION_RECORD_COUNT);
}
final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModel.put(Pagination.PAGINATION_RECORD_COUNT, recordCount);
final JSONObject currentUser = Sessions.currentUser(request);
if (null == currentUser) {
dataModel.put(Common.IS_MY_ARTICLE, false);
} else {
dataModel.put(Common.IS_MY_ARTICLE, userName.equals(currentUser.optString(User.USER_NAME)));
}
dataModel.put(Common.TYPE, "home");
}
/**
* Shows user home comments page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}/comments", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHomeComments(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response,
final String userName) throws Exception {
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("/home/comments.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
final int pageSize = Symphonys.getInt("userHomeCmtsCnt");
final int windowSize = Symphonys.getInt("userHomeCmtsWindowSize");
fillHomeUser(dataModel, user);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
JSONObject currentUser = null;
if (isLoggedIn) {
currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
}
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
final List<JSONObject> userComments = commentQueryService.getUserComments(avatarViewMode,
user.optString(Keys.OBJECT_ID), Comment.COMMENT_ANONYMOUS_C_PUBLIC, pageNum, pageSize, currentUser);
dataModel.put(Common.USER_HOME_COMMENTS, userComments);
int recordCount = 0;
int pageCount = 0;
if (!userComments.isEmpty()) {
final JSONObject first = userComments.get(0);
pageCount = first.optInt(Pagination.PAGINATION_PAGE_COUNT);
recordCount = first.optInt(Pagination.PAGINATION_RECORD_COUNT);
}
final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModel.put(Pagination.PAGINATION_RECORD_COUNT, recordCount);
dataModel.put(Common.TYPE, "comments");
}
/**
* Shows user home following users page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}/following/users", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHomeFollowingUsers(final HTTPRequestContext context, final HttpServletRequest request,
final HttpServletResponse response, final String userName) throws Exception {
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("/home/following-users.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
final int pageSize = Symphonys.getInt("userHomeFollowingUsersCnt");
final int windowSize = Symphonys.getInt("userHomeFollowingUsersWindowSize");
fillHomeUser(dataModel, user);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
final JSONObject followingUsersResult = followQueryService.getFollowingUsers(avatarViewMode,
followingId, pageNum, pageSize);
final List<JSONObject> followingUsers = (List<JSONObject>) followingUsersResult.opt(Keys.RESULTS);
dataModel.put(Common.USER_HOME_FOLLOWING_USERS, followingUsers);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
if (isLoggedIn) {
final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
for (final JSONObject followingUser : followingUsers) {
final String homeUserFollowingUserId = followingUser.optString(Keys.OBJECT_ID);
followingUser.put(Common.IS_FOLLOWING, followQueryService.isFollowing(followerId, homeUserFollowingUserId, Follow.FOLLOWING_TYPE_C_USER));
}
}
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
final int followingUserCnt = followingUsersResult.optInt(Pagination.PAGINATION_RECORD_COUNT);
final int pageCount = (int) Math.ceil((double) followingUserCnt / (double) pageSize);
final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModel.put(Pagination.PAGINATION_RECORD_COUNT, followingUserCnt);
dataModel.put(Common.TYPE, "followingUsers");
}
/**
* Shows user home following tags page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}/following/tags", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHomeFollowingTags(final HTTPRequestContext context, final HttpServletRequest request,
final HttpServletResponse response, final String userName) throws Exception {
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("/home/following-tags.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
final int pageSize = Symphonys.getInt("userHomeFollowingTagsCnt");
final int windowSize = Symphonys.getInt("userHomeFollowingTagsWindowSize");
fillHomeUser(dataModel, user);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
final JSONObject followingTagsResult = followQueryService.getFollowingTags(followingId, pageNum, pageSize);
final List<JSONObject> followingTags = (List<JSONObject>) followingTagsResult.opt(Keys.RESULTS);
dataModel.put(Common.USER_HOME_FOLLOWING_TAGS, followingTags);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
if (isLoggedIn) {
final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
for (final JSONObject followingTag : followingTags) {
final String homeUserFollowingTagId = followingTag.optString(Keys.OBJECT_ID);
followingTag.put(Common.IS_FOLLOWING, followQueryService.isFollowing(followerId, homeUserFollowingTagId, Follow.FOLLOWING_TYPE_C_TAG));
}
}
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
final int followingTagCnt = followingTagsResult.optInt(Pagination.PAGINATION_RECORD_COUNT);
final int pageCount = (int) Math.ceil(followingTagCnt / (double) pageSize);
final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModel.put(Pagination.PAGINATION_RECORD_COUNT, followingTagCnt);
dataModel.put(Common.TYPE, "followingTags");
}
/**
* Shows user home following articles page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}/following/articles", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHomeFollowingArticles(final HTTPRequestContext context, final HttpServletRequest request,
final HttpServletResponse response, final String userName) throws Exception {
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("/home/following-articles.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
final int pageSize = Symphonys.getInt("userHomeFollowingArticlesCnt");
final int windowSize = Symphonys.getInt("userHomeFollowingArticlesWindowSize");
fillHomeUser(dataModel, user);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
final JSONObject followingArticlesResult = followQueryService.getFollowingArticles(avatarViewMode,
followingId, pageNum, pageSize);
final List<JSONObject> followingArticles = (List<JSONObject>) followingArticlesResult.opt(Keys.RESULTS);
dataModel.put(Common.USER_HOME_FOLLOWING_ARTICLES, followingArticles);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
if (isLoggedIn) {
final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
for (final JSONObject followingArticle : followingArticles) {
final String homeUserFollowingArticleId = followingArticle.optString(Keys.OBJECT_ID);
followingArticle.put(Common.IS_FOLLOWING, followQueryService.isFollowing(followerId, homeUserFollowingArticleId, Follow.FOLLOWING_TYPE_C_ARTICLE));
}
}
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
final int followingArticleCnt = followingArticlesResult.optInt(Pagination.PAGINATION_RECORD_COUNT);
final int pageCount = (int) Math.ceil(followingArticleCnt / (double) pageSize);
final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModel.put(Pagination.PAGINATION_RECORD_COUNT, followingArticleCnt);
dataModel.put(Common.TYPE, "followingArticles");
}
/**
* Shows user home watching articles page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}/watching/articles", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHomeWatchingArticles(final HTTPRequestContext context, final HttpServletRequest request,
final HttpServletResponse response, final String userName) throws Exception {
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("/home/watching-articles.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
final int pageSize = Symphonys.getInt("userHomeFollowingArticlesCnt");
final int windowSize = Symphonys.getInt("userHomeFollowingArticlesWindowSize");
fillHomeUser(dataModel, user);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
final JSONObject followingArticlesResult = followQueryService.getWatchingArticles(avatarViewMode,
followingId, pageNum, pageSize);
final List<JSONObject> followingArticles = (List<JSONObject>) followingArticlesResult.opt(Keys.RESULTS);
dataModel.put(Common.USER_HOME_FOLLOWING_ARTICLES, followingArticles);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
if (isLoggedIn) {
final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
for (final JSONObject followingArticle : followingArticles) {
final String homeUserFollowingArticleId = followingArticle.optString(Keys.OBJECT_ID);
followingArticle.put(Common.IS_FOLLOWING, followQueryService.isFollowing(followerId, homeUserFollowingArticleId, Follow.FOLLOWING_TYPE_C_ARTICLE_WATCH));
}
}
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
final int followingArticleCnt = followingArticlesResult.optInt(Pagination.PAGINATION_RECORD_COUNT);
final int pageCount = (int) Math.ceil(followingArticleCnt / (double) pageSize);
final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModel.put(Pagination.PAGINATION_RECORD_COUNT, followingArticleCnt);
dataModel.put(Common.TYPE, "watchingArticles");
}
/**
* Shows user home follower users page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}/followers", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHomeFollowers(final HTTPRequestContext context, final HttpServletRequest request,
final HttpServletResponse response, final String userName) throws Exception {
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("/home/followers.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
final int pageSize = Symphonys.getInt("userHomeFollowersCnt");
final int windowSize = Symphonys.getInt("userHomeFollowersWindowSize");
fillHomeUser(dataModel, user);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
final JSONObject followerUsersResult = followQueryService.getFollowerUsers(avatarViewMode,
followingId, pageNum, pageSize);
final List<JSONObject> followerUsers = (List) followerUsersResult.opt(Keys.RESULTS);
dataModel.put(Common.USER_HOME_FOLLOWER_USERS, followerUsers);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
if (isLoggedIn) {
final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, followingId, Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
for (final JSONObject followerUser : followerUsers) {
final String homeUserFollowerUserId = followerUser.optString(Keys.OBJECT_ID);
followerUser.put(Common.IS_FOLLOWING, followQueryService.isFollowing(followerId, homeUserFollowerUserId, Follow.FOLLOWING_TYPE_C_USER));
}
if (followerId.equals(followingId)) {
notificationMgmtService.makeRead(followingId, Notification.DATA_TYPE_C_NEW_FOLLOWER);
}
}
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
final int followerUserCnt = followerUsersResult.optInt(Pagination.PAGINATION_RECORD_COUNT);
final int pageCount = (int) Math.ceil((double) followerUserCnt / (double) pageSize);
final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModel.put(Pagination.PAGINATION_RECORD_COUNT, followerUserCnt);
dataModel.put(Common.TYPE, "followers");
notificationMgmtService.makeRead(followingId, Notification.DATA_TYPE_C_NEW_FOLLOWER);
}
/**
* Shows user home points page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param userName the specified user name
* @throws Exception exception
*/
@RequestProcessing(value = "/member/{userName}/points", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class, UserBlockCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHomePoints(final HTTPRequestContext context, final HttpServletRequest request,
final HttpServletResponse response, final String userName) throws Exception {
final JSONObject user = (JSONObject) request.getAttribute(User.USER);
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("/home/points.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
final int pageSize = Symphonys.getInt("userHomePointsCnt");
final int windowSize = Symphonys.getInt("userHomePointsWindowSize");
fillHomeUser(dataModel, user);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
final String followingId = user.optString(Keys.OBJECT_ID);
dataModel.put(Follow.FOLLOWING_ID, followingId);
final JSONObject userPointsResult
= pointtransferQueryService.getUserPoints(user.optString(Keys.OBJECT_ID), pageNum, pageSize);
final List<JSONObject> userPoints
= CollectionUtils.<JSONObject>jsonArrayToList(userPointsResult.optJSONArray(Keys.RESULTS));
dataModel.put(Common.USER_HOME_POINTS, userPoints);
final boolean isLoggedIn = (Boolean) dataModel.get(Common.IS_LOGGED_IN);
if (isLoggedIn) {
final JSONObject currentUser = (JSONObject) dataModel.get(Common.CURRENT_USER);
final String followerId = currentUser.optString(Keys.OBJECT_ID);
final boolean isFollowing = followQueryService.isFollowing(followerId, user.optString(Keys.OBJECT_ID), Follow.FOLLOWING_TYPE_C_USER);
dataModel.put(Common.IS_FOLLOWING, isFollowing);
}
user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
final int pointsCnt = userPointsResult.optInt(Pagination.PAGINATION_RECORD_COUNT);
final int pageCount = (int) Math.ceil((double) pointsCnt / (double) pageSize);
final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, windowSize);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModel.put(Common.TYPE, "points");
}
/**
* Updates user geo status.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
*/
@RequestProcessing(value = "/settings/geo/status", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class})
public void updateGeoStatus(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) {
context.renderJSON();
JSONObject requestJSONObject;
try {
requestJSONObject = Requests.parseRequestJSONObject(request, response);
request.setAttribute(Keys.REQUEST, requestJSONObject);
} catch (final Exception e) {
LOGGER.warn(e.getMessage());
requestJSONObject = new JSONObject();
}
int geoStatus = requestJSONObject.optInt(UserExt.USER_GEO_STATUS);
if (UserExt.USER_GEO_STATUS_C_PRIVATE != geoStatus && UserExt.USER_GEO_STATUS_C_PUBLIC != geoStatus) {
geoStatus = UserExt.USER_GEO_STATUS_C_PUBLIC;
}
try {
final JSONObject user = userQueryService.getCurrentUser(request);
user.put(UserExt.USER_GEO_STATUS, geoStatus);
userMgmtService.updateUser(user.optString(Keys.OBJECT_ID), user);
context.renderTrueResult();
} catch (final ServiceException e) {
context.renderMsg(e.getMessage());
}
}
/**
* Updates user privacy.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/settings/privacy", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class})
public void updatePrivacy(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
context.renderJSON();
JSONObject requestJSONObject;
try {
requestJSONObject = Requests.parseRequestJSONObject(request, response);
request.setAttribute(Keys.REQUEST, requestJSONObject);
} catch (final Exception e) {
LOGGER.warn(e.getMessage());
requestJSONObject = new JSONObject();
}
final boolean articleStatus = requestJSONObject.optBoolean(UserExt.USER_ARTICLE_STATUS);
final boolean commentStatus = requestJSONObject.optBoolean(UserExt.USER_COMMENT_STATUS);
final boolean followingUserStatus = requestJSONObject.optBoolean(UserExt.USER_FOLLOWING_USER_STATUS);
final boolean followingTagStatus = requestJSONObject.optBoolean(UserExt.USER_FOLLOWING_TAG_STATUS);
final boolean followingArticleStatus = requestJSONObject.optBoolean(UserExt.USER_FOLLOWING_ARTICLE_STATUS);
final boolean watchingArticleStatus = requestJSONObject.optBoolean(UserExt.USER_WATCHING_ARTICLE_STATUS);
final boolean followerStatus = requestJSONObject.optBoolean(UserExt.USER_FOLLOWER_STATUS);
final boolean pointStatus = requestJSONObject.optBoolean(UserExt.USER_POINT_STATUS);
final boolean onlineStatus = requestJSONObject.optBoolean(UserExt.USER_ONLINE_STATUS);
final boolean timelineStatus = requestJSONObject.optBoolean(UserExt.USER_TIMELINE_STATUS);
final boolean uaStatus = requestJSONObject.optBoolean(UserExt.USER_UA_STATUS);
final boolean userForgeLinkStatus = requestJSONObject.optBoolean(UserExt.USER_FORGE_LINK_STATUS);
final boolean userJoinPointRank = requestJSONObject.optBoolean(UserExt.USER_JOIN_POINT_RANK);
final boolean userJoinUsedPointRank = requestJSONObject.optBoolean(UserExt.USER_JOIN_USED_POINT_RANK);
final JSONObject user = userQueryService.getCurrentUser(request);
user.put(UserExt.USER_ONLINE_STATUS, onlineStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_ARTICLE_STATUS, articleStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_COMMENT_STATUS, commentStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_FOLLOWING_USER_STATUS, followingUserStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_FOLLOWING_TAG_STATUS, followingTagStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_FOLLOWING_ARTICLE_STATUS, followingArticleStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_WATCHING_ARTICLE_STATUS, watchingArticleStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_FOLLOWER_STATUS, followerStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_POINT_STATUS, pointStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_TIMELINE_STATUS, timelineStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_UA_STATUS, uaStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
user.put(UserExt.USER_JOIN_POINT_RANK, userJoinPointRank
? UserExt.USER_JOIN_POINT_RANK_C_JOIN : UserExt.USER_JOIN_POINT_RANK_C_NOT_JOIN);
user.put(UserExt.USER_JOIN_USED_POINT_RANK, userJoinUsedPointRank
? UserExt.USER_JOIN_USED_POINT_RANK_C_JOIN : UserExt.USER_JOIN_USED_POINT_RANK_C_NOT_JOIN);
user.put(UserExt.USER_FORGE_LINK_STATUS, userForgeLinkStatus
? UserExt.USER_XXX_STATUS_C_PUBLIC : UserExt.USER_XXX_STATUS_C_PRIVATE);
try {
userMgmtService.updateUser(user.optString(Keys.OBJECT_ID), user);
context.renderTrueResult();
} catch (final ServiceException e) {
context.renderMsg(e.getMessage());
}
}
/**
* Updates user function.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/settings/function", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class})
public void updateFunction(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
context.renderJSON();
JSONObject requestJSONObject;
try {
requestJSONObject = Requests.parseRequestJSONObject(request, response);
request.setAttribute(Keys.REQUEST, requestJSONObject);
} catch (final Exception e) {
LOGGER.warn(e.getMessage());
requestJSONObject = new JSONObject();
}
String userListPageSizeStr = requestJSONObject.optString(UserExt.USER_LIST_PAGE_SIZE);
final int userCommentViewMode = requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE);
final int userAvatarViewMode = requestJSONObject.optInt(UserExt.USER_AVATAR_VIEW_MODE);
final boolean notifyStatus = requestJSONObject.optBoolean(UserExt.USER_NOTIFY_STATUS);
final boolean subMailStatus = requestJSONObject.optBoolean(UserExt.USER_SUB_MAIL_STATUS);
final boolean keyboardShortcutsStatus = requestJSONObject.optBoolean(UserExt.USER_KEYBOARD_SHORTCUTS_STATUS);
int userListPageSize;
try {
userListPageSize = Integer.valueOf(userListPageSizeStr);
if (10 > userListPageSize) {
userListPageSize = 10;
}
if (userListPageSize > 30) {
userListPageSize = 30;
}
} catch (final Exception e) {
userListPageSize = Symphonys.getInt("indexArticlesCnt");
}
final JSONObject user = userQueryService.getCurrentUser(request);
user.put(UserExt.USER_LIST_PAGE_SIZE, userListPageSize);
user.put(UserExt.USER_COMMENT_VIEW_MODE, userCommentViewMode);
user.put(UserExt.USER_AVATAR_VIEW_MODE, userAvatarViewMode);
user.put(UserExt.USER_NOTIFY_STATUS, notifyStatus
? UserExt.USER_XXX_STATUS_C_ENABLED : UserExt.USER_XXX_STATUS_C_DISABLED);
user.put(UserExt.USER_SUB_MAIL_STATUS, subMailStatus
? UserExt.USER_XXX_STATUS_C_ENABLED : UserExt.USER_XXX_STATUS_C_DISABLED);
user.put(UserExt.USER_KEYBOARD_SHORTCUTS_STATUS, keyboardShortcutsStatus
? UserExt.USER_XXX_STATUS_C_ENABLED : UserExt.USER_XXX_STATUS_C_DISABLED);
try {
userMgmtService.updateUser(user.optString(Keys.OBJECT_ID), user);
context.renderTrueResult();
} catch (final ServiceException e) {
context.renderMsg(e.getMessage());
}
}
/**
* Updates user profiles.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/settings/profiles", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class, UpdateProfilesValidation.class})
public void updateProfiles(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
context.renderJSON();
final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
final String userTags = requestJSONObject.optString(UserExt.USER_TAGS);
final String userURL = requestJSONObject.optString(User.USER_URL);
final String userQQ = requestJSONObject.optString(UserExt.USER_QQ);
final String userIntro = requestJSONObject.optString(UserExt.USER_INTRO);
final String userNickname = requestJSONObject.optString(UserExt.USER_NICKNAME);
final JSONObject user = userQueryService.getCurrentUser(request);
user.put(UserExt.USER_TAGS, userTags);
user.put(User.USER_URL, userURL);
user.put(UserExt.USER_QQ, userQQ);
user.put(UserExt.USER_INTRO, userIntro.replace("<", "<").replace(">", ">"));
user.put(UserExt.USER_NICKNAME, userNickname.replace("<", "<").replace(">", ">"));
user.put(UserExt.USER_AVATAR_TYPE, UserExt.USER_AVATAR_TYPE_C_UPLOAD);
try {
userMgmtService.updateProfiles(user);
context.renderTrueResult();
} catch (final ServiceException e) {
context.renderMsg(e.getMessage());
}
}
/**
* Updates user avatar.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/settings/avatar", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class, UpdateProfilesValidation.class})
public void updateAvatar(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
context.renderJSON();
final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
final String userAvatarURL = requestJSONObject.optString(UserExt.USER_AVATAR_URL);
final long now = System.currentTimeMillis();
final JSONObject user = userQueryService.getCurrentUser(request);
user.put(UserExt.USER_AVATAR_TYPE, UserExt.USER_AVATAR_TYPE_C_UPLOAD);
user.put(UserExt.USER_UPDATE_TIME, System.currentTimeMillis());
if (Symphonys.getBoolean("qiniu.enabled")) {
final String qiniuDomain = Symphonys.get("qiniu.domain");
if (!StringUtils.startsWith(userAvatarURL, qiniuDomain)) {
user.put(UserExt.USER_AVATAR_URL, Symphonys.get("defaultThumbnailURL"));
} else {
user.put(UserExt.USER_AVATAR_URL, userAvatarURL);
}
} else {
user.put(UserExt.USER_AVATAR_URL, userAvatarURL);
}
try {
userMgmtService.updateUser(user.optString(Keys.OBJECT_ID), user);
context.renderTrueResult();
} catch (final ServiceException e) {
context.renderMsg(e.getMessage());
}
}
/**
* Point transfer.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/point/transfer", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class, PointTransferValidation.class})
public void pointTransfer(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final JSONObject ret = Results.falseResult();
context.renderJSON(ret);
final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
final int amount = requestJSONObject.optInt(Common.AMOUNT);
final JSONObject toUser = (JSONObject) request.getAttribute(Common.TO_USER);
final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
final String fromId = currentUser.optString(Keys.OBJECT_ID);
final String toId = toUser.optString(Keys.OBJECT_ID);
final String transferId = pointtransferMgmtService.transfer(fromId, toId,
Pointtransfer.TRANSFER_TYPE_C_ACCOUNT2ACCOUNT, amount, toId, System.currentTimeMillis());
final boolean succ = null != transferId;
ret.put(Keys.STATUS_CODE, succ);
if (!succ) {
ret.put(Keys.MSG, langPropsService.get("transferFailLabel"));
} else {
final JSONObject notification = new JSONObject();
notification.put(Notification.NOTIFICATION_USER_ID, toId);
notification.put(Notification.NOTIFICATION_DATA_ID, transferId);
notificationMgmtService.addPointTransferNotification(notification);
}
}
/**
* Updates user B3log sync.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/settings/sync/b3", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class, UpdateSyncB3Validation.class})
public void updateSyncB3(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
context.renderJSON();
final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
final String b3Key = requestJSONObject.optString(UserExt.USER_B3_KEY);
final String addArticleURL = requestJSONObject.optString(UserExt.USER_B3_CLIENT_ADD_ARTICLE_URL);
final String updateArticleURL = requestJSONObject.optString(UserExt.USER_B3_CLIENT_UPDATE_ARTICLE_URL);
final String addCommentURL = requestJSONObject.optString(UserExt.USER_B3_CLIENT_ADD_COMMENT_URL);
final boolean syncWithSymphonyClient = requestJSONObject.optBoolean(UserExt.SYNC_TO_CLIENT, false);
final JSONObject user = userQueryService.getCurrentUser(request);
user.put(UserExt.USER_B3_KEY, b3Key);
user.put(UserExt.USER_B3_CLIENT_ADD_ARTICLE_URL, addArticleURL);
user.put(UserExt.USER_B3_CLIENT_UPDATE_ARTICLE_URL, updateArticleURL);
user.put(UserExt.USER_B3_CLIENT_ADD_COMMENT_URL, addCommentURL);
user.put(UserExt.SYNC_TO_CLIENT, syncWithSymphonyClient);
try {
userMgmtService.updateSyncB3(user);
context.renderTrueResult();
} catch (final ServiceException e) {
final String msg = langPropsService.get("updateFailLabel") + " - " + e.getMessage();
LOGGER.log(Level.ERROR, msg, e);
context.renderMsg(msg);
}
}
/**
* Updates user password.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/settings/password", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class, UpdatePasswordValidation.class})
public void updatePassword(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
context.renderJSON();
final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
final String password = requestJSONObject.optString(User.USER_PASSWORD);
final String newPassword = requestJSONObject.optString(User.USER_NEW_PASSWORD);
final JSONObject user = userQueryService.getCurrentUser(request);
if (!password.equals(user.optString(User.USER_PASSWORD))) {
context.renderMsg(langPropsService.get("invalidOldPwdLabel"));
return;
}
user.put(User.USER_PASSWORD, newPassword);
try {
userMgmtService.updatePassword(user);
context.renderTrueResult();
} catch (final ServiceException e) {
final String msg = langPropsService.get("updateFailLabel") + " - " + e.getMessage();
LOGGER.log(Level.ERROR, msg, e);
context.renderMsg(msg);
}
}
/**
* Updates user emotions.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/settings/emotionList", method = HTTPRequestMethod.POST)
@Before(adviceClass = {LoginCheck.class, CSRFCheck.class, UpdateEmotionListValidation.class})
public void updateEmoji(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
context.renderJSON();
final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);
final String emotionList = requestJSONObject.optString(Emotion.EMOTIONS);
final JSONObject user = userQueryService.getCurrentUser(request);
try {
emotionMgmtService.setEmotionList(user.optString(Keys.OBJECT_ID), emotionList);
context.renderTrueResult();
} catch (final ServiceException e) {
final String msg = langPropsService.get("updateFailLabel") + " - " + e.getMessage();
LOGGER.log(Level.ERROR, msg, e);
context.renderMsg(msg);
}
}
/**
* Resets unverified users.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/cron/users/reset-unverified", method = HTTPRequestMethod.GET)
public void resetUnverifiedUsers(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final String key = Symphonys.get("keyOfSymphony");
if (!key.equals(request.getParameter("key"))) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
userMgmtService.resetUnverifiedUsers();
context.renderJSON().renderTrueResult();
}
/**
* Lists usernames.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/users/names", method = HTTPRequestMethod.GET)
public void listNames(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
if (null == Sessions.currentUser(request)) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
context.renderJSON().renderTrueResult();
final String namePrefix = request.getParameter("name");
if (StringUtils.isBlank(namePrefix)) {
final List<JSONObject> admins = userQueryService.getAdmins();
final List<JSONObject> userNames = new ArrayList<>();
for (final JSONObject admin : admins) {
final JSONObject userName = new JSONObject();
userName.put(User.USER_NAME, admin.optString(User.USER_NAME));
final String avatar = avatarQueryService.getAvatarURLByUser(
UserExt.USER_AVATAR_VIEW_MODE_C_STATIC, admin, "20");
userName.put(UserExt.USER_AVATAR_URL, avatar);
userNames.add(userName);
}
context.renderJSONValue(Common.USER_NAMES, userNames);
return;
}
final List<JSONObject> userNames = userQueryService.getUserNamesByPrefix(namePrefix);
context.renderJSONValue(Common.USER_NAMES, userNames);
}
/**
* Lists emotions.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/users/emotions", method = HTTPRequestMethod.GET)
public void getEmotions(final HTTPRequestContext context, final HttpServletRequest request,
final HttpServletResponse response) throws Exception {
context.renderJSON();
final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
if (null == currentUser) {
context.renderJSONValue("emotions", "");
return;
}
final String userId = currentUser.optString(Keys.OBJECT_ID);
final String emotions = emotionQueryService.getEmojis(userId);
context.renderJSONValue("emotions", emotions);
}
/**
* Loads usernames.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/cron/users/load-names", method = HTTPRequestMethod.GET)
public void loadUserNames(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final String key = Symphonys.get("keyOfSymphony");
if (!key.equals(request.getParameter("key"))) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
userQueryService.loadUserNames();
context.renderJSON().renderTrueResult();
}
/**
* Fills home user.
*
* @param dataModel the specified data model
* @param user the specified user
*/
private void fillHomeUser(final Map<String, Object> dataModel, final JSONObject user) {
dataModel.put(User.USER, user);
final String roleId = user.optString(User.USER_ROLE);
final JSONObject role = roleQueryService.getRole(roleId);
user.put(Role.ROLE_NAME, role.optString(Role.ROLE_NAME));
}
}
|
package org.owasp.esapi.reference;
import java.util.HashMap;
import org.apache.log4j.Level;
import javax.servlet.http.HttpSession;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.LogFactory;
import org.owasp.esapi.Logger;
import org.owasp.esapi.User;
public class Log4JLogFactory implements LogFactory {
private String applicationName;
@SuppressWarnings("unchecked")
private HashMap loggersMap = new HashMap();
/**
* Null argument constructor for this implementation of the LogFactory interface
* needed for dynamic configuration.
*/
public Log4JLogFactory() {}
/**
* Constructor for this implementation of the LogFactory interface.
*
* @param applicationName The name of this application this logger is being constructed for.
*/
public Log4JLogFactory(String applicationName) {
this.applicationName = applicationName;
}
/**
* {@inheritDoc}
*/
public void setApplicationName(String newApplicationName) {
applicationName = newApplicationName;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public Logger getLogger(Class clazz) {
// If a logger for this class already exists, we return the same one, otherwise we create a new one.
Logger classLogger = (Logger) loggersMap.get(clazz);
if (classLogger == null) {
classLogger = new Log4JLogger(applicationName, clazz.getName());
loggersMap.put(clazz, classLogger);
}
return classLogger;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public Logger getLogger(String moduleName) {
// If a logger for this module already exists, we return the same one, otherwise we create a new one.
Logger moduleLogger = (Logger) loggersMap.get(moduleName);
if (moduleLogger == null) {
moduleLogger = new Log4JLogger(applicationName, moduleName);
loggersMap.put(moduleName, moduleLogger);
}
return moduleLogger;
}
private static class Log4JLogger implements org.owasp.esapi.Logger {
/** The jlogger object used by this class to log everything. */
private org.apache.log4j.Logger jlogger = null;
/** The application name using this log. */
private String applicationName = null;
/** The module name using this log. */
private String moduleName = null;
/**
* Public constructor should only ever be called via the appropriate LogFactory
*
* @param applicationName the application name
* @param moduleName the module name
*/
private Log4JLogger(String applicationName, String moduleName) {
this.applicationName = applicationName;
this.moduleName = moduleName;
this.jlogger = org.apache.log4j.Logger.getLogger(applicationName + ":" + moduleName);
}
/**
* {@inheritDoc}
* Note: In this implementation, this change is not persistent,
* meaning that if the application is restarted, the log level will revert to the level defined in the
* ESAPI SecurityConfiguration properties file.
*/
public void setLevel(int level)
{
try {
jlogger.setLevel(convertESAPILeveltoLoggerLevel( level ));
}
catch (IllegalArgumentException e) {
this.error(Logger.SECURITY_FAILURE, "", e);
}
}
private static Level convertESAPILeveltoLoggerLevel(int level)
{
switch (level) {
case Logger.OFF: return Level.OFF;
case Logger.FATAL: return Level.FATAL;
case Logger.ERROR: return Level.ERROR;
case Logger.WARNING: return Level.WARN;
case Logger.INFO: return Level.INFO;
case Logger.DEBUG: return Level.DEBUG; //fine
case Logger.TRACE: return Level.TRACE; //finest
case Logger.ALL: return Level.ALL;
default: {
throw new IllegalArgumentException("Invalid logging level. Value was: " + level);
}
}
}
/**
* {@inheritDoc}
*/
public void trace(EventType type, String message, Throwable throwable) {
log(Level.TRACE, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void trace(EventType type, String message) {
log(Level.TRACE, type, message, null);
}
/**
* {@inheritDoc}
*/
public void debug(EventType type, String message, Throwable throwable) {
log(Level.DEBUG, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void debug(EventType type, String message) {
log(Level.DEBUG, type, message, null);
}
/**
* {@inheritDoc}
*/
public void info(EventType type, String message) {
log(Level.INFO, type, message, null);
}
/**
* {@inheritDoc}
*/
public void info(EventType type, String message, Throwable throwable) {
log(Level.INFO, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void warning(EventType type, String message, Throwable throwable) {
log(Level.WARN, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void warning(EventType type, String message) {
log(Level.WARN, type, message, null);
}
/**
* {@inheritDoc}
*/
public void error(EventType type, String message, Throwable throwable) {
log(Level.ERROR, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void error(EventType type, String message) {
log(Level.ERROR, type, message, null);
}
/**
* {@inheritDoc}
*/
public void fatal(EventType type, String message, Throwable throwable) {
log(Level.FATAL, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void fatal(EventType type, String message) {
log(Level.FATAL, type, message, null);
}
/**
* Log the message after optionally encoding any special characters that might be dangerous when viewed
* by an HTML based log viewer. Also encode any carriage returns and line feeds to prevent log
* injection attacks. This logs all the supplied parameters plus the user ID, user's source IP, a logging
* specific session ID, and the current date/time.
*
* It will only log the message if the current logging level is enabled, otherwise it will
* discard the message.
*
* @param level the severity level of the security event
* @param type the type of the event (SECURITY, FUNCTIONALITY, etc.)
* @param success whether this was a failed or successful event
* @param message the message
* @param throwable the throwable
*/
private void log(Level level, EventType type, String message, Throwable throwable) {
// Before we waste time preparing this event for the log, we check to see if it needs to be logged
if (!jlogger.isEnabledFor( level )) return;
User user = ESAPI.authenticator().getCurrentUser();
// create a random session number for the user to represent the user's 'session', if it doesn't exist already
String userSessionIDforLogging = "unknown";
try {
HttpSession session = ESAPI.httpUtilities().getCurrentRequest().getSession( false );
userSessionIDforLogging = (String)session.getAttribute("ESAPI_SESSION");
// if there is no session ID for the user yet, we create one and store it in the user's session
if ( userSessionIDforLogging == null ) {
userSessionIDforLogging = ""+ ESAPI.randomizer().getRandomInteger(0, 1000000);
session.setAttribute("ESAPI_SESSION", userSessionIDforLogging);
}
} catch( NullPointerException e ) {
// continue
}
// ensure there's something to log
if ( message == null ) {
message = "";
}
// ensure no CRLF injection into logs for forging records
String clean = message.replace( '\n', '_' ).replace( '\r', '_' );
if ( ((DefaultSecurityConfiguration)ESAPI.securityConfiguration()).getLogEncodingRequired() ) {
clean = ESAPI.encoder().encodeForHTML(message);
if (!message.equals(clean)) {
clean += " (Encoded)";
}
}
// create the message to log
String msg = "";
if ( user != null && type != null) {
msg = type + " " + user.getAccountName() + "@"+ user.getLastHostAddress() +":" + userSessionIDforLogging + " " + clean;
}
if(throwable == null) {
jlogger.log(level, applicationName + " " + moduleName + " " + msg);
} else {
jlogger.log(level, applicationName + " " + moduleName + " " + msg, throwable);
}
//ERROR HibernateAccessController - ARMS:com.aspectsecurity.arms.service.HibernateAccessController:SECURITY SUCCESS-SUCCESS dave@192.168.7.100:342842 -- ACCESS GRANTED isAuthorizedForURL urlString=/arms/assessment/AssessmentView.do?id=709
}
/**
* {@inheritDoc}
*/
public boolean isDebugEnabled() {
return jlogger.isEnabledFor(Level.DEBUG);
}
/**
* {@inheritDoc}
*/
public boolean isErrorEnabled() {
return jlogger.isEnabledFor(Level.ERROR);
}
/**
* {@inheritDoc}
*/
public boolean isFatalEnabled() {
return jlogger.isEnabledFor(Level.FATAL);
}
/**
* {@inheritDoc}
*/
public boolean isInfoEnabled() {
return jlogger.isEnabledFor(Level.INFO);
}
/**
* {@inheritDoc}
*/
public boolean isTraceEnabled() {
return jlogger.isEnabledFor(Level.TRACE);
}
/**
* {@inheritDoc}
*/
public boolean isWarningEnabled() {
return jlogger.isEnabledFor(Level.WARN);
}
}
}
|
package soot.jimple.infoflow.android.resources;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import pxb.android.axml.AxmlReader;
import pxb.android.axml.AxmlVisitor;
import pxb.android.axml.AxmlVisitor.NodeVisitor;
import soot.PackManager;
import soot.Scene;
import soot.SceneTransformer;
import soot.SootClass;
import soot.Transform;
/**
* Parser for analyzing the layout XML files inside an android application
*
* @author Steven Arzt
*
*/
public class LayoutFileParser extends AbstractResourceParser {
private static final boolean DEBUG = true;
private final Map<Integer, LayoutControl> userControls = new HashMap<Integer, LayoutControl>();
private final Map<String, Set<String>> callbackMethods = new HashMap<String, Set<String>>();
private final String packageName;
private final static int TYPE_NUMBER_VARIATION_PASSWORD = 0x00000010;
private final static int TYPE_TEXT_VARIATION_PASSWORD = 0x00000080;
private final static int TYPE_TEXT_VARIATION_VISIBLE_PASSWORD = 0x00000090;
private final static int TYPE_TEXT_VARIATION_WEB_PASSWORD = 0x000000e0;
public LayoutFileParser(String packageName) {
this.packageName = packageName;
}
private SootClass getLayoutClass(String className) {
SootClass sc = Scene.v().forceResolve(className, SootClass.BODIES);
if ((sc == null || sc.isPhantom()) && !packageName.isEmpty())
sc = Scene.v().forceResolve(packageName + "." + className, SootClass.BODIES);
if (sc == null || sc.isPhantom())
sc = Scene.v().forceResolve("android.widget." + className, SootClass.BODIES);
if (sc == null || sc.isPhantom())
sc = Scene.v().forceResolve("android.webkit." + className, SootClass.BODIES);
if (sc == null || sc.isPhantom())
System.err.println("Could not find layout class " + className);
return sc;
}
private boolean isLayoutClass(SootClass theClass) {
if (theClass == null)
return false;
// To make sure that nothing all wonky is going on here, we
// check the hierarchy to find the android view class
boolean found = false;
for (SootClass parent : Scene.v().getActiveHierarchy().getSuperclassesOf(theClass))
if (parent.getName().equals("android.view.ViewGroup")) {
found = true;
break;
}
return found;
}
private boolean isViewClass(SootClass theClass) {
if (theClass == null)
return false;
// To make sure that nothing all wonky is going on here, we
// check the hierarchy to find the android view class
boolean found = false;
for (SootClass parent : Scene.v().getActiveHierarchy().getSuperclassesOf(theClass))
if (parent.getName().equals("android.view.View")
|| parent.getName().equals("android.webkit.WebView")) {
found = true;
break;
}
if (!found) {
System.err.println("Layout class " + theClass.getName() + " is not derived from "
+ "android.view.View");
return false;
}
return true;
}
private class LayoutParser extends NodeVisitor {
private final String layoutFile;
private final SootClass theClass;
private Integer id = -1;
private boolean isSensitive = false;
public LayoutParser(String layoutFile, SootClass theClass) {
this.layoutFile = layoutFile;
this.theClass = theClass;
}
@Override
public NodeVisitor child(String ns, String name) {
final SootClass childClass = getLayoutClass(name.trim());
if (isLayoutClass(childClass) || isViewClass(childClass))
return new LayoutParser(layoutFile, childClass);
else
return super.child(ns, name);
}
@Override
public void attr(String ns, String name, int resourceId, int type, Object obj) {
// Check that we're actually working on an android attribute
if (ns == null)
return;
ns = ns.trim();
if (ns.startsWith("*"))
ns = ns.substring(1);
if (!ns.equals("http://schemas.android.com/apk/res/android"))
return;
// Read out the field data
name = name.trim();
if (name.equals("id") && type == AxmlVisitor.TYPE_REFERENCE)
this.id = (Integer) obj;
else if (name.equals("password") && type == AxmlVisitor.TYPE_INT_BOOLEAN)
isSensitive = ((Integer) obj) != 0; // -1 for true, 0 for false
else if (!isSensitive && name.equals("inputType") && type == AxmlVisitor.TYPE_INT_HEX) {
int tp = (Integer) obj;
isSensitive = ((tp & TYPE_NUMBER_VARIATION_PASSWORD) == TYPE_NUMBER_VARIATION_PASSWORD)
|| ((tp & TYPE_TEXT_VARIATION_PASSWORD) == TYPE_TEXT_VARIATION_PASSWORD)
|| ((tp & TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == TYPE_TEXT_VARIATION_VISIBLE_PASSWORD)
|| ((tp & TYPE_TEXT_VARIATION_WEB_PASSWORD) == TYPE_TEXT_VARIATION_WEB_PASSWORD);
}
else if (isActionListener(name) && type == AxmlVisitor.TYPE_STRING && obj instanceof String) {
String strData = ((String) obj).trim();
if (callbackMethods.containsKey(layoutFile))
callbackMethods.get(layoutFile).add(strData);
else {
Set<String> callbackSet = new HashSet<String>();
callbackSet.add(strData);
callbackMethods.put(layoutFile, callbackSet);
}
}
else {
if (DEBUG && type == AxmlVisitor.TYPE_STRING)
System.out.println("Found unrecognized XML attribute: " + name);
}
}
/**
* Checks whether this name is the name of a well-known Android listener
* attribute. This is a function to allow for future extension.
* @param name The attribute name to check. This name is guaranteed to
* be in the android namespace.
* @return True if the given attribute name corresponds to a listener,
* otherwise false.
*/
private boolean isActionListener(String name) {
return name.equals("onClick");
}
@Override
public void end() {
if (id > 0)
userControls.put(id, new LayoutControl(id, theClass, isSensitive));
}
}
/**
* Parses all layout XML files in the given APK file and loads the IDs of
* the user controls in it.
* @param fileName The APK file in which to look for user controls
*/
public void parseLayoutFile(final String fileName, final Set<String> classes) {
Transform transform = new Transform("wjtp.lfp", new SceneTransformer() {
protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) {
handleAndroidResourceFiles(fileName, /*classes,*/ null, new IResourceHandler() {
@Override
public void handleResourceFile(final String fileName, Set<String> fileNameFilter, InputStream stream) {
if (!fileName.endsWith(".xml")) {
System.err.println("Skipping file " + fileName + " in layout folder...");
return;
}
String entryClass = fileName.substring(0, fileName.lastIndexOf("."));
if (!packageName.isEmpty())
entryClass = packageName + "." + entryClass;
// We are dealing with resource files
if (!fileName.startsWith("res/layout"))
return;
if (fileNameFilter != null) {
boolean found = false;
for (String s : fileNameFilter)
if (s.equalsIgnoreCase(entryClass)) {
found = true;
break;
}
if (!found)
return;
}
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int in;
while ((in = stream.read()) >= 0)
bos.write(in);
bos.flush();
byte[] data = bos.toByteArray();
AxmlReader rdr = new AxmlReader(data);
rdr.accept(new AxmlVisitor() {
@Override
public NodeVisitor first(String ns, String name) {
final SootClass theClass = name == null ? null : getLayoutClass(name.trim());
if (theClass == null || isLayoutClass(theClass))
return new LayoutParser(fileName, theClass);
else
return super.first(ns, name);
}
});
System.out.println("Found " + userControls.size() + " layout controls in file "
+ fileName);
}
catch (IOException ex) {
System.err.println("Could not read binary XML file: " + ex.getMessage());
ex.printStackTrace();
}
}
});
}
});
PackManager.v().getPack("wjtp").add(transform);
}
/**
* Gets the user controls found in the layout XML file. The result is a
* mapping from the id to the respective layout control.
* @return The layout controls found in the XML file.
*/
public Map<Integer, LayoutControl> getUserControls() {
return this.userControls;
}
/**
* Gets the callback methods found in the layout XML file. The result is a
* mapping from the file name to the set of found callback methods.
* @return The callback methods found in the XML file.
*/
public Map<String, Set<String>> getCallbackMethods() {
return this.callbackMethods;
}
}
|
/**
Khalid
*/
package org.sikuli.slides.uis;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.SpinnerNumberModel;
import javax.swing.text.NumberFormatter;
import org.sikuli.api.robot.desktop.DesktopScreen;
import org.sikuli.slides.utils.Constants;
import org.sikuli.slides.utils.UserPreferencesEditor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PreferencesEditorUI extends JFrame implements ActionListener{
private static final long serialVersionUID = 5720589766452453287L;
private UserPreferencesEditor prefs = new UserPreferencesEditor();
private static final Logger logger = (Logger) LoggerFactory.getLogger(PreferencesEditorUI.class);
private JSpinner maxWaitTimeSpinner, maxLabelDisplayTimeSpinner, instructionHintFontSizeSpinner,
canvasWidthSizeSpinner;
private JButton okButton, cancelButton, restoreButton;
private JSlider preciseControlSlider;
private JComboBox displaysComboBox;
public PreferencesEditorUI(){
super("sikuli-slides -- Preferences");
}
private void createAndShowUI() {
JPanel panel = new JPanel(new BorderLayout());
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("General",makeGeneralPanel());
tabbedPane.add("Tutorial mode settings",makeSettingsPanel());
panel.add(tabbedPane, BorderLayout.PAGE_START);
JPanel bottomPanel = new JPanel(new FlowLayout());
okButton = new JButton("OK");
okButton.addActionListener(this);
bottomPanel.add(okButton);
restoreButton = new JButton("Restore Defaults");
restoreButton.addActionListener(this);
bottomPanel.add(restoreButton);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
bottomPanel.add(cancelButton);
panel.add(bottomPanel, BorderLayout.PAGE_END);
add(panel);
pack();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(false);
setVisible(true);
}
private JPanel makeGeneralPanel() {
GridBagLayout gridBagLayout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
JPanel panel = new JPanel(false);
panel.setLayout(gridBagLayout);
JLabel maxWaitTimeLabel = new JLabel("Maximum wait time to find target on the screen:");
int currentSpinnerMaxWaitTimeSec = prefs.getMaxWaitTime() / 1000;
int maxSpinnerMaxWaitTimeSec = 259200; // 72 hours
SpinnerNumberModel maxWaitTimeSpinnerModel = new SpinnerNumberModel(currentSpinnerMaxWaitTimeSec, 0, maxSpinnerMaxWaitTimeSec, 1);
maxWaitTimeSpinner = new JSpinner(maxWaitTimeSpinnerModel);
JFormattedTextField txt = ((JSpinner.NumberEditor) maxWaitTimeSpinner.getEditor()).getTextField();
((NumberFormatter) txt.getFormatter()).setAllowsInvalid(false);
maxWaitTimeLabel.setLabelFor(maxWaitTimeSpinner);
constraints.gridx = 0;
constraints.gridy = 0;
gridBagLayout.setConstraints(maxWaitTimeLabel, constraints);
panel.add(maxWaitTimeLabel);
constraints.gridx = 1;
gridBagLayout.setConstraints(maxWaitTimeSpinner, constraints);
panel.add(maxWaitTimeSpinner);
JLabel unitLabel = new JLabel(" seconds ");
constraints.gridx = 2;
gridBagLayout.setConstraints(unitLabel, constraints);
panel.add(unitLabel);
constraints.gridx = 0;
constraints.gridy = 1;
int currentPreciseScoreValue = (int) (prefs.getPreciseSearchScore() * 10);
final int maxPreciseScoreValue = 10;
JLabel perciseControlLabel=new JLabel("Precision value score that controls how accurate the image search is:");
preciseControlSlider = new JSlider(JSlider.HORIZONTAL,1, maxPreciseScoreValue, currentPreciseScoreValue);
preciseControlSlider.setPaintLabels(true);
preciseControlSlider.setPaintTicks(true);
preciseControlSlider.setMajorTickSpacing(1);
preciseControlSlider.setMinorTickSpacing(1);
preciseControlSlider.setMaximumSize(preciseControlSlider.getPreferredSize());
perciseControlLabel.setLabelFor(preciseControlSlider);
gridBagLayout.setConstraints(perciseControlLabel, constraints);
panel.add(perciseControlLabel);
constraints.gridx = 1;
gridBagLayout.setConstraints(preciseControlSlider, constraints);
panel.add(preciseControlSlider);
JLabel displaysLabel=new JLabel("Main Display (select from connected displays):");
constraints.gridy = 2;
constraints.gridx = 0;
int numberofDisplays = DesktopScreen.getNumberScreens();
String [] availableDisplays = new String[numberofDisplays];
for(int i=0; i<numberofDisplays; i++){
availableDisplays[i] = Integer.toString(i);
}
displaysComboBox = new JComboBox(availableDisplays);
displaysComboBox.setSelectedIndex(Constants.ScreenId);
displaysComboBox.addActionListener(this);
displaysComboBox.setMaximumSize(displaysComboBox.getPreferredSize());
displaysComboBox.addActionListener(this);
displaysLabel.setLabelFor(displaysComboBox);
gridBagLayout.setConstraints(displaysLabel, constraints);
panel.add(displaysLabel);
constraints.gridx = 1;
gridBagLayout.setConstraints(displaysComboBox, constraints);
panel.add(displaysComboBox);
return panel;
}
private JPanel makeSettingsPanel() {
GridBagLayout gridBagLayout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
JPanel panel = new JPanel(false);
panel.setLayout(gridBagLayout);
JLabel canvasDisplayTimeLabel = new JLabel("<html>Time to display a label on the screen:</html>");
int currentSpinnerLabelDisplayTimeSec = prefs.getLabelDisplayTime();
int maxSpinnerLabelDisplayTimeSec = 21600; // 6 hours
SpinnerNumberModel maxLabelDisplayTimeModel = new SpinnerNumberModel(currentSpinnerLabelDisplayTimeSec, 0, maxSpinnerLabelDisplayTimeSec, 1);
maxLabelDisplayTimeSpinner = new JSpinner(maxLabelDisplayTimeModel);
JFormattedTextField txt = ((JSpinner.NumberEditor) maxLabelDisplayTimeSpinner.getEditor()).getTextField();
((NumberFormatter) txt.getFormatter()).setAllowsInvalid(false);
canvasDisplayTimeLabel.setLabelFor(maxLabelDisplayTimeSpinner);
constraints.gridx = 0;
constraints.gridy = 0;
gridBagLayout.setConstraints(canvasDisplayTimeLabel, constraints);
panel.add(canvasDisplayTimeLabel);
constraints.gridx = 1;
gridBagLayout.setConstraints(maxLabelDisplayTimeSpinner, constraints);
panel.add(maxLabelDisplayTimeSpinner);
JLabel unitLabel = new JLabel(" seconds");
constraints.gridx = 2;
gridBagLayout.setConstraints(unitLabel, constraints);
panel.add(unitLabel);
// Instruction hint font size
JLabel instructionHintFontSizeLabel = new JLabel("Instruction hint (tooltip) font size:");
int currentSpinnerinstructionHintFontSize = prefs.getLabelDisplayTime();
int maxSpinnerinstructionHintFontSize = 21600; // 6 hours
SpinnerNumberModel instructionHintFontSizeModel = new SpinnerNumberModel(currentSpinnerinstructionHintFontSize, 0, maxSpinnerinstructionHintFontSize, 1);
instructionHintFontSizeSpinner = new JSpinner(instructionHintFontSizeModel);
JFormattedTextField instructionHintFontSizeFormatted = ((JSpinner.NumberEditor) instructionHintFontSizeSpinner.getEditor()).getTextField();
((NumberFormatter) instructionHintFontSizeFormatted.getFormatter()).setAllowsInvalid(false);
instructionHintFontSizeLabel.setLabelFor(instructionHintFontSizeSpinner);
constraints.gridx = 0;
constraints.gridy = 1;
gridBagLayout.setConstraints(instructionHintFontSizeLabel, constraints);
panel.add(instructionHintFontSizeLabel);
constraints.gridx = 1;
gridBagLayout.setConstraints(instructionHintFontSizeSpinner, constraints);
panel.add(instructionHintFontSizeSpinner);
JLabel unitLabel2 = new JLabel(" points");
constraints.gridx = 2;
gridBagLayout.setConstraints(unitLabel2, constraints);
panel.add(unitLabel2);
// Canvas width size
// Instruction hint font size
JLabel CanvasWidthSizeLabel = new JLabel("Canvas width size:");
int currentSpinnerCanvasWidthSize = prefs.getCanvasWidthSize();
int maxSpinnerCanvasWidthSize = 30; // 30 points
SpinnerNumberModel CanvasWidthSizeModel = new SpinnerNumberModel(currentSpinnerCanvasWidthSize, 0, maxSpinnerCanvasWidthSize, 1);
canvasWidthSizeSpinner = new JSpinner(CanvasWidthSizeModel);
JFormattedTextField CanvasWidthSizeFormatted = ((JSpinner.NumberEditor) canvasWidthSizeSpinner.getEditor()).getTextField();
((NumberFormatter) CanvasWidthSizeFormatted.getFormatter()).setAllowsInvalid(false);
CanvasWidthSizeLabel.setLabelFor(canvasWidthSizeSpinner);
constraints.gridx = 0;
constraints.gridy = 2;
gridBagLayout.setConstraints(CanvasWidthSizeLabel, constraints);
panel.add(CanvasWidthSizeLabel);
constraints.gridx = 1;
gridBagLayout.setConstraints(canvasWidthSizeSpinner, constraints);
panel.add(canvasWidthSizeSpinner);
JLabel unitLabel3 = new JLabel(" points");
constraints.gridx = 2;
gridBagLayout.setConstraints(unitLabel3, constraints);
panel.add(unitLabel3);
return panel;
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == okButton){
storeUserPreferences();
}
else if(e.getSource() == restoreButton){
restoreDefaultUserPreferences();
}
else if(e.getSource() == cancelButton){
this.dispose();
}
else if(e.getSource() == displaysComboBox){
prefs.putDisplayId(displaysComboBox.getSelectedIndex());
}
}
private void restoreDefaultUserPreferences() {
prefs.putMaxWaitTime(Constants.MAX_WAIT_TIME_MS_DEFAULT);
maxWaitTimeSpinner.setValue(Constants.MAX_WAIT_TIME_MS_DEFAULT / 1000);
prefs.putLabelDisplayTime(Constants.LABEL_DISPLAY_TIME_SEC_DEFAULT);
maxLabelDisplayTimeSpinner.setValue(Constants.LABEL_DISPLAY_TIME_SEC_DEFAULT);
prefs.putInstructionHintFontSize(Constants.INSTRUCTION_HINT_FONT_SIZE_DEFAULT);
instructionHintFontSizeSpinner.setValue(Constants.INSTRUCTION_HINT_FONT_SIZE_DEFAULT);
prefs.putCanvasWidthSize(Constants.CANVAS_WIDTH_SIZE_DEFAULT);
canvasWidthSizeSpinner.setValue(Constants.CANVAS_WIDTH_SIZE_DEFAULT);
prefs.putPreciseSearchScore((int) (Constants.PRECISE_SEARCH_SCORE_DEFAULT * 10));
preciseControlSlider.setValue((int) (Constants.PRECISE_SEARCH_SCORE_DEFAULT * 10));
}
private void storeUserPreferences() {
try{
prefs.putMaxWaitTime((Integer) maxWaitTimeSpinner.getValue() * 1000);
prefs.putLabelDisplayTime((Integer)maxLabelDisplayTimeSpinner.getValue());
prefs.putInstructionHintFontSize((Integer) instructionHintFontSizeSpinner.getValue());
prefs.putCanvasWidthSize((Integer) canvasWidthSizeSpinner.getValue());
prefs.putPreciseSearchScore(preciseControlSlider.getValue());
this.dispose();
}
catch (Exception e){
logger.error("Error: Failed to save preferences.");
}
}
public static void showPreferencesEditorUI(){
PreferencesEditorUI preferencesEditorUI = new PreferencesEditorUI();
preferencesEditorUI.createAndShowUI();
}
}
|
package org.cruk.mga;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Class providing a mapping between reference genome IDs and species.
*
* @author eldrid01
*/
public class ReferenceGenomeSpeciesMapping
{
private Map<String, String> referenceGenomeSpeciesLookup = new HashMap<String, String>();
private Map<String, String> referenceGenomeIdLookup = new HashMap<String, String>();
/**
* Loads reference genome ID to species mappings from the given properties
* file.
*
* @param referenceGenomeMappingFile the reference genome mapping file
* @throws FileNotFoundException
* @throws IOException
*/
public void loadFromPropertiesFile(String referenceGenomeMappingFile) throws FileNotFoundException, IOException
{
Properties properties = new Properties();
properties.load(new FileInputStream(referenceGenomeMappingFile));
Enumeration<?> referenceGenomeIds = properties.keys();
while (referenceGenomeIds.hasMoreElements())
{
String referenceGenomeId = (String)referenceGenomeIds.nextElement();
String[] names = properties.getProperty(referenceGenomeId).split("\\|");
List<String> nameList = new ArrayList<String>();
for (String name : names)
{
name = name.trim();
if (name.length() > 0)
{
nameList.add(name);
}
}
if (nameList.isEmpty())
{
referenceGenomeSpeciesLookup.put(referenceGenomeId, "Not specified");
}
else
{
referenceGenomeSpeciesLookup.put(referenceGenomeId, nameList.get(0));
for (String name : nameList)
{
name = name.toLowerCase();
if (!referenceGenomeIdLookup.containsKey(name))
{
referenceGenomeIdLookup.put(name, referenceGenomeId);
}
}
}
}
}
/**
* Returns the reference genome ID for the given species name/synonym.
*
* @param species the name of the species.
* @return
*/
public String getReferenceGenomeId(String species)
{
return referenceGenomeIdLookup.get(species.toLowerCase());
}
/**
* Returns the species display name for the given reference genome ID.
*
* @param referenceGenomeId the reference genome identifier
* @return
*/
public String getSpecies(String referenceGenomeId)
{
return referenceGenomeSpeciesLookup.get(referenceGenomeId);
}
}
|
package org.stefanl.closure_cli;
import com.esotericsoftware.yamlbeans.YamlConfig;
import com.esotericsoftware.yamlbeans.YamlException;
import com.esotericsoftware.yamlbeans.YamlReader;
import com.esotericsoftware.yamlbeans.YamlWriter;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import jline.Terminal;
import jline.console.ConsoleReader;
import jline.console.completer.Completer;
import jline.console.completer.StringsCompleter;
import org.kohsuke.args4j.CmdLineParser;
import org.stefanl.closure_cli.config.ClosureConfig;
import org.stefanl.closure_cli.config.ConfigYamlReader;
import org.stefanl.closure_cli.parser.CommandCLIConfigurable;
import org.stefanl.closure_cli.runners.MainRunner;
import org.stefanl.closure_utilities.closure.ClosureOptions;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
public class CommandLineRunner {
public static Boolean isTesting = false;
public static void setTesting() {
isTesting = true;
}
public final MainRunner mainRunner;
private final InputStream inputStream;
private final OutputStream outputStream;
private CommandLineRunner(
@Nonnull final ClosureOptions closureOptions,
@Nonnull final ClosureConfig closureConfig) {
this.mainRunner = new MainRunner(closureOptions, closureConfig);
this.inputStream = System.in;
this.outputStream = System.out;
}
public String getSampleConfigFileContent(ClosureConfig options) {
try {
StringWriter stringWriter = new StringWriter();
YamlConfig yamlConfig = new YamlConfig();
yamlConfig.writeConfig.setAlwaysWriteClassname(false);
yamlConfig.writeConfig.setWriteRootTags(false);
YamlWriter yamlWriter = new YamlWriter(stringWriter, yamlConfig);
yamlWriter.write(options);
yamlWriter.close();
return stringWriter.toString();
} catch (YamlException yamlException) {
throw new RuntimeException(yamlException);
}
}
public static File DEFAULT_CONFIG_FILE =
new File("closure.yml");
public static List<File> ALTERNATE_CONFIG_LOCATIONS =
Lists.newArrayList(new File("config/closure.yml"));
@Nonnull
public static ImmutableList<File> getPossibleConfigFiles() {
ImmutableList.Builder<File> listBuilder = new ImmutableList.Builder<>();
listBuilder.add(DEFAULT_CONFIG_FILE);
listBuilder.addAll(ALTERNATE_CONFIG_LOCATIONS);
return listBuilder.build();
}
public Function<String, File> STRING_TO_FILE =
new Function<String, File>() {
@Nullable
@Override
public File apply(@Nullable String input) {
return new File(input);
}
};
public final static String PROMPT = " closure-cli > ";
private static ClosureConfig getConfigOptions(
@Nonnull final File configFile) throws IOException {
try (FileReader fileReader = new FileReader(configFile)) {
final YamlReader yamlReader = new YamlReader(fileReader);
final ClosureConfig configOptions =
yamlReader.read(ClosureConfig.class);
yamlReader.close();
if (configOptions != null) {
return configOptions;
} else {
return ConfigurationFactory.createEmpty();
}
}
}
@Nonnull
public static File getWorkingDirectory(
@Nonnull final CommandCLIConfigurable configurable) {
if (configurable.pwdDirectory != null) {
return configurable.pwdDirectory.getAbsoluteFile();
}
return new File("").getAbsoluteFile();
}
private static final List<String> CONFIG_FILES =
Lists.newArrayList("closure.yaml", "config/closure.yaml");
public static File getConfigurationFile(
@Nonnull final CommandCLIConfigurable configurable) {
if (configurable.configFile != null) {
if (!configurable.configFile.exists()) {
throw new RuntimeException("Configuration file " +
configurable.configFile + " does not exist");
}
return configurable.configFile;
}
File pwd = getWorkingDirectory(configurable);
for (String configFileName : CONFIG_FILES) {
File configFile = new File(pwd, configFileName);
if (configFile.exists()) {
return configFile;
}
}
throw new RuntimeException("No config file found in working " +
"directory: " + pwd);
}
@Nonnull
public static ClosureConfig getClosureConfig(
@Nonnull final CommandCLIConfigurable configurable)
throws IOException {
final File pwd = getWorkingDirectory(configurable);
final File cfg = getConfigurationFile(configurable);
final ConfigYamlReader configYamlReader = new ConfigYamlReader(pwd);
final ClosureConfig closureConfig = configYamlReader.read(cfg);
if (closureConfig == null) {
throw new RuntimeException("Fatal, failed to create closure " +
"config.");
}
return closureConfig;
}
public static ClosureOptions getClosureOptions(
@Nonnull final CommandCLIConfigurable configurable,
@Nonnull final ClosureConfig closureConfig) {
final ClosureOptions closureOptions = new ClosureOptions();
closureConfig.load(closureOptions);
configurable.load(closureOptions);
return closureOptions;
}
public void run(final String... args) throws Exception {
mainRunner.run(args);
}
private LinkedList<Completer> getCompleters() {
final LinkedList<Completer> completers = new LinkedList<>();
List<String> stringCommands =
Lists.transform(Lists.newArrayList(Command.values()),
new Function<Command,
String>() {
@Nullable
@Override
public String apply(@Nullable Command input) {
if (input != null) {
return input.toString().toLowerCase();
} else {
return null;
}
}
});
completers.add(new StringsCompleter(stringCommands));
return completers;
}
public void interactive() throws IOException {
final ConsoleReader reader = new ConsoleReader(System.in, System.out);
reader.setPrompt(PROMPT);
reader.setBellEnabled(false);
final Terminal terminal = reader.getTerminal();
terminal.setEchoEnabled(false);
for (Completer c : getCompleters()) {
reader.addCompleter(c);
}
final PrintWriter out = new PrintWriter(reader.getOutput());
String line;
while ((line = reader.readLine()) != null) {
try {
String[] args = line.split(" ");
if (args.length != 0) {
String stringCommand = args[0];
if (stringCommand.trim().equalsIgnoreCase("exit")) {
out.close();
System.exit(0);
}
run(args);
}
} catch (Exception exception) {
out.println("Exception occurred.");
exception.printStackTrace(out);
}
out.flush();
}
out.close();
}
protected static void mainInternal(String... args) throws Exception {
final CommandCLIConfigurable configurable = new
CommandCLIConfigurable();
final CmdLineParser cmdLineParser = new CmdLineParser(configurable);
cmdLineParser.parseArgument(args);
ClosureConfig closureConfig = getClosureConfig(configurable);
ClosureOptions closureOptions = getClosureOptions(configurable,
closureConfig);
CommandLineRunner commandLineRunner =
new CommandLineRunner(closureOptions, closureConfig);
if (configurable.args != null && configurable.args.length != 0) {
commandLineRunner.run(configurable.args);
} else {
commandLineRunner.interactive();
}
}
public static void main(String... args) throws Exception {
mainInternal(args);
System.exit(0);
}
}
|
package com.github.ocelotwars.service;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.times;
import static java.util.Collections.singletonList;
import static org.mockito.Mockito.verify;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import com.github.ocelotwars.engine.Player;
import com.github.ocelotwars.engine.command.GatherCommand;
import com.github.ocelotwars.engine.command.MoveCommand;
import com.github.ocelotwars.engine.game.Game;
import com.github.ocelotwars.service.commands.Direction;
import com.github.ocelotwars.service.commands.Gather;
import com.github.ocelotwars.service.commands.Move;
import com.github.ocelotwars.service.commands.Unload;
import io.vertx.core.http.ServerWebSocket;
import rx.Observable;
import rx.plugins.RxJavaHooks;
import rx.schedulers.TestScheduler;
import rx.subjects.PublishSubject;
public class GameSessionTest {
@Rule
public MockitoRule mockitoJUnit = MockitoJUnit.rule();
private TestScheduler scheduler;
@Mock
private Game game;
private List<SocketPlayer> players = new ArrayList<>();
@Before
public void before() {
scheduler = new TestScheduler();
RxJavaHooks.setOnComputationScheduler(d -> scheduler);
}
@Test
@SuppressWarnings("unchecked")
public void testRound_CommandsMove() throws Exception {
ServerWebSocket socket1 = Mockito.mock(ServerWebSocket.class);
players.add(new SocketPlayer("player1", socket1));
Commands commands = new Commands(singletonList(new Move(1, Direction.EAST)));
Observable<SocketMessage> mq = Observable.just(new SocketMessage(socket1, commands));
GameSession session = new GameSession(game, players, 5);
session.round(0, mq);
verify(game).execute(
singletonList(new MoveCommand(new Player("player1"), 1, com.github.ocelotwars.engine.Direction.EAST))
);
}
@Test
@SuppressWarnings("unchecked")
public void testRound_CommandsGather() throws Exception {
ServerWebSocket socket1 = Mockito.mock(ServerWebSocket.class);
players.add(new SocketPlayer("player1", socket1));
Commands commands = new Commands(singletonList(new Gather(1)));
Observable<SocketMessage> mq = Observable.just(new SocketMessage(socket1, commands));
GameSession session = new GameSession(game, players, 5);
session.round(0, mq);
verify(game).execute(singletonList(new GatherCommand(new Player("player1"), 1)));
}
@Test
@SuppressWarnings("unchecked")
public void testRound_TwoPlayers_CommandsForPlayer1() throws Exception {
ServerWebSocket socket1 = Mockito.mock(ServerWebSocket.class);
ServerWebSocket socket2 = Mockito.mock(ServerWebSocket.class);
players.add(new SocketPlayer("player1", socket1));
players.add(new SocketPlayer("player2", socket2));
Commands commands = new Commands(singletonList(new Gather(1)));
Observable<SocketMessage> mq = Observable.just(new SocketMessage(socket1, commands));
GameSession session = new GameSession(game, players, 5);
session.round(0, mq);
verify(game).execute(singletonList(new GatherCommand(new Player("player1"), 1)));
}
@Test
@SuppressWarnings("unchecked")
public void testRound_TwoPlayers_CommandsForPlayer2() throws Exception {
ServerWebSocket socket1 = Mockito.mock(ServerWebSocket.class);
ServerWebSocket socket2 = Mockito.mock(ServerWebSocket.class);
players.add(new SocketPlayer("player1", socket1));
players.add(new SocketPlayer("player2", socket2));
Commands commands = new Commands(singletonList(new Gather(1)));
Observable<SocketMessage> mq = Observable.just(new SocketMessage(socket2, commands));
GameSession session = new GameSession(game, players, 5);
session.round(0, mq);
verify(game).execute(singletonList(new GatherCommand(new Player("player2"), 1)));
}
@Test
@SuppressWarnings("unchecked")
public void testRound_TwoPlayers_CommandsForPlayer12() throws Exception {
ServerWebSocket socket1 = Mockito.mock(ServerWebSocket.class);
ServerWebSocket socket2 = Mockito.mock(ServerWebSocket.class);
players.add(new SocketPlayer("player1", socket1));
players.add(new SocketPlayer("player2", socket2));
Commands commands1 = new Commands(singletonList(new Move(1, Direction.NORTH)));
Commands commands2 = new Commands(singletonList(new Gather(1)));
Observable<SocketMessage> mq = Observable.just(new SocketMessage(socket2, commands2), new SocketMessage(socket1, commands1));
GameSession session = new GameSession(game, players, 5);
session.round(0, mq);
verify(game).execute(singletonList(new MoveCommand(new Player("player1"), 1, com.github.ocelotwars.engine.Direction.NORTH)));
verify(game).execute(singletonList(new GatherCommand(new Player("player2"), 1)));
}
@Test
@SuppressWarnings("unchecked")
public void testRound_TwoPlayers_CommandsForIllegalSecondMessage_() throws Exception {
ServerWebSocket socket1 = Mockito.mock(ServerWebSocket.class);
ServerWebSocket socket2 = Mockito.mock(ServerWebSocket.class);
players.add(new SocketPlayer("player1", socket1));
players.add(new SocketPlayer("player2", socket2));
Commands commands1 = new Commands(singletonList(new Move(1, Direction.NORTH)));
Commands commands2 = new Commands(singletonList(new Gather(1)));
Commands commands3 = new Commands(singletonList(new Unload(1)));
Observable<SocketMessage> mq = Observable.just(
new SocketMessage(socket2, commands2),
new SocketMessage(socket1, commands1),
new SocketMessage(socket2, commands3));
GameSession session = new GameSession(game, players, 5);
session.round(0, mq);
verify(game).execute(singletonList(new MoveCommand(new Player("player1"), 1, com.github.ocelotwars.engine.Direction.NORTH)));
verify(game).execute(singletonList(new GatherCommand(new Player("player2"), 1)));
}
@Test
@SuppressWarnings("unchecked")
public void testRound_TwoPlayers_CommandsWithTimeout() throws Exception {
ServerWebSocket socket1 = Mockito.mock(ServerWebSocket.class);
ServerWebSocket socket2 = Mockito.mock(ServerWebSocket.class);
players.add(new SocketPlayer("player1", socket1));
players.add(new SocketPlayer("player2", socket2));
Commands commands1 = new Commands(singletonList(new Move(1, Direction.NORTH)));
Commands commands2 = new Commands(singletonList(new Gather(1)));
Observable<SocketMessage> mq = Observable.just(new SocketMessage(socket1, commands1), new SocketMessage(socket2, commands2))
.zipWith(Observable.interval(3, TimeUnit.SECONDS), (message, time) -> message);
GameSession session = new GameSession(game, players, 5);
session.round(0, mq);
scheduler.advanceTimeBy(6, TimeUnit.SECONDS);
verify(game).execute(singletonList(new MoveCommand(new Player("player1"), 1, com.github.ocelotwars.engine.Direction.NORTH)));
}
@Test
public void testRound_notifysAllPlayers() throws Exception {
ServerWebSocket socket1 = Mockito.mock(ServerWebSocket.class);
ServerWebSocket socket2 = Mockito.mock(ServerWebSocket.class);
players.add(new SocketPlayer("player1", socket1));
players.add(new SocketPlayer("player2", socket2));
Observable<SocketMessage> mq = Observable.empty();
GameSession session = new GameSession(game, players, 5);
session.round(0, mq);
verify(socket1).writeFinalTextFrame("{\"@type\":\"Notify\"}");
verify(socket2).writeFinalTextFrame("{\"@type\":\"Notify\"}");
}
@Test
@SuppressWarnings("unchecked")
public void testRounds_2rounds_runInSequence() throws Exception {
ServerWebSocket socket1 = Mockito.mock(ServerWebSocket.class);
ServerWebSocket socket2 = Mockito.mock(ServerWebSocket.class);
players.add(new SocketPlayer("player1", socket1));
players.add(new SocketPlayer("player2", socket2));
Commands commands1 = new Commands(singletonList(new Move(1, Direction.NORTH)));
Commands commands2 = new Commands(singletonList(new Move(1, Direction.WEST)));
PublishSubject<SocketMessage> mq = PublishSubject.create();
GameSession session = new GameSession(game, players, 5);
session.rounds(2, mq);
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
verify(socket1).writeFinalTextFrame("{\"@type\":\"Notify\"}");
verify(socket2).writeFinalTextFrame("{\"@type\":\"Notify\"}");
scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
mq.onNext(new SocketMessage(socket1, commands1));
verify(game, times(1)).execute(
singletonList(new MoveCommand(new Player("player1"), 1, com.github.ocelotwars.engine.Direction.NORTH))
);
Mockito.reset(game, socket1, socket2);
scheduler.advanceTimeBy(3, TimeUnit.SECONDS);
verify(socket1).writeFinalTextFrame("{\"@type\":\"Notify\"}");
verify(socket2).writeFinalTextFrame("{\"@type\":\"Notify\"}");
mq.onNext(new SocketMessage(socket2, commands2));
verify(game, times(1)).execute(
singletonList(new MoveCommand(new Player("player2"), 1, com.github.ocelotwars.engine.Direction.WEST)));
}
@Test
@SuppressWarnings("unchecked")
public void testRounds_2rounds_terminatesWithWinner() throws Exception {
ServerWebSocket socket1 = Mockito.mock(ServerWebSocket.class);
ServerWebSocket socket2 = Mockito.mock(ServerWebSocket.class);
players.add(new SocketPlayer("player1", socket1));
players.add(new SocketPlayer("player2", socket2));
Commands commands1 = new Commands(singletonList(new Move(1, Direction.NORTH)));
Commands commands2 = new Commands(singletonList(new Move(1, Direction.WEST)));
PublishSubject<SocketMessage> mq = PublishSubject.create();
GameSession session = new GameSession(game, players, 5);
SocketPlayer[] winner = new SocketPlayer[1];
session.winner().subscribe(p -> {winner[0] = p;});
session.rounds(2, mq);
scheduler.advanceTimeBy(3, TimeUnit.SECONDS);
mq.onNext(new SocketMessage(socket1, commands1));
scheduler.advanceTimeBy(3, TimeUnit.SECONDS);
mq.onNext(new SocketMessage(socket2, commands2));
verify(game).execute(singletonList(new MoveCommand(new Player("player1"), 1, com.github.ocelotwars.engine.Direction.NORTH)));
verify(game).execute(singletonList(new MoveCommand(new Player("player2"), 1, com.github.ocelotwars.engine.Direction.WEST)));
assertThat(winner[0], nullValue());
scheduler.advanceTimeBy(4, TimeUnit.SECONDS);
assertThat(winner[0], notNullValue());
}
}
|
package org.zooper.becuz.restmote.utils;
import org.zooper.becuz.restmote.model.App;
import org.zooper.becuz.restmote.model.MediaCategory;
import org.zooper.becuz.restmote.model.Settings;
import org.zooper.becuz.restmote.rest.resources.PcResource;
/**
* Defined constants used in all application
* @author bebo
*/
public class Constants {
/**
* Name of the root {@link MediaCategory}
*/
public static final String MEDIA_ROOT = "root";
/**
* Name of the subfolder in a icons theme, containing system icons (not belonging to the controls)
*/
public static final String NAME_DIR_ICON_SYSTEM = "system";
/**
* Default theme (img dir in client/images/)
*/
public static final String DEFAULT_THEME = "iconic";
/**
* Default value for {@link Settings#getScanDepth()}
*/
public static final int SCAN_DEPTH = 2;
/**
* Default number of pixels to move the mouse in {@link PcResource}
*/
public static final int DEFAULT_MOUSE_DELTA_MOVE = 8;
/**
* Default number of pixels to move the wheel mouse in {@link PcResource}
*/
public static final int DEFAULT_MOUSE_WHEEL = 10;
/**
* Constants value for {@link App#setArgumentsFile(String)}
*/
public static final String APP_ARGUMENT_FILE = "%f";
/**
* Constants value for {@link App#setArgumentsDir(String)}
*/
public static final String APP_ARGUMENT_DIR = "%f";
}
|
package org.geoint.gf.audit.log.jul;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.geoint.gf.audit.log.AuditAttribute;
import org.geoint.gf.audit.log.AuditCategory;
import org.geoint.gf.audit.log.AuditLogger;
import org.geoint.logging.splunk.SplunkLogRecord;
import org.geoint.logging.splunk.StandardSplunkFormatter;
/**
* Logs audits using a {@link java.util.logging.Logger Logger} under the logger
* name <i>org.geoint.gf.audit</i>.
*
*/
public class JULAuditLogger implements AuditLogger {
private static final String PARENT_LOGGER = "org.geoint.gf.audit";
private static final Logger logger;
private static final String PROP_LOG_PATTERN
= "org.geoint.gf.audit.file.pattern";
private static final String PROP_LOG_COUNT
= "org.geoint.gf.audit.file.count";
private static final String PROP_LOG_APPEND
= "org.geoint.gf.audit.file.append";
private static final String PROP_LOG_LIMIT
= "org.geoint.gf.audit.file.limit";
private static final String PROP_LOG_LEVEL
= "org.geoint.gf.audit.file.level";
private static final String DEFAULT_PATTERN = "%t/gf-audit.%g.log";
private static final String DEFAULT_LIMIT = "200000";
private static final String DEFAULT_COUNT = "5";
private static final String DEFAULT_APPEND = "true";
private static final String DEFAULT_LEVEL = Level.INFO.getName();
static {
logger = Logger.getLogger(PARENT_LOGGER);
try {
final FileHandler fh = new FileHandler(
System.getProperties().getProperty(PROP_LOG_PATTERN,
DEFAULT_PATTERN),
Integer.valueOf(
System.getProperties().getProperty(PROP_LOG_LIMIT,
DEFAULT_LIMIT)
),
Integer.valueOf(
System.getProperties().getProperty(PROP_LOG_COUNT,
DEFAULT_COUNT)
),
Boolean.valueOf(
System.getProperties().getProperty(PROP_LOG_APPEND,
DEFAULT_APPEND)
)
);
Level level = Level.parse(
System.getProperties().getProperty(PROP_LOG_LEVEL,
DEFAULT_LEVEL)
);
fh.setLevel(level);
logger.setLevel(level);
logger.addHandler(fh);
fh.setFormatter(new StandardSplunkFormatter());
logger.log(Level.INFO, "Started AuditLogger");
} catch (IOException ex) {
//use the GF managed logger
logger.log(Level.SEVERE,
"Unable to setup GF Audit module logging", ex);
}
}
@Override
public void debug(String message) {
logger.log(Level.FINE, () -> message);
}
@Override
public void system(String message) {
SplunkLogRecord r = new SplunkLogRecord(Level.INFO, message);
r.field("category", AuditCategory.SYSTEM.name());
logger.log(r);
}
@Override
public void log(AuditCategory category, String username, String message,
AuditAttribute... attributes) {
log(category, username, message, null, attributes);
}
@Override
public void log(AuditCategory category, String username,
String message, Throwable ex, AuditAttribute... attributes) {
log(category, Level.INFO, username, message, ex, attributes);
}
@Override
public void error(AuditCategory category, String username, String error,
AuditAttribute... attributes) {
log(category, Level.SEVERE, username, error, null, attributes);
}
@Override
public void error(AuditCategory category, String username,
String error, Throwable ex, AuditAttribute... attributes) {
log(category, Level.SEVERE, username, error, ex, attributes);
}
private void log(AuditCategory category, Level level,
String username, String message, Throwable ex,
AuditAttribute... attributes) {
if (username == null) {
if (logger.isLoggable(Level.FINE)) {
username = "unknown";
} else {
//normally don't audit-log anything that can't be attributable
//to a user
return;
}
}
SplunkLogRecord r = new SplunkLogRecord(level, message);
r.field("category", category.name())
.field("username", username);
if (ex != null) {
r.setThrown(ex);
}
for (AuditAttribute a : attributes) {
r.field(a.getName(), a.getValue());
}
logger.log(r);
}
}
|
package pl.mkrystek.mkbot.message;
import static com.google.common.collect.Lists.newArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sqlite.JDBC;
import pl.mkrystek.mkbot.BotProperties;
public class MessageProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(MessageProvider.class);
private Connection databaseConnection;
private List<String> chatParticipants;
private Integer conversationId;
private long lastMessageId;
public MessageProvider() throws Exception {
try {
databaseConnection = JDBC.createConnection(JDBC.PREFIX + BotProperties.getSkypeDbPath(), new Properties());
extractConversationId();
extractParticipants();
} catch (SQLException e) {
LOGGER.error("Problem creating MessageProvider: ", e);
throw new Exception(e);
}
updateLastMessageId();
}
private void extractConversationId() throws SQLException {
PreparedStatement ps = databaseConnection.prepareStatement("SELECT id FROM Conversations WHERE displayname = ?");
ps.setString(1, BotProperties.getChatName());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
conversationId = rs.getInt("id");
}
ps.close();
rs.close();
}
private void extractParticipants() throws SQLException {
chatParticipants = newArrayList();
PreparedStatement ps = databaseConnection.prepareStatement("SELECT identity FROM Participants WHERE convo_id = ? AND rank <> 7");
ps.setInt(1, conversationId);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
chatParticipants.add(rs.getString("identity"));
}
ps.close();
rs.close();
}
private void updateLastMessageId() {
try {
PreparedStatement ps = databaseConnection.prepareStatement("SELECT max(id) AS 'last_id' FROM Messages WHERE convo_id = ?");
ps.setLong(1, conversationId);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
lastMessageId = rs.getLong("last_id");
}
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.error("Error during updating last message id: ", e);
}
}
public List<String> getNewMessages() {
List<String> newMessages = newArrayList();
try {
PreparedStatement ps = databaseConnection
.prepareStatement("SELECT from_dispname, body_xml FROM Messages WHERE convo_id = ? AND id > ? AND author <> ?");
ps.setInt(1, conversationId);
ps.setLong(2, lastMessageId);
ps.setString(3, BotProperties.getSkypeUsername());
ResultSet rs = ps.executeQuery();
while (rs.next()) {
newMessages.add(String.format("%s - %s", rs.getString("from_dispname"), rs.getString("body_xml")));
}
ps.close();
rs.close();
} catch (SQLException e) {
LOGGER.error("Error during new message retrieval: ", e);
} finally {
updateLastMessageId();
}
return newMessages;
}
public void close() {
try {
if (databaseConnection != null) {
databaseConnection.close();
}
} catch (SQLException e) {
LOGGER.error("Error while closing: ", e);
}
}
public List<String> getChatParticipants() {
return chatParticipants;
}
}
|
package org.graylog2.plugins.slack;
import com.google.common.base.CharMatcher;
import org.graylog2.plugin.configuration.Configuration;
import org.graylog2.plugin.configuration.ConfigurationException;
import org.graylog2.plugin.configuration.ConfigurationRequest;
import org.graylog2.plugin.configuration.fields.BooleanField;
import org.graylog2.plugin.configuration.fields.ConfigurationField;
import org.graylog2.plugin.configuration.fields.TextField;
import org.graylog2.plugin.streams.Stream;
import java.net.URI;
import java.net.URISyntaxException;
public class SlackPluginBase {
private static final CharMatcher NAME_MATCHER = CharMatcher.inRange('a', 'z')
.or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9'))
.or(CharMatcher.anyOf("_-
.precomputed();
public static final String CK_WEBHOOK_URL = "webhook_url";
public static final String CK_CHANNEL = "channel";
public static final String CK_USER_NAME = "user_name";
public static final String CK_NOTIFY_CHANNEL = "notify_channel";
public static final String CK_ADD_ATTACHMENT = "add_attachment";
public static final String CK_SHORT_MODE = "short_mode";
public static final String CK_LINK_NAMES = "link_names";
public static final String CK_ICON_URL = "icon_url";
public static final String CK_ICON_EMOJI = "icon_emoji";
public static final String CK_GRAYLOG2_URL = "graylog2_url";
public static final String CK_COLOR = "color";
public static ConfigurationRequest configuration() {
final ConfigurationRequest configurationRequest = new ConfigurationRequest();
configurationRequest.addField(new TextField(
CK_WEBHOOK_URL, "Webhook URL", "", "Slack \"Incoming Webhook\" URL",
ConfigurationField.Optional.NOT_OPTIONAL)
);
configurationRequest.addField(new TextField(
CK_CHANNEL, "Channel", "#channel", "Name of Slack #channel or @user for a direct message.",
ConfigurationField.Optional.NOT_OPTIONAL)
);
configurationRequest.addField(new TextField(
CK_USER_NAME, "User name", "Graylog",
"User name of the sender in Slack",
ConfigurationField.Optional.OPTIONAL)
);
configurationRequest.addField(new TextField(
CK_COLOR, "Color", "#FF0000",
"Color to use for Slack message",
ConfigurationField.Optional.NOT_OPTIONAL)
);
configurationRequest.addField(new BooleanField(
CK_ADD_ATTACHMENT, "Include more information", true,
"Add structured information as message attachment")
);
configurationRequest.addField(new BooleanField(
CK_SHORT_MODE, "Short mode", false,
"Enable short mode? This strips down the Slack message to the bare minimum to take less space in the chat room. " +
"Not used in alarm callback but only in the message output module.")
);
configurationRequest.addField(new BooleanField(
CK_NOTIFY_CHANNEL, "Notify Channel", false,
"Notify all users in channel by adding @channel to the message.")
);
configurationRequest.addField(new BooleanField(
CK_LINK_NAMES, "Link names", true,
"Find and link channel names and user names")
);
configurationRequest.addField(new TextField(
CK_ICON_URL, "Icon URL", null,
"Image to use as the icon for this message",
ConfigurationField.Optional.OPTIONAL)
);
configurationRequest.addField(new TextField(
CK_ICON_EMOJI, "Icon Emoji", null,
"Emoji to use as the icon for this message (overrides Icon URL)",
ConfigurationField.Optional.OPTIONAL)
);
configurationRequest.addField(new TextField(
CK_GRAYLOG2_URL, "Graylog URL", null,
"URL to your Graylog web interface. Used to build links in alarm notification.",
ConfigurationField.Optional.OPTIONAL)
);
return configurationRequest;
}
public static void checkConfiguration(Configuration configuration) throws ConfigurationException {
if (!configuration.stringIsSet(CK_WEBHOOK_URL)) {
throw new ConfigurationException(CK_WEBHOOK_URL + " is mandatory and must not be empty.");
}
if (!configuration.stringIsSet(CK_CHANNEL)) {
throw new ConfigurationException(CK_CHANNEL + " is mandatory and must not be empty.");
}
if (!configuration.stringIsSet(CK_COLOR)) {
throw new ConfigurationException(CK_COLOR + " is mandatory and must not be empty.");
}
if (!configuration.stringIsSet(CK_USER_NAME)) {
throw new ConfigurationException(CK_USER_NAME + " is mandatory and must not be empty.");
}
// work around for "null" string bug in graylog-server v1.2
if (configuration.stringIsSet(CK_ICON_URL) && !configuration.getString(CK_ICON_URL).equals("null")) {
try {
final URI iconUri = new URI(configuration.getString(CK_ICON_URL));
if (!"http".equals(iconUri.getScheme()) && !"https".equals(iconUri.getScheme())) {
throw new ConfigurationException(CK_ICON_URL + " must be a valid HTTP or HTTPS URL.");
}
} catch (URISyntaxException e) {
throw new ConfigurationException("Couldn't parse " + CK_ICON_URL + " correctly.", e);
}
}
// work around for "null" string bug in graylog-server v1.2
if (configuration.stringIsSet(CK_GRAYLOG2_URL) && !configuration.getString(CK_GRAYLOG2_URL).equals("null")) {
try {
final URI graylog2Uri = new URI(configuration.getString(CK_GRAYLOG2_URL));
if (!"http".equals(graylog2Uri.getScheme()) && !"https".equals(graylog2Uri.getScheme())) {
throw new ConfigurationException(CK_GRAYLOG2_URL + " must be a valid HTTP or HTTPS URL.");
}
} catch (URISyntaxException e) {
throw new ConfigurationException("Couldn't parse " + CK_GRAYLOG2_URL + " correctly.", e);
}
}
}
protected String buildStreamLink(String baseUrl, Stream stream) {
if (!baseUrl.endsWith("/")) {
baseUrl = baseUrl + "/";
}
return baseUrl + "streams/" + stream.getId() + "/messages?q=*&rangetype=relative&relative=3600";
}
}
|
package refinedstorage.inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.items.ItemStackHandler;
public class BasicItemHandler extends ItemStackHandler {
private TileEntity tile;
private IItemValidator[] validators;
public BasicItemHandler(int size, TileEntity tile, IItemValidator... validators) {
super(size);
this.tile = tile;
this.validators = validators;
}
public BasicItemHandler(int size, IItemValidator... validators) {
this(size, null, validators);
}
@Override
public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) {
if (validators.length > 0) {
for (IItemValidator validator : validators) {
if (validator.valid(stack)) {
return super.insertItem(slot, stack, simulate);
}
}
return stack;
}
return super.insertItem(slot, stack, simulate);
}
@Override
protected void onContentsChanged(int slot) {
super.onContentsChanged(slot);
if (tile != null) {
tile.markDirty();
}
}
}
|
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.uber.jenkins.phabricator.utils;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
public class LoggerTest {
private ByteArrayOutputStream byteArrayOutputStream;
private PrintStream stream;
private Logger logger;
@Before
public void setup() {
byteArrayOutputStream = new ByteArrayOutputStream();
stream = new PrintStream(byteArrayOutputStream);
logger = new Logger(stream);
}
@Test
public void testInfo() {
String tag = "phabricator-jenkins";
String message = "This is a great plugin!";
logger.info(tag, message);
assertEquals("[phabricator-jenkins] This is a great plugin!\n", byteArrayOutputStream.toString());
}
}
|
package org.javarosa.core.services;
import org.javarosa.core.services.properties.IPropertyRules;
import org.javarosa.core.services.properties.Property;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.services.storage.StorageManager;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.Vector;
/**
* PropertyManager is a class that is used to set and retrieve name/value pairs
* from persistent storage.
*
* Which properties are allowed, and what they can be set to, can be specified by an implementation of
* the IPropertyRules interface, any number of which can be registered with a property manager. All
* property rules are inclusive, and can only increase the number of potential properties or property
* values.
*
* @author Clayton Sims
*/
public class PropertyManager implements IPropertyManager {
/**
* The name for the Persistent storage utility name
*/
public static final String STORAGE_KEY = "PROPERTY";
/**
* The persistent storage utility
*/
private final IStorageUtilityIndexed properties;
/**
* Constructor for this PropertyManager
*/
public PropertyManager(IStorageUtilityIndexed properties) {
this.properties = properties;
}
/**
* Retrieves the singular property specified, as long as it exists in one of the current rulesets
*
* @param propertyName the name of the property being retrieved
* @return The String value of the property specified if it exists, is singluar, and is in one the current
* rulessets. null if the property is denied by the current ruleset, or is a vector.
*/
@Override
public String getSingularProperty(String propertyName) {
String retVal = null;
Vector value = getValue(propertyName);
if (value != null && value.size() == 1) {
retVal = (String)value.elementAt(0);
}
return retVal;
}
/**
* Retrieves the property specified, as long as it exists in one of the current rulesets
*
* @param propertyName the name of the property being retrieved
* @return The String value of the property specified if it exists, and is the current ruleset, if one exists.
* null if the property is denied by the current ruleset.
*/
@Override
public Vector getProperty(String propertyName) {
return getValue(propertyName);
}
/**
* Sets the given property to the given string value, if both are allowed by any existing ruleset
*
* @param propertyName The property to be set
* @param propertyValue The value that the property will be set to
*/
@Override
public void setProperty(String propertyName, String propertyValue) {
Vector<String> wrapper = new Vector<>();
wrapper.addElement(propertyValue);
setProperty(propertyName, wrapper);
}
/**
* Sets the given property to the given vector value, if both are allowed by any existing ruleset
*
* @param propertyName The property to be set
* @param propertyValue The value that the property will be set to
*/
@Override
public void setProperty(String propertyName, Vector<String> propertyValue) {
Vector oldValue = getProperty(propertyName);
if (oldValue != null && vectorEquals(oldValue, propertyValue)) {
//No point in redundantly setting values!
return;
}
writeValue(propertyName, propertyValue);
}
private boolean vectorEquals(Vector v1, Vector v2) {
if (v1.size() != v2.size()) {
return false;
} else {
for (int i = 0; i < v1.size(); ++i) {
if (!v1.elementAt(i).equals(v2.elementAt(i))) {
return false;
}
}
}
return true;
}
/**
* Retrieves the set of rules being used by this property manager if any exist.
*
* @return The rulesets being used by this property manager
*/
@Override
public Vector getRules() {
throw new RuntimeException("PropertyManager rules not implemented");
}
/**
* Adds a set of rules to be used by this PropertyManager.
* Note that rules sets are inclusive, they add new possible
* values, never remove possible values.
*
* @param rules The set of rules to be added to the permitted list
*/
@Override
public void addRules(IPropertyRules rules) {
throw new RuntimeException("PropertyManager rules not implemented");
}
public Vector getValue(String name) {
try {
Property p = (Property)properties.getRecordForValue("NAME", name);
return p.value;
} catch (NoSuchElementException nsee) {
return null;
}
}
private void writeValue(String propertyName, Vector value) {
Property theProp = new Property();
theProp.name = propertyName;
theProp.value = value;
Vector IDs = properties.getIDsForValue("NAME", propertyName);
if (IDs.size() == 1) {
theProp.setID((Integer)IDs.elementAt(0));
}
properties.write(theProp);
}
}
|
package ro.satrapu.jeedeploytocloud;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author satrapu
*/
@WebServlet(name = "StatusServlet", urlPatterns = {"/status"})
public class StatusServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Resource(name = "java:jboss/datasources/PostgreSQLDS")
private DataSource dataSource;
/**
* Processes HTTP requests.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Status</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Status</h1>");
Map<String, Object> statusInfo = getStatusInfo(request);
writeStatus(statusInfo, out);
out.println("</body>");
out.println("</html>");
}
}
/**
* @param request
* @return
*/
private Map<String, Object> getStatusInfo(HttpServletRequest request) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("Server IP", request.getLocalAddr());
result.put("Server name", request.getLocalName());
result.put("Server port", request.getLocalPort());
result.put("Java version", System.getProperty("java.version"));
try {
DatabaseMetaData databaseMetaData = dataSource.getConnection().getMetaData();
result.put("JDBC driver name", databaseMetaData.getDriverName());
result.put("JDBC driver version", databaseMetaData.getDriverVersion());
result.put("Database product name", databaseMetaData.getDatabaseProductName());
result.put("Database product version", databaseMetaData.getDatabaseProductVersion());
} catch (SQLException e) {
e.printStackTrace();
result.put("Data source", "Unable to get data source info");
}
result.put("Client IP", request.getRemoteAddr());
result.put("Client name", request.getRemoteHost());
result.put("Request URI", request.getRequestURI());
result.put("Request method", request.getMethod());
result.put("Current date", DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now()));
return result;
}
/**
* @param statusInfo
* @param writer
*/
private static void writeStatus(Map<String, Object> statusInfo, PrintWriter writer) {
writer.println("<ul>");
for (String key : statusInfo.keySet()) {
Object value = statusInfo.get(key);
writer.println("<li>");
writer.println(MessageFormat.format("{0}: {1}", key, value));
writer.println("</li>");
}
writer.println("</ul>");
}
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
throw new ServletException(new UnsupportedOperationException("POST verb not supported"));
}
}
|
package com.wolfninja.keystore.redis;
import java.util.Optional;
import org.easymock.EasyMock;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.wolfninja.keystore.api.Keyspace;
import redis.clients.jedis.JedisPool;
@SuppressWarnings("javadoc")
@Test
public class RedisAdapterTest {
@Test(dataProvider = "buildKeyspaceNameData")
public void buildKeyspaceName(final String inputPrefix, final String expected) {
final JedisPool mockPool = EasyMock.createMock(JedisPool.class);
final RedisAdapter adapter = RedisAdapter.create(mockPool, inputPrefix);
final String actual = adapter.buildKeyspaceName("myKeyspace");
Assert.assertEquals(actual, expected);
}
@DataProvider
Object[][] buildKeyspaceNameData() {
return new Object[][] {
{ null, "myKeyspace" },
{ "nice_", "nice_myKeyspace" },
};
}
@Test
public void create() {
final JedisPool mockPool = EasyMock.createMock(JedisPool.class);
final RedisAdapter actual = RedisAdapter.create(mockPool);
Assert.assertNotNull(actual);
}
@Test
public void createWithPrefix() {
final JedisPool mockPool = EasyMock.createMock(JedisPool.class);
final RedisAdapter actual = RedisAdapter.create(mockPool, "asdf_");
Assert.assertNotNull(actual);
Assert.assertEquals(actual.getKeyspacePrefix(), Optional.of("asdf_"));
}
@Test
public void getKeyspace() {
final JedisPool mockPool = EasyMock.createMock(JedisPool.class);
final RedisAdapter adapter = RedisAdapter.create(mockPool);
final Keyspace actual = adapter.getKeyspace("my.keyspace");
Assert.assertEquals(actual.getClass(), RedisKeyspace.class);
}
}
|
package org.kuali.kfs.coa.businessobject;
import java.util.logging.Logger;
public class FundGroup {
protected String code;
protected String name;
protected boolean active = true;
private String financialReportingSortCode;
private String fundGroupBudgetAdjustmentRestrictionLevelCode;
private static Logger LOG = Logger.getLogger(FundGroup.class.getName());
/**
* @return Getter for the Code.
*/
public String getCode() {
return code;
}
/**
* @param code - Setter for the Code.
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return Getter for the Name.
*/
public String getName() {
return name;
}
/**
* @param name - Setter for the name.
*/
public void setName(String name) {
this.name = name;
}
/**
* @return Getter for the active field.
*/
public boolean isActive() {
return active;
}
/**
* @param a - Setter for the active field.
*/
public void setActive(boolean a) {
this.active = a;
}
/**
* Static helper method to allow other classes to provide consistent "code and description"
* behavior, even if not extending from this class.
*/
public static String getCodeAndDescription(String code, String desc) {
if (code != null) {
if (desc == null) {
return code;
} else {
return code + " - " + desc;
}
}
return "";
}
/**
* This method...
*
* @return
*/
public String getFinancialReportingSortCode() {
return financialReportingSortCode;
}
/**
* This method...
*
* @param financialReportingSortCode
*/
public void setFinancialReportingSortCode(String financialReportingSortCode) {
this.financialReportingSortCode = financialReportingSortCode;
}
/**
* Gets the fundGroupBudgetAdjustmentRestrictionLevelCode attribute.
*
* @return Returns the fundGroupBudgetAdjustmentRestrictionLevelCode.
*/
public String getFundGroupBudgetAdjustmentRestrictionLevelCode() {
return fundGroupBudgetAdjustmentRestrictionLevelCode;
}
/**
* Sets the fundGroupBudgetAdjustmentRestrictionLevelCode attribute value.
*
* @param fundGroupBudgetAdjustmentRestrictionLevelCode The fundGroupBudgetAdjustmentRestrictionLevelCode to set.
*/
public void setFundGroupBudgetAdjustmentRestrictionLevelCode(String fundGroupBudgetAdjustmentRestrictionLevelCode) {
this.fundGroupBudgetAdjustmentRestrictionLevelCode = fundGroupBudgetAdjustmentRestrictionLevelCode;
}
}
|
package org.leibnizcenter.rechtspraak.crf;
import cc.mallet.fst.*;
import cc.mallet.pipe.Pipe;
import cc.mallet.pipe.TokenSequence2FeatureVectorSequence;
import cc.mallet.types.*;
import cc.mallet.util.CommandOption;
import org.leibnizcenter.rechtspraak.features.Features;
import org.leibnizcenter.rechtspraak.tokens.*;
import org.leibnizcenter.rechtspraak.tokens.Label;
import org.leibnizcenter.rechtspraak.tokens.text.TokenTreeLeaf;
import org.leibnizcenter.rechtspraak.tokens.tokentree.TokenTree;
import org.leibnizcenter.rechtspraak.tokens.tokentree.TokenTreeVertex;
import org.leibnizcenter.rechtspraak.util.Const;
import org.leibnizcenter.rechtspraak.util.Xml;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class TrainCrf {
private static final int MAX_DOCS = -1;
private static final CommandOption.Double gaussianVarianceOption = new CommandOption.Double
(SimpleTagger.class, "gaussian-variance", "DECIMAL", true, 10.0,
"The gaussian prior variance used for training.", null);
private static final CommandOption.Boolean trainOption = new CommandOption.Boolean
(SimpleTagger.class, "train", "true|false", true, false,
"Whether to train", null);
private static final CommandOption.String testOption = new CommandOption.String
(SimpleTagger.class, "test", "lab or seg=start-1.continue-1,...,start-n.continue-n",
true, null,
"Test measuring labeling or segmentation (start-i, continue-i) accuracy", null);
private static final CommandOption.File modelOption = new CommandOption.File
(SimpleTagger.class, "model-file", "FILENAME", true, null,
"The filename for reading (train/run) or saving (train) the model.", null);
private static final CommandOption.Double trainingFractionOption = new CommandOption.Double
(SimpleTagger.class, "training-proportion", "DECIMAL", true, 0.5,
"Fraction of data to use for training in a random split.", null);
private static final CommandOption.Integer randomSeedOption = new CommandOption.Integer
(SimpleTagger.class, "random-seed", "INTEGER", true, 0,
"The random seed for randomly selecting a proportion of the instance list for training", null);
private static final CommandOption.IntegerArray ordersOption = new CommandOption.IntegerArray
(SimpleTagger.class, "orders", "COMMA-SEP-DECIMALS", true, new int[]{1},
"List of label Markov orders (main and backoff) ", null);
private static final CommandOption.String forbiddenOption = new CommandOption.String(
SimpleTagger.class, "forbidden", "REGEXP", true,
"\\s", "label1,label2 transition forbidden if it find this", null);
private static final CommandOption.String allowedOption = new CommandOption.String(
SimpleTagger.class, "allowed", "REGEXP", true,
".*", "label1,label2 transition allowed only if it find this", null);
private static final CommandOption.String defaultOption = new CommandOption.String(
SimpleTagger.class, "default-label", "STRING", true, "O",
"Label for initial context and uninteresting tokens", null);
private static final CommandOption.Integer iterationsOption = new CommandOption.Integer(
SimpleTagger.class, "iterations", "INTEGER", true, Integer.MAX_VALUE,
"Number of training iterations", null);
private static final CommandOption.Boolean viterbiOutputOption = new CommandOption.Boolean(
SimpleTagger.class, "viterbi-output", "true|false", true, false,
"Print Viterbi periodically during training", null);
private static final CommandOption.Boolean connectedOption = new CommandOption.Boolean(
SimpleTagger.class, "fully-connected", "true|false", true, true,
"Include all allowed transitions, even those not in training data", null);
private static final CommandOption.String weightsOption = new CommandOption.String(
SimpleTagger.class, "weights", "sparse|some-dense|dense", true, "some-dense",
"Use sparse, some dense (using a heuristic), or dense features on transitions.", null);
private static final CommandOption.Boolean continueTrainingOption = new CommandOption.Boolean(
SimpleTagger.class, "continue-training", "true|false", false, false,
"Continue training from model specified by --model-file", null);
private static final CommandOption.Integer nBestOption = new CommandOption.Integer(
SimpleTagger.class, "n-best", "INTEGER", true, 1,
"How many answers to output", null);
private static final CommandOption.Integer cacheSizeOption = new CommandOption.Integer(
SimpleTagger.class, "cache-size", "INTEGER", true, 100000,
"How much state information to memoize in n-best decoding", null);
private static final CommandOption.Boolean includeInputOption = new CommandOption.Boolean(
SimpleTagger.class, "include-input", "true|false", true, false,
"Whether to include the input features when printing decoding output", null);
private static final CommandOption.Boolean featureInductionOption = new CommandOption.Boolean(
SimpleTagger.class, "feature-induction", "true|false", true, false,
"Whether to perform feature induction during training", null);
private static final CommandOption.Integer numThreads = new CommandOption.Integer(
SimpleTagger.class, "threads", "INTEGER", true, 4,
"Number of threads to use for CRF training.", null);
private static Alphabet dataAlphabet = new Alphabet();
public static final Pipe pipe = new TokenSequence2FeatureVectorSequence(dataAlphabet, true, false);
private static Alphabet labelAlphabet = new LabelAlphabet();
private static Random r = new Random(69L);
public static void main(String[] args) throws IOException, ClassNotFoundException, ParserConfigurationException {
Xml.setFolders(args);
// Load a corpus
System.out.println("_____________________________________");
InstanceList il = new InstanceList(pipe);
List<File> xmlFiles = Xml.listXmlFiles(new File(Xml.OUT_FOLDER), MAX_DOCS, false);
int i = 0;
for (TokenList doc : new TokenList.FileIterable(
new TokenList.FileIterator(xmlFiles.toArray(new File[xmlFiles.size()])))
) {
List<Label> labels = TokenTree.labelFromAnnotation(doc);
Instance instance = getInstance(doc, labels, false);
il.addThruPipe(instance);
i++;
if (i % 50 == 0) {
System.out.println(i);
}
}
System.gc();
// InstanceList[] trainingLists =
// il.split(
// r, new double[]{0.8,
// 1.0 - 0.8});
// InstanceList trainingData = trainingLists[0];
// InstanceList testData = trainingLists[1];
// TokenAccuracyEvaluator eval = new TokenAccuracyEvaluator(
// new InstanceList[]{trainingData, testData}, new String[]{"Training", "Testing"}
CRF crf = constructCrf(dataAlphabet, labelAlphabet);
// CRF crf = loadCrf(new File(Const.RECHTSPRAAK_MARKUP_TAGGER_CRF));
Set<String> trnasitions = Label.getAllowedTransitions().stream()
.map((arr) -> String.join(",", arr[0].name(), arr[1].name()))
.collect(Collectors.toSet());
String allowedTransitions = String.join(" ",
trnasitions);
System.out.println(forbiddenOption.defaultValue);
train(il, null, null, ordersOption.value, defaultOption.value,
forbiddenOption.defaultValue,
allowedTransitions,
connectedOption.value, iterationsOption.value,
gaussianVarianceOption.value, crf, numThreads.value);
saveToFile(crf, new File(Const.RECHTSPRAAK_MARKUP_TAGGER_CRF));
}
/**
* Create and train a CRF model from the given training data,
* optionally testing it on the given test data.
*
* @param training training data
* @param testing test data (possibly <code>null</code>)
* @param eval accuracy evaluator (possibly <code>null</code>)
* @param orders label Markov orders (main and backoff)
* @param defaultLabel default label
* @param forbidden regular expression specifying impossible label
* transitions <em>current</em><code>,</code><em>next</em>
* (<code>null</code> indicates no forbidden transitions)
* @param allowed regular expression specifying allowed label transitions
* (<code>null</code> indicates everything is allowed that is not forbidden)
* @param connected whether to include even transitions not
* occurring in the training data.
* @param iterations number of training iterations
* @param var Gaussian prior variance
* @param numThreads Number of threads to use
* @return the trained model
*/
public static CRF train(InstanceList training, InstanceList testing,
TransducerEvaluator eval, int[] orders,
String defaultLabel,
String forbidden, String allowed,
boolean connected, int iterations, double var, CRF crf, int numThreads) {
Pattern forbiddenPat = Pattern.compile(forbidden);
Pattern allowedPat = Pattern.compile(allowed);
if (crf == null) {
crf = new CRF(training.getPipe(), null);
String startName =
crf.addOrderNStates(
training,
orders,
null,
defaultLabel,
forbiddenPat,
allowedPat,
connected);
for (int i = 0; i < crf.numStates(); i++) {
crf.getState(i).setInitialWeight(Transducer.IMPOSSIBLE_WEIGHT);
}
crf.getState(startName).setInitialWeight(0.0);
}
System.out.println("Training on " + training.size() + " instances");
if (testing != null) {
System.out.println("Testing on " + testing.size() + " instances");
}
assert (numThreads > 0);
if (numThreads > 1) {
CRFTrainerByThreadedLabelLikelihood crft = new CRFTrainerByThreadedLabelLikelihood(crf, numThreads);
crft.setGaussianPriorVariance(var);
setWeightsOptions(crft);
if (featureInductionOption.value) {
throw new IllegalArgumentException("Multi-threaded feature induction is not yet supported.");
} else {
trainWhileNotConverged(training, testing, eval, iterations, crft);
}
crft.shutdown();
} else {
CRFTrainerByLabelLikelihood crft = new CRFTrainerByLabelLikelihood(crf);
crft.setGaussianPriorVariance(var);
setWeightsOptions(crft);
if (featureInductionOption.value) {
crft.trainWithFeatureInduction(training, null, testing, eval, iterations, 10, 20, 500, 0.5, false, null);
} else {
trainWhileNotConverged(training, testing, eval, iterations, crft);
}
}
return crf;
}
private static void setWeightsOptions(CRFTrainerByThreadedLabelLikelihood crft) {
//noinspection Duplicates
switch (weightsOption.value) {
case "dense":
crft.setUseSparseWeights(false);
crft.setUseSomeUnsupportedTrick(false);
break;
case "some-dense":
crft.setUseSparseWeights(true);
crft.setUseSomeUnsupportedTrick(true);
break;
case "sparse":
crft.setUseSparseWeights(true);
crft.setUseSomeUnsupportedTrick(false);
break;
default:
throw new RuntimeException("Unknown weights option: " + weightsOption.value);
}
}
public static void setWeightsOptions(CRFTrainerByLabelLikelihood crft) {
//noinspection Duplicates
switch (weightsOption.value) {
case "dense":
crft.setUseSparseWeights(false);
crft.setUseSomeUnsupportedTrick(false);
break;
case "some-dense":
crft.setUseSparseWeights(true);
crft.setUseSomeUnsupportedTrick(true);
break;
case "sparse":
crft.setUseSparseWeights(true);
crft.setUseSomeUnsupportedTrick(false);
break;
default:
throw new RuntimeException("Unknown weights option: " + weightsOption.value);
}
}
public static void trainWhileNotConverged(InstanceList training,
InstanceList testing,
TransducerEvaluator eval,
int iterations,
TransducerTrainer crft) {
boolean converged;
for (int i = 1; i <= iterations; i++) {
converged = crft.train(training, 1);
if (i % 10 == 0 && eval != null) { // Change the 1 to higher integer to evaluate less often
eval.evaluate(crft);
}
if (viterbiOutputOption.value && i % 10 == 0) {
new ViterbiWriter("", new InstanceList[]{training, testing}, new String[]{"training", "testing"}).evaluate(crft);
}
if (converged) break;
}
}
public static Instance getInstance(List<TokenTreeLeaf> doc, List<Label> labels, boolean preserveInfo) {
TokenSequence ts = getTokenSequence(doc, preserveInfo);
LabelSequence ls = getLabelSequence(labels);
return new Instance(ts, ls, null, null);
}
public static Instance getInstance(List<TokenTreeLeaf> doc, boolean preserveInfo) {
TokenSequence ts = getTokenSequence(doc, preserveInfo);
return new Instance(ts, null, null, null);
}
public static TokenSequence getTokenSequence(List<TokenTreeLeaf> doc, boolean preserveInfo) {
TokenSequence ts = new TokenSequence(doc.size());
for (int i = 0; i < doc.size(); i++) {
TokenTreeLeaf token = doc.get(i);
Token t = new Token(null);
Features.setAllFeatures(t, doc, i);
if (preserveInfo) {
t.setText(token.getTextContent().trim());
t.setProperty(Const.RECHTSPRAAK_TOKEN, token);
}
ts.add(t);
}
return ts;
}
public static LabelSequence getLabelSequence(List<Label> doc) {
LabelSequence ls = new LabelSequence(labelAlphabet);
doc.forEach(l -> ls.add(l.name()));
return ls;
}
private static CRF constructCrf(Alphabet inputAlphabet, Alphabet outputAlphabet) {
CRF crf = new CRF(inputAlphabet, outputAlphabet);
// Add states
String[] destinations = Arrays.stream(Label.values())
.map(Enum::name)
.collect(Collectors.toSet())
.toArray(new String[Label.values().length]);
for (Label l2 : Label.values()) crf.addState(l2.name(), destinations);
// CRFOptimizableBy* objects (terms in the objective function)
// CRF trainer
// evaluator and writer
return crf;
}
private static void saveToFile(CRF crf, File file) {
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(crf);
fos.close();
System.out.println("Written CRF to " + file.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package de.ids_mannheim.korap.index;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.lucene.store.MMapDirectory;
import org.junit.Ignore;
import org.junit.Test;
import de.ids_mannheim.korap.KrillIndex;
public class TestIndexRevision {
@Test
public void testIndexRevisionAdd () throws IOException {
KrillIndex ki = new KrillIndex();
assertEquals(ki.getFingerprint(),"null");
ki.addDoc(getClass().getResourceAsStream("/wiki/00001.json.gz"), true);
ki.commit();
String x1 = ki.getFingerprint();
assertEquals("ibtSULzKIMrfGAtES3GXRA==",x1);
ki.addDoc(getClass().getResourceAsStream("/wiki/00002.json.gz"), true);
ki.addDoc(getClass().getResourceAsStream("/wiki/00003.json.gz"), true);
ki.addDoc(getClass().getResourceAsStream("/wiki/00004.json.gz"), true);
ki.commit();
String x2 = ki.getFingerprint();
assertEquals("0UIQZpZVfiGDD2leAq6YQA==",x2);
ki.addDoc(getClass().getResourceAsStream("/wiki/00006.json.gz"), true);
ki.commit();
String x3 = ki.getFingerprint();
assertEquals("fS3GqnKynhPQ5wFyC9/XWw==",x3);
// Check if the same changes will have the same effect
KrillIndex ki2 = new KrillIndex();
assertEquals("null",ki2.getFingerprint());
ki2.addDoc(getClass().getResourceAsStream("/wiki/00001.json.gz"), true);
ki2.commit();
assertEquals(x1, ki2.getFingerprint());
ki2.addDoc(getClass().getResourceAsStream("/wiki/00002.json.gz"), true);
ki2.addDoc(getClass().getResourceAsStream("/wiki/00003.json.gz"), true);
ki2.addDoc(getClass().getResourceAsStream("/wiki/00004.json.gz"), true);
ki2.commit();
assertEquals(x2, ki2.getFingerprint());
ki2.addDoc(getClass().getResourceAsStream("/wiki/00006.json.gz"), true);
ki2.commit();
assertEquals(x3, ki2.getFingerprint());
};
@Test
public void testIndexRevisionDel () throws IOException {
KrillIndex ki = new KrillIndex();
assertEquals(ki.getFingerprint(),"null");
ki.addDoc(getClass().getResourceAsStream("/wiki/00001.json.gz"), true);
ki.commit();
String x1 = ki.getFingerprint();
assertEquals("ibtSULzKIMrfGAtES3GXRA==",x1);
assertTrue(ki.delDocs("title", "A"));
ki.commit();
String x2 = ki.getFingerprint();
assertNotEquals(x1, x2);
};
@Test
public void testIndexRevisionTempFile () throws IOException {
Path tmpdir = Files.createTempDirectory("wiki");
KrillIndex ki = new KrillIndex(new MMapDirectory(tmpdir));
assertEquals("null", ki.getFingerprint());
ki.addDoc(getClass().getResourceAsStream("/wiki/00001.json.gz"), true);
ki.commit();
ki.addDoc(getClass().getResourceAsStream("/wiki/00002.json.gz"), true);
ki.addDoc(getClass().getResourceAsStream("/wiki/00003.json.gz"), true);
ki.addDoc(getClass().getResourceAsStream("/wiki/00004.json.gz"), true);
ki.commit();
ki.addDoc(getClass().getResourceAsStream("/wiki/00006.json.gz"), true);
ki.commit();
assertTrue(ki.delDocs("title", "A"));
ki.commit();
assertEquals(false, ki.isReaderOpen());
String fingerp = "aoD2zQvZKa8oQPjFJlji1g==";
assertEquals(fingerp, ki.getFingerprint());
assertEquals(true, ki.isReaderOpen());
assertEquals(4, ki.numberOf("base", "documents"));
assertEquals(fingerp, ki.getFingerprint());
ki.close();
// Reload index
ki = new KrillIndex(new MMapDirectory(tmpdir));
assertEquals(fingerp, ki.getFingerprint());
ki.close();
};
@Ignore
public void testIndexRevisionSample () throws IOException {
KrillIndex ki = new KrillIndex(new MMapDirectory(
Paths.get(getClass().getResource("/sample-index").getFile())));
assertEquals("Wes8Bd4h1OypPqbWF5njeQ==",ki.getFingerprint());
};
};
|
package org.lightmare.jpa.datasource.c3p0;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
import javax.naming.Context;
import javax.sql.DataSource;
import org.lightmare.jpa.datasource.InitDataSource;
import org.lightmare.jpa.datasource.InitMessages;
import org.lightmare.jpa.datasource.Initializer;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
import com.mchange.v2.c3p0.PooledDataSource;
/**
* Initializes and bind to {@link Context} c3p0 pooled {@link DataSource} object
*
* @author Levan Tsinadze
* @since 0.0.79-SNAPSHOT
*/
public class InitC3p0 extends InitDataSource {
public InitC3p0(Properties properties) {
super(properties);
}
/**
* Initializes appropriated driver and {@link DataSource} objects
*
* @param properties
* @return {@link DataSource}
* @throws IOException
*/
@Override
public DataSource initializeDataSource() throws IOException {
DataSource namedDataSource;
DataSource dataSource;
try {
if (poolConfig.isPooledDataSource()) {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
dataSource = comboPooledDataSource;
} else {
// Initializes and loads data base driver class by name
Initializer.initializeDriver(driver);
dataSource = DataSources
.unpooledDataSource(url, user, password);
}
Map<Object, Object> configMap = poolConfig.merge(properties);
namedDataSource = DataSources.pooledDataSource(dataSource,
configMap);
} catch (SQLException ex) {
throw new IOException(ex);
} catch (PropertyVetoException ex) {
throw new IOException(ex);
}
return namedDataSource;
}
@Override
protected boolean checkInstance(DataSource dataSource) throws IOException {
boolean valid = (dataSource instanceof PooledDataSource);
return valid;
}
/**
* Destroys passed {@link DataSource} for shut down
*
* @param dataSource
*/
@Override
public void cleanUp(DataSource dataSource) {
try {
DataSources.destroy(dataSource);
} catch (SQLException ex) {
LOG.error(InitMessages.COULD_NOT_CLOSE_ERROR, ex);
}
}
}
|
package seedu.emeraldo.logic.commands;
/**
* Lists all persons in the address book to the user.
*/
public class ListCommand extends Command {
public static final String COMMAND_WORD = "list";
public static final String MESSAGE_SUCCESS = "Listed all tasks";
public ListCommand() {}
@Override
public CommandResult execute() {
model.updateFilteredListToShowAll();
return new CommandResult(MESSAGE_SUCCESS);
}
}
|
package hudson.remoting;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author Kohsuke Kawaguchi
*/
public class SingleLaneExecutorServiceTest extends Assert {
ExecutorService base = Executors.newFixedThreadPool(5);
ExecutorService lane1 = new SingleLaneExecutorService(base);
ExecutorService lane2 = new SingleLaneExecutorService(base);
@After
public void tearDown() {
base.shutdown();
}
/**
* Schedule two heavy tasks in one lane, and one task in another lane.
* The second lane should finish first and the first heavy lane should take turns.
*/
@Test
public void laneIndependence() throws Exception {
final Object lock = new Object();
final StringBuilder record = new StringBuilder();
synchronized (lock) {
lane1.submit(new Runnable() {
public void run() {
synchronized (lock) {}
sleep(1000);
record.append("x");
}
});
lane1.submit(new Runnable() {
public void run() {
record.append("y");
}
});
lane2.submit(new Runnable() {
public void run() {
record.append("z");
}
});
}
waitForCompletion(lane1);
waitForCompletion(lane2);
assertEquals("zxy",record.toString());
}
/**
* Tasks should execute in order even when there are a lot of capacities to execute them.
*/
@Test
public void fifo() throws Exception {
final Random r = new Random(0);
class Workload {
List<Runnable> tasks = new LinkedList<Runnable>();
StringBuilder record = new StringBuilder();
ExecutorService lane = new SingleLaneExecutorService(base);
Workload() {
for (char t='a'; t<='z'; t++) {
final char ch = t;
tasks.add(new Runnable() {
public void run() {
sleep(50+r.nextInt(100));
record.append(ch);
}
});
}
}
}
List<Workload> works = new ArrayList<Workload>();
for (int i=0; i<5; i++)
works.add(new Workload());
// submit them all in the queue
List<Workload> remaining = new ArrayList<Workload>(works);
int total = (('z' - 'a') + 1) * works.size();
for (int i=0; i<total; i++) {
while (true) {
int j = r.nextInt(remaining.size());
Workload wl = remaining.get(j);
if (!wl.tasks.isEmpty()) {
wl.lane.submit(wl.tasks.remove(0));
break;
} else {
remaining.remove(wl);
}
}
}
// the execution order must have been preserved.
for (Workload wl : works) {
waitForCompletion(wl.lane);
assertEquals("abcdefghijklmnopqrstuvwxyz",wl.record.toString());
}
}
private void waitForCompletion(ExecutorService es) throws InterruptedException {
es.shutdown();
es.awaitTermination(5000, TimeUnit.MILLISECONDS);
}
private void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new Error();
}
}
}
|
package org.lognavigator.controller;
import static org.lognavigator.util.Constants.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.lognavigator.bean.Breadcrumb;
import org.lognavigator.bean.FileInfo;
import org.lognavigator.bean.TableCell;
import org.lognavigator.exception.LogAccessException;
import org.lognavigator.service.LogAccessService;
import org.lognavigator.util.BreadcrumbFactory;
import org.lognavigator.util.FileInfoFactory;
import org.lognavigator.util.TableCellFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class ListController {
@Autowired
@Qualifier("facade")
private LogAccessService logAccessService;
@RequestMapping("/{logAccessConfigId}/list")
public String list(Model model,
@PathVariable String logAccessConfigId,
@RequestParam(value="subPath", required=false) String subPath
)
throws LogAccessException, IOException {
// Get the log files list
Set<FileInfo> fileInfos = logAccessService.listFiles(logAccessConfigId, subPath);
// Add link to parent folder
if (subPath != null) {
FileInfo parentFolderLink = FileInfoFactory.createParentFolderLink(subPath);
fileInfos.add(parentFolderLink);
}
// Prepare the table lines for HTML presentation
List<List<TableCell>> tableLines = new ArrayList<List<TableCell>>(fileInfos.size());
// Construct cells for files and folders
for (FileInfo fileInfo : fileInfos) {
List<TableCell> lineCells = TableCellFactory.createTableCellList(fileInfo);
tableLines.add(lineCells);
}
model.addAttribute(TABLE_HEADERS_KEY, Arrays.asList(FILE_TABLE_HEADER, SIZE_TABLE_HEADER, DATE_TABLE_HEADER, ACTIONS_TABLE_HEADER));
model.addAttribute(TABLE_LINES_KEY, tableLines);
model.addAttribute(TABLE_LAYOUT_CLASS_KEY, TABLE_LAYOUT_CENTERED);
// Construct breadcrumbs
if (subPath != null) {
List<Breadcrumb> breadcrumbs = BreadcrumbFactory.createBreadCrumbs(logAccessConfigId);
BreadcrumbFactory.addSubPath(breadcrumbs, subPath, false);
model.addAttribute(BREADCRUMBS_KEY, breadcrumbs);
}
// Return view to display
return PREPARE_MAIN_VIEW;
}
}
|
package techreborn.compat.recipes;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import forestry.api.arboriculture.EnumWoodType;
import forestry.api.arboriculture.TreeManager;
import forestry.api.fuels.FuelManager;
import forestry.api.fuels.GeneratorFuel;
import forestry.core.config.Version;
import ic2.api.item.IC2Items;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
import techreborn.api.fuel.FluidPowerManager;
import techreborn.api.recipe.RecipeHandler;
import techreborn.api.recipe.machines.IndustrialSawmillRecipe;
import techreborn.compat.ICompatModule;
import techreborn.config.ConfigTechReborn;
import java.util.Iterator;
import java.util.Map;
public class RecipesForestry implements ICompatModule {
@Override
public void preInit(FMLPreInitializationEvent event) {
}
@Override
public void init(FMLInitializationEvent event) {
}
@Override
public void postInit(FMLPostInitializationEvent event) {
if (ConfigTechReborn.AllowForestryRecipes) {
ItemStack pulpStack = OreDictionary.getOres("pulpWood").get(0);
for (EnumWoodType woodType : EnumWoodType.VALUES) {
ItemStack log = TreeManager.woodItemAccess.getLog(woodType, true);
log.stackSize = 1;
ItemStack plank = TreeManager.woodItemAccess.getPlanks(woodType, true);
plank.stackSize = 6;
System.out.println(log.getDisplayName() + ":" + plank.getDisplayName());
RecipeHandler.addRecipe(new IndustrialSawmillRecipe(log, null, new FluidStack(FluidRegistry.WATER, 1000), plank, pulpStack, null, 200, 30, false));
RecipeHandler.addRecipe(new IndustrialSawmillRecipe(log, IC2Items.getItem("waterCell"), null, plank, pulpStack, IC2Items.getItem("cell"), 200, 30, false));
RecipeHandler.addRecipe(new IndustrialSawmillRecipe(log, new ItemStack(Items.water_bucket), null, plank, pulpStack, new ItemStack(Items.bucket), 200, 30, false));
log = TreeManager.woodItemAccess.getLog(woodType, false);
log.stackSize = 1;
plank = TreeManager.woodItemAccess.getPlanks(woodType, false);
plank.stackSize = 6;
System.out.println(log.getDisplayName() + ":" + plank.getDisplayName());
RecipeHandler.addRecipe(new IndustrialSawmillRecipe(log, null, new FluidStack(FluidRegistry.WATER, 1000), plank, pulpStack, null, 200, 30, false));
RecipeHandler.addRecipe(new IndustrialSawmillRecipe(log, IC2Items.getItem("waterCell"), null, plank, pulpStack, IC2Items.getItem("cell"), 200, 30, false));
RecipeHandler.addRecipe(new IndustrialSawmillRecipe(log, new ItemStack(Items.water_bucket), null, plank, pulpStack, new ItemStack(Items.bucket), 200, 30, false));
}
}
Iterator entries = FuelManager.generatorFuel.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry thisEntry = (Map.Entry) entries.next();
Fluid fluid = (Fluid) thisEntry.getKey();
GeneratorFuel generatorFuel = (GeneratorFuel) thisEntry.getValue();
FluidPowerManager.fluidPowerValues.put(fluid, (double) (generatorFuel.eu / generatorFuel.rate));
}
}
@Override
public void serverStarting(FMLServerStartingEvent event) {
}
}
|
package org.mbari.m3.vars.annotation;
import io.reactivex.Observable;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.stage.FileChooser;
import org.mbari.io.IOUtilities;
import org.mbari.m3.vars.annotation.mediaplayers.MediaPlayer;
import org.mbari.m3.vars.annotation.mediaplayers.MediaPlayers;
import org.mbari.m3.vars.annotation.messages.*;
import org.mbari.m3.vars.annotation.events.*;
import org.mbari.m3.vars.annotation.model.Annotation;
import org.mbari.m3.vars.annotation.model.Media;
import org.mbari.m3.vars.annotation.services.CachedConceptService;
import org.mbari.m3.vars.annotation.services.ConceptService;
import org.mbari.m3.vars.annotation.ui.Alerts;
import org.mbari.m3.vars.annotation.ui.AnnotationServiceDecorator;
import org.mbari.m3.vars.annotation.ui.AppPaneController;
import org.mbari.net.URLUtilities;
import org.mbari.util.SystemUtilities;
import org.mbari.vcr4j.VideoError;
import org.mbari.vcr4j.VideoState;
import org.mbari.vcr4j.time.Timecode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.security.Key;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.UUID;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
/**
* @author Brian Schlining
* @since 2017-05-10T09:55:00
*/
public class AppController {
private Scene scene;
private final UIToolBox toolBox;
private final Alerts alerts;
// Should automatically open the correct player. Listens for MediaChangedEvents
private final MediaPlayers mediaPlayers;
private final Logger log = LoggerFactory.getLogger(getClass());
private final FileChooser fileChooser = new FileChooser();
public AppController(UIToolBox toolBox) {
this.toolBox = toolBox;
alerts = new Alerts(toolBox);
mediaPlayers = new MediaPlayers(toolBox);
initialize();
}
public Scene getScene() {
if (scene == null) {
//AppPaneController paneController = new AppPaneController(toolBox);
AppPaneController paneController = new AppPaneController(toolBox);
scene = new Scene(paneController.getRoot());
scene.getStylesheets()
.addAll(toolBox.getStylesheets());
KeyCombination.Modifier osModifier = SystemUtilities.isMacOS() ?
KeyCombination.META_DOWN : KeyCombination.CONTROL_DOWN;
KeyCodeCombination spaceCombo = new KeyCodeCombination(KeyCode.SPACE, KeyCombination.CONTROL_DOWN);
KeyCodeCombination downCombo = new KeyCodeCombination(KeyCode.DOWN, osModifier);
KeyCodeCombination upCombo = new KeyCodeCombination(KeyCode.UP, osModifier);
KeyCodeCombination nCombo = new KeyCodeCombination(KeyCode.N, osModifier);
KeyCodeCombination cCombo = new KeyCodeCombination(KeyCode.G, osModifier);
KeyCodeCombination tCombo = new KeyCodeCombination(KeyCode.T, osModifier);
KeyCodeCombination fCombo = new KeyCodeCombination(KeyCode.F, osModifier);
KeyCodeCombination deleteCombo = new KeyCodeCombination(KeyCode.DELETE, osModifier);
scene.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
if (spaceCombo.match(e)) {
MediaPlayer<? extends VideoState, ? extends VideoError> mediaPlayer = toolBox.getMediaPlayer();
if (mediaPlayer != null) {
mediaPlayer.requestIsPlaying()
.thenAccept(playing -> {
if (playing) {
mediaPlayer.stop();
} else {
mediaPlayer.play();
}
});
}
e.consume();
}
else if (downCombo.match(e)) {
TableView.TableViewSelectionModel<Annotation> selectionModel = paneController.getAnnotationTableController()
.getTableView()
.getSelectionModel();
int idx = selectionModel.getSelectedIndex();
selectionModel.clearSelection();
selectionModel.select(idx + 1);
e.consume();
}
else if (upCombo.match(e)) {
TableView.TableViewSelectionModel<Annotation> selectionModel = paneController.getAnnotationTableController()
.getTableView()
.getSelectionModel();
int idx = selectionModel.getSelectedIndex();
selectionModel.clearSelection();
selectionModel.select(idx - 1);
e.consume();
}
else if (nCombo.match(e)) {
toolBox.getEventBus().send(new NewAnnotationMsg());
e.consume();
}
else if(cCombo.match(e)) {
toolBox.getEventBus().send(new CopyAnnotationMsg());
e.consume();
}
else if (tCombo.match(e)) {
toolBox.getEventBus().send(new DuplicateAnnotationMsg());
e.consume();
}
else if (fCombo.match(e)) {
toolBox.getEventBus().send(new FramecaptureMsg());
e.consume();
}
else if (deleteCombo.match(e)) {
toolBox.getEventBus().send(new DeleteAnnotationsMsg());
e.consume();
}
});
}
return scene;
}
private void initialize() {
// wire up data to listen to events
EventBus eventBus = toolBox.getEventBus();
Data data = toolBox.getData();
Observable<Object> eventObservable = eventBus.toObserverable();
eventObservable.ofType(AnnotationsAddedEvent.class)
.subscribe(e -> {
if (e.get() != null) {
data.getAnnotations().addAll(e.get());
}
},
er -> log.error("Subscriber failed", er));
eventObservable.ofType(AnnotationsRemovedEvent.class)
.subscribe(e -> {
// Remove from both annotations and selectedAnnotations.
// Reset selected to exclude any that were removed.
ArrayList<Annotation> selected = new ArrayList<>(data.getSelectedAnnotations());
selected.removeAll(e.get());
eventBus.send(new AnnotationsSelectedEvent(selected));
data.getAnnotations().removeAll(e.get());
});
eventObservable.ofType(AnnotationsChangedEvent.class)
.subscribe(e -> {
// They use observation UUID as hash key. Remove and replace with new ones
data.getAnnotations().removeAll(e.get());
data.getAnnotations().addAll(e.get());
});
eventObservable.ofType(AnnotationsSelectedEvent.class)
.subscribe(e -> data.setSelectedAnnotations(e.get()));
eventObservable.ofType(MediaChangedEvent.class)
.subscribe(e -> changeMedia(e.get()));
eventObservable.ofType(UserChangedEvent.class)
.subscribe(e -> data.setUser(e.get()));
eventObservable.ofType(ClearCacheMsg.class)
.subscribe(e -> {
ConceptService conceptService = toolBox.getServices().getConceptService();
if (conceptService instanceof CachedConceptService) {
((CachedConceptService) conceptService).clear();
}
});
eventObservable.ofType(MediaPlayerChangedEvent.class)
.subscribe(e -> toolBox.mediaPlayerProperty().set(e.get()));
eventObservable.ofType(ShowConcurrentAnnotationsMsg.class)
.subscribe(e -> showConcurrentMedia(e.getShow()));
eventObservable.ofType(SeekMsg.class)
.subscribe(this::seek);
eventObservable.ofType(SaveImageMsg.class)
.subscribe(this::saveImage);
eventObservable.ofType(ShowAlert.class)
.subscribe(alerts::showAlert);
}
private void saveImage(SaveImageMsg msg) {
URL url = msg.getUrl();
if (url != null ) {
String filename = URLUtilities.toFilename(url);
fileChooser.setTitle(toolBox.getI18nBundle().getString("appcontroller.imagesave.title"));
fileChooser.setInitialFileName(filename);
File file = fileChooser.showSaveDialog(msg.getWindow());
if (file != null) {
try (BufferedInputStream in = new BufferedInputStream(url.openStream());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
IOUtilities.copy(in, out);
}
catch (IOException e) {
log.error("Failed to copy " + url + " to " + file);
}
}
}
}
private void seek(SeekMsg msg) {
Object idx = msg.getIndex();
MediaPlayer<? extends VideoState, ? extends VideoError> mediaPlayer = toolBox.getMediaPlayer();
if (idx instanceof Timecode) {
mediaPlayer.seek((Timecode) idx);
}
else if (idx instanceof Duration) {
mediaPlayer.seek((Duration) idx);
}
else if (idx instanceof Instant) {
Media media = toolBox.getData().getMedia();
if (media != null) {
Instant startTime = media.getStartTimestamp();
if (startTime != null) {
Instant time = (Instant) idx;
Duration elapsedTime = Duration.between(startTime, time);
mediaPlayer.seek(elapsedTime);
}
}
}
}
private void changeMedia(Media newMedia) {
EventBus eventBus = toolBox.getEventBus();
Data data = toolBox.getData();
// Clear out old data
eventBus.send(new AnnotationsSelectedEvent(new ArrayList<>()));
eventBus.send(new AnnotationsRemovedEvent(data.getAnnotations()));
eventBus.send(new ClearCommandManagerMsg());
// Load new data
data.setMedia(newMedia);
AnnotationServiceDecorator decorator = new AnnotationServiceDecorator(toolBox);
if (newMedia != null) {
decorator.findAnnotations(newMedia.getVideoReferenceUuid());
}
}
private void showConcurrentMedia(Boolean show) {
AnnotationServiceDecorator decorator = new AnnotationServiceDecorator(toolBox);
Media media = toolBox.getData().getMedia();
if (show) {
if (media != null) {
UUID uuid = media.getVideoReferenceUuid();
/*
1. Find medias for your deployment that overlap the one with
the uuid you provided
2. Convert those medias to a list of their UUIDs
3. Pass that list to findConcurrentAnnotations. That will
get all annotations, from the overlapping media, that
overlap with the timebounds of your current media
*/
toolBox.getServices()
.getMediaService()
.findConcurrentByVideoReferenceUuid(uuid)
.thenApply(ms -> ms.stream()
.filter(m -> !m.getVideoReferenceUuid().equals(uuid))
.map(Media::getVideoReferenceUuid)
.collect(Collectors.toList()))
.thenAccept(decorator::findConcurrentAnnotations);
}
}
else {
if (media != null) {
decorator.removeAnnotationsExceptFor(media.getVideoReferenceUuid());
}
else {
ObservableList<Annotation> annotations = toolBox.getData().getAnnotations();
EventBus eventBus = toolBox.getEventBus();
eventBus.send(new AnnotationsSelectedEvent(new ArrayList<>()));
eventBus.send(new AnnotationsRemovedEvent(annotations));
}
}
}
}
|
package org.minimalj.transaction.criteria;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Criteria implements Serializable {
private static final long serialVersionUID = 1L;
// TODO: check for recursion?
public Criteria and(Criteria other) {
if (other != null) {
if (other instanceof AndCriteria) {
((AndCriteria) other).getCriterias().add(0, this);
return other;
} else {
return new AndCriteria(this, other);
}
} else {
return this;
}
}
public Criteria and(Filter filter) {
Criteria other = filter.getCriteria();
return and(other);
}
public Criteria or(Criteria other) {
if (other != null) {
if (other instanceof OrCriteria) {
((OrCriteria) other).getCriterias().add(0, this);
return other;
} else {
return new OrCriteria(this, other);
}
} else {
return this;
}
}
public int getLevel() {
return 0;
}
public static abstract class CombinedCriteria extends Criteria implements Serializable {
private static final long serialVersionUID = 1L;
private final List<Criteria> criterias;
public CombinedCriteria(Criteria criteria1, Criteria criteria2) {
// don't use Arrays.asList as Array might change later
criterias = new ArrayList<>();
criterias.add(criteria1);
criterias.add(criteria2);
}
public CombinedCriteria(List<Criteria> criterias) {
this.criterias = criterias;
}
public List<Criteria> getCriterias() {
return criterias;
}
}
public static class OrCriteria extends CombinedCriteria implements Serializable {
private static final long serialVersionUID = 1L;
public OrCriteria(Criteria criteria1, Criteria criteria2) {
super(criteria1, criteria2);
}
public OrCriteria(List<Criteria> criterias) {
super(criterias);
}
@Override
public int getLevel() {
return -1;
}
@Override
public Criteria or(Criteria other) {
if (other != null && !getCriterias().contains(other)) {
getCriterias().add(other);
}
return this;
}
}
public static class AndCriteria extends CombinedCriteria implements Serializable {
private static final long serialVersionUID = 1L;
public AndCriteria(Criteria criteria1, Criteria criteria2) {
super(criteria1, criteria2);
}
public AndCriteria(List<Criteria> criterias) {
super(criterias);
}
@Override
public Criteria and(Criteria other) {
if (other != null && !getCriterias().contains(other)) {
getCriterias().add(other);
}
return this;
}
@Override
public int getLevel() {
return 1;
}
}
public static interface Filter {
public Criteria getCriteria();
}
}
|
package us.myles.ViaVersion.slot;
import io.netty.buffer.ByteBuf;
import org.bukkit.Material;
import org.spacehq.opennbt.tag.builtin.CompoundTag;
import org.spacehq.opennbt.tag.builtin.StringTag;
import us.myles.ViaVersion.CancelException;
import us.myles.ViaVersion.util.PacketUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ItemSlotRewriter {
public static void rewrite1_9To1_8(ByteBuf input, ByteBuf output) throws CancelException {
try {
ItemStack item = readItemStack(input);
fixIdsFrom1_9To1_8(item);
writeItemStack(item, output);
} catch (Exception e) {
System.out.println("Error while rewriting an item slot.");
e.printStackTrace();
throw new CancelException();
}
}
public static void rewrite1_8To1_9(ByteBuf input, ByteBuf output) throws CancelException {
try {
ItemStack item = readItemStack(input);
fixIdsFrom1_8To1_9(item);
writeItemStack(item, output);
} catch (Exception e) {
System.out.println("Error while rewriting an item slot.");
e.printStackTrace();
throw new CancelException();
}
}
public static void fixIdsFrom1_9To1_8(ItemStack item) {
if (item != null) {
if (item.id == Material.MONSTER_EGG.getId() && item.data == 0) {
CompoundTag tag = item.tag;
int data = 0;
if (tag != null && tag.get("EntityTag") instanceof CompoundTag) {
CompoundTag entityTag = tag.get("EntityTag");
if (entityTag.get("id") instanceof StringTag) {
StringTag id = entityTag.get("id");
if (ENTTIY_NAME_TO_ID.containsKey(id.getValue()))
data = ENTTIY_NAME_TO_ID.get(id.getValue());
}
}
item.tag = null;
item.data = (short) data;
}
if (item.id == Material.POTION.getId()) {
CompoundTag tag = item.tag;
int data = 0;
if (tag != null && tag.get("Potion") instanceof StringTag) {
StringTag potion = tag.get("Potion");
String potionName = potion.getValue().replace("minecraft:", "");
if (POTION_NAME_TO_ID.containsKey(potionName)) {
data = POTION_NAME_TO_ID.get(potionName);
}
}
item.tag = null;
item.data = (short) data;
}
if (item.id == 438) {
CompoundTag tag = item.tag;
int data = 0;
item.id = (short) Material.POTION.getId();
if (tag != null && tag.get("Potion") instanceof StringTag) {
StringTag potion = tag.get("Potion");
String potionName = potion.getValue().replace("minecraft:", "");
if (POTION_NAME_TO_ID.containsKey(potionName)) {
data = POTION_NAME_TO_ID.get(potionName) + 8192;
}
}
item.tag = null;
item.data = (short) data;
}
}
}
public static void fixIdsFrom1_8To1_9(ItemStack item) {
if (item != null) {
if (item.id == Material.MONSTER_EGG.getId() && item.data != 0) {
CompoundTag tag = item.tag;
if (tag == null) {
tag = new CompoundTag("tag");
}
CompoundTag entityTag = new CompoundTag("EntityTag");
if (ENTTIY_ID_TO_NAME.containsKey(Integer.valueOf(item.data))) {
StringTag id = new StringTag("id", ENTTIY_ID_TO_NAME.get(Integer.valueOf(item.data)));
entityTag.put(id);
tag.put(entityTag);
}
item.tag = tag;
item.data = 0;
}
if (item.id == Material.POTION.getId()) {
CompoundTag tag = item.tag;
if (tag == null) {
tag = new CompoundTag("tag");
}
if(item.data >= 16384){
item.id = 438; // splash id
item.data = (short) (item.data - 8192);
}
if (POTION_ID_TO_NAME.containsKey(Integer.valueOf(item.data))) {
String name = POTION_ID_TO_NAME.get(Integer.valueOf(item.data));
StringTag potion = new StringTag("Potion", "minecraft:" + name);
tag.put(potion);
}
item.tag = tag;
item.data = 0;
}
}
}
public static ItemStack readItemStack(ByteBuf input) throws IOException {
short id = input.readShort();
if (id < 0) {
return null;
} else {
ItemStack item = new ItemStack();
item.id = id;
item.amount = input.readByte();
item.data = input.readShort();
item.tag = PacketUtil.readNBT(input);
return item;
}
}
public static void writeItemStack(ItemStack item, ByteBuf output) throws IOException {
if (item == null) {
output.writeShort(-1);
} else {
output.writeShort(item.id);
output.writeByte(item.amount);
output.writeShort(item.data);
PacketUtil.writeNBT(output, item.tag);
}
}
public static class ItemStack {
private short id;
private byte amount;
private short data;
private CompoundTag tag;
public static ItemStack fromBukkit(org.bukkit.inventory.ItemStack stack) {
ItemStack item = new ItemStack();
item.id = (short) stack.getTypeId();
item.amount = (byte) stack.getAmount();
item.data = stack.getData().getData();
// TODO: nbt
return item;
}
}
private static Map<String, Integer> ENTTIY_NAME_TO_ID = new HashMap<>();
private static Map<Integer, String> ENTTIY_ID_TO_NAME = new HashMap<>();
private static Map<String, Integer> POTION_NAME_TO_ID = new HashMap<>();
private static Map<Integer, String> POTION_ID_TO_NAME = new HashMap<>();
static {
/* Entities */
registerEntity(1, "Item");
registerEntity(2, "XPOrb");
registerEntity(7, "ThrownEgg");
registerEntity(8, "LeashKnot");
registerEntity(9, "Painting");
registerEntity(10, "Arrow");
registerEntity(11, "Snowball");
registerEntity(12, "Fireball");
registerEntity(13, "SmallFireball");
registerEntity(14, "ThrownEnderpearl");
registerEntity(15, "EyeOfEnderSignal");
registerEntity(16, "ThrownPotion");
registerEntity(17, "ThrownExpBottle");
registerEntity(18, "ItemFrame");
registerEntity(19, "WitherSkull");
registerEntity(20, "PrimedTnt");
registerEntity(21, "FallingSand");
registerEntity(22, "FireworksRocketEntity");
registerEntity(30, "ArmorStand");
registerEntity(40, "MinecartCommandBlock");
registerEntity(41, "Boat");
registerEntity(42, "MinecartRideable");
registerEntity(43, "MinecartChest");
registerEntity(44, "MinecartFurnace");
registerEntity(45, "MinecartTNT");
registerEntity(46, "MinecartHopper");
registerEntity(47, "MinecartSpawner");
registerEntity(48, "Mob");
registerEntity(49, "Monster");
registerEntity(50, "Creeper");
registerEntity(51, "Skeleton");
registerEntity(52, "Spider");
registerEntity(53, "Giant");
registerEntity(54, "Zombie");
registerEntity(55, "Slime");
registerEntity(56, "Ghast");
registerEntity(57, "PigZombie");
registerEntity(58, "Enderman");
registerEntity(59, "CaveSpider");
registerEntity(60, "Silverfish");
registerEntity(61, "Blaze");
registerEntity(62, "LavaSlime");
registerEntity(63, "EnderDragon");
registerEntity(64, "WitherBoss");
registerEntity(65, "Bat");
registerEntity(66, "Witch");
registerEntity(67, "Endermite");
registerEntity(68, "Guardian");
registerEntity(90, "Pig");
registerEntity(91, "Sheep");
registerEntity(92, "Cow");
registerEntity(93, "Chicken");
registerEntity(94, "Squid");
registerEntity(95, "Wolf");
registerEntity(96, "MushroomCow");
registerEntity(97, "SnowMan");
registerEntity(98, "Ozelot");
registerEntity(99, "VillagerGolem");
registerEntity(100, "EntityHorse");
registerEntity(101, "Rabbit");
registerEntity(120, "Villager");
registerEntity(200, "EnderCrystal");
/* Potions */
registerPotion(0, "water");
registerPotion(64, "mundane");
registerPotion(32, "thick");
registerPotion(16, "awkward");
registerPotion(8198, "night_vision");
registerPotion(8262, "long_night_vision");
registerPotion(8206, "invisibility");
registerPotion(8270, "long_invisibility");
registerPotion(8203, "leaping");
registerPotion(8267, "long_leaping");
registerPotion(8235, "strong_leaping");
registerPotion(8195, "fire_resistance");
registerPotion(8259, "long_fire_resistance");
registerPotion(8194, "swiftness");
registerPotion(8258, "long_swiftness");
registerPotion(8226, "strong_swiftness");
registerPotion(8202, "slowness");
registerPotion(8266, "long_slowness");
registerPotion(8205, "water_breathing");
registerPotion(8269, "long_water_breathing");
registerPotion(8197, "healing");
registerPotion(8229, "strong_healing");
registerPotion(8204, "harming");
registerPotion(8236, "strong_harming");
registerPotion(8196, "poison");
registerPotion(8260, "long_poison");
registerPotion(8228, "strong_poison");
registerPotion(8193, "regeneration");
registerPotion(8257, "long_regeneration");
registerPotion(8225, "strong_regeneration");
registerPotion(8201, "strength");
registerPotion(8265, "long_strength");
registerPotion(8233, "strong_strength");
registerPotion(8200, "weakness");
registerPotion(8264, "long_weakness");
}
private static void registerEntity(Integer id, String name) {
ENTTIY_ID_TO_NAME.put(id, name);
ENTTIY_NAME_TO_ID.put(name, id);
}
private static void registerPotion(Integer id, String name) {
POTION_ID_TO_NAME.put(id, name);
POTION_NAME_TO_ID.put(name, id);
}
}
|
package org.kaazing.qpid.amqp_1_0.jms;
import static javax.jms.Session.AUTO_ACKNOWLEDGE;
import static javax.jms.Session.CLIENT_ACKNOWLEDGE;
import static javax.jms.Session.DUPS_OK_ACKNOWLEDGE;
import org.apache.qpid.amqp_1_0.jms.Connection;
import org.apache.qpid.amqp_1_0.jms.ConnectionFactory;
import org.apache.qpid.amqp_1_0.jms.MessageConsumer;
import org.apache.qpid.amqp_1_0.jms.Session;
import org.apache.qpid.amqp_1_0.jms.impl.ConnectionFactoryImpl;
import org.junit.Rule;
import org.junit.Test;
import org.kaazing.robot.junit.annotation.Robotic;
import org.kaazing.robot.junit.rules.RobotRule;
public class QueueConsumerIT {
@Rule
public RobotRule robot = new RobotRule().setScriptRoot("org/kaazing/robot/scripts/amqp_1_0/jms/queue/consumer");
@Robotic(script = "create.then.close")
@Test(timeout = 1000)
public void shouldCreateAutoAcknowledgeConsumer() throws Exception {
ConnectionFactory factory = new ConnectionFactoryImpl("localhost", 5672, null, null, "clientID");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(session.createQueue("queue://queue-A"));
consumer.close();
session.close();
connection.close();
robot.join();
}
@Robotic(script = "create.then.close")
@Test(timeout = 1000)
public void shouldCreateClientAcknowledgeConsumer() throws Exception {
ConnectionFactory factory = new ConnectionFactoryImpl("localhost", 5672, null, null, "clientID");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(session.createQueue("queue://queue-A"));
consumer.close();
session.close();
connection.close();
robot.join();
}
@Robotic(script = "create.then.close")
@Test(timeout = 1000)
public void shouldCreateDupsOkayAcknowledgeConsumer() throws Exception {
ConnectionFactory factory = new ConnectionFactoryImpl("localhost", 5672, null, null, "clientID");
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, DUPS_OK_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(session.createQueue("queue://queue-A"));
consumer.close();
session.close();
connection.close();
robot.join();
}
}
|
package reborncore.common.recipes;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraftforge.oredict.OreDictionary;
import javax.annotation.Nullable;
public class RecipeTranslator {
public static
@Nullable
ItemStack getStackFromObject(Object object) {
if (object instanceof ItemStack) {
return (ItemStack) object;
} else if (object instanceof String) {
String oreName = (String) object;
if (OreDictionary.doesOreNameExist(oreName)) {
NonNullList<ItemStack> list = OreDictionary.getOres(oreName);
return list.get(0).copy(); //The first entry
}
}
return ItemStack.EMPTY;
}
}
|
package org.takes.servlet;
import java.io.IOException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.cactoos.text.FormattedText;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.takes.rs.RsEmpty;
import org.takes.rs.RsWithHeader;
/**
* Test case for {@link HttpServletResponseFake}.
*
* @since 1.14
*/
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public final class HttpServletResponseFakeTest {
/**
* Set-Cookie header name.
*/
private static final String SET_COOKIE = "Set-Cookie:";
/**
* HTTP/1.1 header name.
*/
private static final String HTTP_1_1 = "HTTP/1.1";
@Test
public void cookie() throws Exception {
final String name = "foo";
final String value = "bar";
final HttpServletResponse sresp = new HttpServletResponseFake(
new RsEmpty()
);
sresp.addCookie(new Cookie(name, value));
MatcherAssert.assertThat(
"Can't add a cookie in servlet response",
sresp.getHeaders(HttpServletResponseFakeTest.SET_COOKIE),
Matchers.hasItem(
new FormattedText(
"%s %s=%s;",
HttpServletResponseFakeTest.SET_COOKIE,
name,
value
).asString()
)
);
}
@Test
public void addHeader() throws Exception {
final String name = "oba";
final String value = "abo";
final HttpServletResponse sresp = new HttpServletResponseFake(
new RsEmpty()
);
sresp.setHeader(name, value);
MatcherAssert.assertThat(
"Can't add a new header in servlet response",
sresp.getHeaders(name),
Matchers.hasItem(
new FormattedText(
"%s: %s",
name,
value
).asString()
)
);
}
@Test
public void changeHeader() throws Exception {
final String name = "marco";
final String value = "polo";
final HttpServletResponse sresp = new HttpServletResponseFake(
new RsWithHeader(name, value)
);
sresp.setHeader(name, value);
MatcherAssert.assertThat(
"Can't change a header value in servlet response",
sresp.getHeaders(name),
Matchers.hasItem(
new FormattedText(
"%s: %s",
name,
value
).asString()
)
);
}
@Test
public void status() {
final HttpServletResponse sresp = new HttpServletResponseFake(
new RsEmpty()
);
// @checkstyle MagicNumber (1 line)
sresp.setStatus(502);
MatcherAssert.assertThat(
"Can't set a status in servlet response",
sresp.getHeaders(HttpServletResponseFakeTest.HTTP_1_1),
Matchers.hasItem("HTTP/1.1 502 Bad Gateway")
);
}
@Test
public void sendError() throws IOException {
final HttpServletResponse sresp = new HttpServletResponseFake(
new RsEmpty()
);
// @checkstyle MagicNumber (1 line)
sresp.sendError(101, "Custom error message");
MatcherAssert.assertThat(
"Can't send a error in servlet response",
sresp.getHeaders("HTTP/1.1"),
Matchers.hasItem("HTTP/1.1 101 Custom error message")
);
}
}
|
package romelo333.notenoughwands.proxy;
import mcjty.lib.setup.DefaultCommonSetup;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import org.apache.logging.log4j.Level;
import romelo333.notenoughwands.*;
import romelo333.notenoughwands.network.NEWPacketHandler;
import romelo333.notenoughwands.varia.WrenchChecker;
import java.io.File;
public class CommonSetup extends DefaultCommonSetup {
@Override
public void preInit(FMLPreInitializationEvent e) {
super.preInit(e);
MinecraftForge.EVENT_BUS.register(new ForgeEventHandlers());
ModItems.init();
readMainConfig();
FreezePotion.freezePotion = new FreezePotion();
NEWPacketHandler.registerMessages("notenoughwands");
}
@Override
public void createTabs() {
createTab("NotEnoughWands", new ItemStack(ModItems.teleportationWand));
}
private Configuration mainConfig;
private void readMainConfig() {
mainConfig = new Configuration(new File(modConfigDir, "notenoughwands.cfg"));
Configuration cfg = mainConfig;
try {
cfg.load();
cfg.addCustomCategoryComment(Config.CATEGORY_GENERAL, "General configuration");
cfg.addCustomCategoryComment(Config.CATEGORY_WANDS, "Wand configuration");
Config.init(cfg);
} catch (Exception e1) {
getLogger().log(Level.ERROR, "Problem loading config file!", e1);
} finally {
if (mainConfig.hasChanged()) {
mainConfig.save();
}
}
}
@Override
public void init(FMLInitializationEvent e) {
super.init(e);
ModCrafting.init(); // @todo still has to be fixed
}
@Override
public void postInit(FMLPostInitializationEvent e) {
super.postInit(e);
if (mainConfig.hasChanged()) {
mainConfig.save();
}
mainConfig = null;
WrenchChecker.init();
}
}
|
package org.traccar.protocol;
import org.junit.Test;
import org.traccar.ProtocolTest;
import org.traccar.model.Position;
public class T800xProtocolDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
T800xProtocolDecoder decoder = new T800xProtocolDecoder(null);
verifyPosition(decoder, binary(
"2727040049001b0866425039645728c916190604005240000000007739d2c25b681f420000000080000081000020174105000005458216001e000000f01e00001e30d0000000000000"));
verifyAttribute(decoder, binary(
"272705005e000108664250328807851905301107481054002d004d006f00620069006c006500074341542d4e42310a4c54452042414e4420340f333130323430323030303032333030143839303132343032303531303030323330303746"),
Position.KEY_OPERATOR, "T-Mobile");
verifyPosition(decoder, binary(
"272702004904a90866425032880785c800190530080350000000000705eec29bf50842000000000008008090502a003700000a9e358002003c000003841900001e3f90000000000000272702004904aa0866425032880785c800190530081851000000000705eec29bf50842000000000008008090602e003700000a9e358002003c000003841900001e3f90000000000000"));
verifyNull(decoder, binary(
"2727010017000108806168988888881016010207110111"));
verifyNull(decoder, binary(
"252501001504050880061689888888111111250350"));
verifyAttribute(decoder, binary(
"2525810128000108664250328959160149004d00450049003a003800360036003400320035003000330032003800390035003900310036002c005300450054002000560045005200530049004f004e0020004f004b002c00560065007200730069006f006e003a00420061007300690063003a00560031002e0030002e0030002c004100500050003a00560034002e0032002e0033002c004200550049004c0044003a0032003000310039002d00300033002d00330030002c00300038003a00300035002c0050004c0054003a0032003500300033004100560045002c00480057003a00560032002e0031002c004d004f00440045004c003a002c004d004f00440045004d003a0042003900470036004d0041005200300032004100300037004d00310047002300"),
Position.KEY_RESULT, "IMEI:866425032895916,SET VERSION OK,Version:Basic:V1.0.0,APP:V4.2.3,BUILD:2019-03-30,08:05,PLT:2503AVE,HW:V2.1,MODEL:,MODEM:B9G6MAR02A07M1G
verifyPosition(decoder, binary(
"2525020044a66d0862522030401350001403841409c40064edc000051100960000071701370000003ea7ee0019032010581300000000aad3e1bda6f24d42000000001281"));
verifyPosition(decoder, binary(
"252502004400010880616898888888000A00FF2001000020409600989910101010055501550000101005050005051010050558866B4276D6E342912AB441111500051010"));
verifyNull(decoder, binary(
"232301001500000880316890202968140197625020"));
verifyNull(decoder, binary(
"232303000f00000880316890202968"));
verifyAttributes(decoder, binary(
"232302004200000880316890202968001e02582d00000000000000050000320000018901920000001dc1e2001601081154255d0202005a0053875a00a57e5a00af80"));
verifyNull(decoder, binary(
"232301001500020357367031063979150208625010"));
verifyNull(decoder, binary(
"232303000f00000357367031063979"));
verifyPosition(decoder, binary(
"232304004200030357367031063979003c03842307d00000c80000050100008000008900890100000017b100151022121648b8ef0c4422969342cec5944100000110"));
verifyPosition(decoder, binary(
"232302004200150357367031063979003c03842307d000004a0000050100004001009500940000000285ab001510281350477f710d4452819342d1ba944101160038"));
verifyAttributes(decoder, binary(
"232302004200000357367031063979003c03842307d000008000000501000000010094009400000002a0b90015102814590694015a00620cf698620cf49e620cf498"));
}
}
|
package selling.sunshine.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.Webhooks;
import selling.sunshine.model.Agent;
import selling.sunshine.model.BillStatus;
import selling.sunshine.model.DepositBill;
import selling.sunshine.service.AgentService;
import selling.sunshine.service.BillService;
import selling.sunshine.service.ToolService;
import selling.sunshine.utils.ResponseCode;
import selling.sunshine.utils.ResultData;
@RequestMapping("/bill")
@RestController
public class BillController {
private Logger logger = LoggerFactory.getLogger(BillController.class);
@Autowired
private ToolService toolService;
@Autowired
private BillService billService;
@Autowired
private AgentService agentService;
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value="/inform")
public ResultData inform(HttpServletRequest request, HttpServletResponse response) throws IOException{
ResultData resultData = new ResultData();
JSONObject webhooks = toolService.getParams(request);
logger.debug("webhooks info == " + webhooks);
JSONObject charge = webhooks.getJSONObject("data").getJSONObject("object");
logger.debug("charge info == " + charge);
String dealId = charge.getString("order_no");
logger.debug("deal id: " + dealId);
if (StringUtils.isEmpty(dealId)) {
resultData.setResponseCode(ResponseCode.RESPONSE_ERROR);
return resultData;
}
if (dealId.startsWith("DPB")) {
Map<String, Object> condition = new HashMap<String, Object>();
condition.put("billId", dealId);
resultData = billService.fetchDepositBill(condition);
DepositBill depositBill = ((List<DepositBill>) resultData.getData()).get(0);
Agent agent = depositBill.getAgent();
agent.setCoffer(agent.getCoffer()+depositBill.getBillAmount());
resultData = agentService.updateAgent(agent);
depositBill.setStatus(BillStatus.PAYED);
resultData = billService.updateDepositBill(depositBill);
Event event = Webhooks.eventParse(webhooks.toString());
if ("charge.succeeded".equals(event.getType())) {
response.setStatus(200);
} else if ("refund.succeeded".equals(event.getType())) {
response.setStatus(200);
} else {
response.setStatus(500);
}
}
return resultData;
}
}
|
package org.usfirst.frc.team5806.robot;
import edu.wpi.first.wpilibj.Counter;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class GearHalf extends Subsystem {
public enum GearState {
MOVING, OFF, FAST_CALIBRATION;
}
int lastPosition = 0;
int direction;
int lastEncoder = 0;
int lastDirection = 1;
int startingPosition;
double speed;
double maxSpeed, minSpeed, accelLength, deaccelLength, deltaPosition;
long startMillis, startFastCalibration;
GearState state = GearState.OFF;
Victor motor;
Counter encoder;
DigitalInput limitSwitch;
String name;
long lastUpdate = -1;
public GearHalf(int motorPort, int encoderPort, int limitSwitchPort, int direction, String name) {
motor = new Victor(motorPort);
encoder = new Counter(new DigitalInput(encoderPort));
limitSwitch = new DigitalInput(limitSwitchPort);
this.direction = Integer.signum(direction);
this.name = name;
encoder.reset();
motor.set(0);
}
public void calibrate() {
motor.set(direction*-0.4);
while(limitSwitch.get()) {
updateDashboard();
}
motor.set(0);
lastPosition = 0;
lastDirection = 1;
encoder.reset();
}
public void fastCalibrate() {
startFastCalibration = System.currentTimeMillis();
state = GearState.FAST_CALIBRATION;
motor.set(direction*-0.9);
}
public void movePosition(double maxSpeed, double minSpeed, double accelLength, double deaccelLength, double deltaPosition) {
this.maxSpeed = maxSpeed;
this.minSpeed = minSpeed;
this.accelLength = accelLength;
this.deaccelLength = deaccelLength;
this.deltaPosition = deltaPosition;
startingPosition = getPosition();
speed = minSpeed;
startMillis = System.currentTimeMillis();
state = GearState.MOVING;
setSpeed(speed*(int)Math.signum(deltaPosition));
}
public void setPosition(double maxSpeed, double minSpeed, double accelLength, double deaccelLength, double position) {
movePosition(maxSpeed, minSpeed, accelLength, deaccelLength, position - getPosition());
}
public int getPosition() {
return lastPosition + lastDirection*Math.abs(encoder.get() - lastEncoder);
}
public void setSpeed(double speed) {
lastPosition += lastDirection*Math.abs(encoder.get()-lastEncoder);
lastEncoder = encoder.get();
if(Math.abs(speed - 0) > 0.001) lastDirection = (int)Math.signum(speed);
motor.set(direction*speed);
}
@Override
public void stop() {
motor.stopMotor();
}
@Override
public void updateSubsystem() {
if(lastUpdate == -1) lastUpdate = System.currentTimeMillis();
if(!limitSwitch.get()) {
lastPosition = 0;
lastDirection = 1;
encoder.reset();
motor.set(0);
}
switch(state) {
case MOVING:
if(Math.abs(getPosition()-startingPosition) < Math.abs(deltaPosition) && (Math.signum(deltaPosition) > 0 || limitSwitch.get())) {
double error = (Math.abs(deltaPosition) - Math.abs(getPosition()-startingPosition)) / Math.abs(deltaPosition);
if(1-error < accelLength) {
speed = minSpeed + ((maxSpeed - minSpeed) * (1-error) / accelLength);
} else if (error < deaccelLength) {
speed = minSpeed + ((maxSpeed - minSpeed) * error / deaccelLength);
} else {
speed = maxSpeed;
}
setSpeed(speed*(int)Math.signum(deltaPosition));
} else {
state = GearState.OFF;
setSpeed(0);
}
break;
case FAST_CALIBRATION:
if(!limitSwitch.get() || System.currentTimeMillis() - startFastCalibration > 500) {
setPosition(0.4, 0.25, 0.1, 0.2, -2000);
} else {
motor.set(direction*-0.9);
}
case OFF:
break;
}
lastUpdate = System.currentTimeMillis();
}
@Override
public void updateDashboard() {
SmartDashboard.putNumber(name+"GearMotor", motor.get());
SmartDashboard.putNumber(name+"GearEncoder", encoder.get());
SmartDashboard.putBoolean(name+"GearLimit", limitSwitch.get());
SmartDashboard.putNumber(name+"GearPosition", getPosition());
SmartDashboard.putNumber(name+"GearDeltaPosition", Math.abs(getPosition()-startingPosition));
}
}
|
package unal.architecture.test.integration;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import org.junit.*;
import org.junit.rules.ExpectedException;
import unal.architecture.entity.Credentials;
import unal.architecture.entity.User;
import javax.naming.NamingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class AuthRESTIT {
private static final String URI = "http://localhost:8080/SoftwareArchitectureUNAL/auth";
private static Client client;
@Rule
public ExpectedException thrown= ExpectedException.none();
@BeforeClass
public static void beforeClass() throws NamingException {
client = ClientBuilder.newClient().register(JacksonJsonProvider.class);
}
@AfterClass
public static void afterClass() throws NamingException {
client.close();
}
@Before
public void before() {
}
@After
public void after() {
}
@Test
public void testNotLoggedin(){
User user;
thrown.expect(javax.ws.rs.ProcessingException.class);
user = client.target(URI)
.path("me")
.request(MediaType.APPLICATION_JSON)
.get(User.class);
assertNull(user);
}
@Test
public void testLogin() {
Response response;
User user;
//Login.
Credentials credentials = new Credentials();
credentials.setUsername("admin");
credentials.setPassword("admin");
response = client.target(URI)
.path("login")
.request(MediaType.APPLICATION_JSON)
.post(Entity.json(credentials));
String session = response.getCookies().get("JSESSIONID").getValue();
user = response.readEntity(User.class);
assertNotNull(user);
//Logged in.
user = client.target(URI)
.path("me")
.request(MediaType.APPLICATION_JSON)
.cookie("JSESSIONID", session)
.get(User.class);
assertNotNull(user);
//Logout.
client.target(URI)
.path("logout")
.request(MediaType.APPLICATION_JSON)
.cookie("JSESSIONID", session)
.post(Entity.json(""));
//Not logged in again.
thrown.expect(javax.ws.rs.ProcessingException.class);
user = client.target(URI)
.path("me")
.request(MediaType.APPLICATION_JSON)
.cookie("JSESSIONID", session)
.get(User.class);
assertNull(user);
}
}
|
package shadow.doctool.output;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import shadow.doctool.Documentation;
import shadow.doctool.DocumentationException;
import shadow.doctool.output.HtmlWriter.Attribute;
import shadow.doctool.tag.TagManager.BlockTagType;
import shadow.parser.javacc.Node;
import shadow.parser.javacc.ShadowException;
import shadow.typecheck.Package;
import shadow.typecheck.type.ClassType;
import shadow.typecheck.type.EnumType;
import shadow.typecheck.type.ExceptionType;
import shadow.typecheck.type.InterfaceType;
import shadow.typecheck.type.MethodSignature;
import shadow.typecheck.type.ModifiedType;
import shadow.typecheck.type.Modifiers;
import shadow.typecheck.type.SequenceType;
import shadow.typecheck.type.SingletonType;
import shadow.typecheck.type.Type;
import shadow.typecheck.type.TypeParameter;
public class ClassOrInterfacePage extends Page
{
private Type type;
private String typeKind;
private HashSet<Type> linkableTypes;
private final Path relativePath;
public final String qualifiedName;
// Method categories
private List<MethodSignature> constructors = new ArrayList<MethodSignature>();
private List<MethodSignature> destructors = new ArrayList<MethodSignature>();
private List<MethodSignature> methods = new ArrayList<MethodSignature>();
private List<MethodSignature> properties = new ArrayList<MethodSignature>();
// Public and protected constants
private List<Node> visibleConstants = new ArrayList<Node>();
public ClassOrInterfacePage(StandardTemplate master, Type type,
Collection<Type> linkableTypes) throws DocumentationException
{
super(master);
if (type instanceof ClassType)
typeKind = "Class";
else if (type instanceof EnumType)
typeKind = "Enum";
else if (type instanceof ExceptionType)
typeKind = "Exception";
else if (type instanceof InterfaceType)
typeKind = "Interface";
else if (type instanceof SingletonType)
typeKind = "Singleton";
else
throw new DocumentationException("Unexpected type: " + type.toString(Type.PACKAGES | Type.TYPE_PARAMETERS));
this.type = type;
this.linkableTypes = new HashSet<Type>(linkableTypes);
this.relativePath = constructOutputPath().resolve(type.getTypeName().replaceAll(":", "\\$") + EXTENSION);
// The qualified name should not contain type parameters
this.qualifiedName = type.toString(Type.PACKAGES);
getVisibleMethods();
getVisibleConstants();
}
/** Sorts all methods into lists based upon their type and visibility */
private void getVisibleMethods()
{
for (List<MethodSignature> overloadList : type.getMethodMap().values()) {
for (MethodSignature method : overloadList) {
if (!method.getModifiers().isPrivate()) {
Modifiers modifiers = method.getModifiers();
if (modifiers.hasModifier(Modifiers.GET)
|| modifiers.hasModifier(Modifiers.SET))
properties.add(method);
else if (method.getSymbol() == "create")
constructors.add(method);
else if (method.getSymbol() == "destroy")
destructors.add(method);
else
methods.add(method);
}
}
}
Collections.sort(constructors);
Collections.sort(destructors);
Collections.sort(methods);
Collections.sort(properties);
}
private void getVisibleConstants()
{
for (Node field : type.getFields().values())
if (field.getModifiers().isConstant() && !field.getModifiers().isPrivate())
visibleConstants.add(field);
Collections.sort(visibleConstants, new Comparator<Node>() {
@Override
public int compare(Node node1, Node node2) {
return node1.toString().compareTo(node2.toString());
}} );
}
public void write(Path root)
throws IOException, ShadowException, DocumentationException
{
// Find/create the directory chain where the document will reside
Path outputDirectory = constructOutputPath(root);
outputDirectory.toFile().mkdirs();
// Begin writing to the document itself
// Note: All colons in class names are replaced with dashes to avoid
// browser issues (i.e. relative paths being interpreted as protocols)
Path output = outputDirectory
.resolve(type.getTypeName().replaceAll(":", "\\$") + EXTENSION);
FileWriter fileWriter = new FileWriter(output.toFile());
HtmlWriter out = new HtmlWriter(fileWriter);
out.openTab("html");
writeHtmlHead(type.getTypeName(), out);
out.openTab("body");
writeNavBar(master.getPackagePage(type.getPackage()), out);
writeHeader(out);
writeConstantSummaries(out);
writeMethodSummaries(out);
writeConstantDetails(out);
writeMethodDetails(out);
out.closeUntab();
out.closeUntab();
fileWriter.close();
}
private void writeHeader(HtmlWriter out)
throws ShadowException, DocumentationException
{
out.openTab("div", new Attribute("class", "header"));
String packageName = type.getPackage().getQualifiedName();
// Create a link to this class/interface's package
out.open("p");
if (!packageName.isEmpty())
writeLink(PackagePage.PAGE_NAME + EXTENSION,
type.getPackage().getQualifiedName(), out);
else
writeLink(PackagePage.PAGE_NAME + EXTENSION,
"default", out);
out.closeLine();
out.fullLine("h2", typeKind + " " + type.getTypeName());
writeInnerClassSection(out);
writeInheritanceSection(out);
out.voidLine("hr");
// Full, "in code" declaration
out.open("p");
out.open("code");
out.add(type.getModifiers().toString() + typeKind.toLowerCase()
+ " " + type.getTypeName());
writeTypeParameters(type, true, out);
out.close();
out.closeLine();
// Documentation text
if (type.hasDocumentation()) {
writeInlineTags(type.getDocumentation().getInlineTags(), out);
writeBlockTags(type.getDocumentation(), out);
}
out.closeUntab();
}
// TODO: Support recursion of type constraints?
private void writeTypeParameters(Type parent, boolean link,
HtmlWriter out) throws ShadowException, DocumentationException
{
SequenceType typeParams = parent.getTypeParameters();
if (typeParams != null && typeParams.size() > 0) {
out.add("<");
int i = 0;
for (ModifiedType modifiedParam : typeParams) {
if (i != 0)
out.add(", ");
TypeParameter param = (TypeParameter)modifiedParam.getType();
out.add(param.getTypeName());
ArrayList<Type> bounds = new ArrayList<Type>();
//only put in class bound if not Object
ClassType classType = param.getClassBound();
if( !classType.equals(Type.OBJECT))
bounds.add(classType);
for( Type bound : param.getBounds() )
if( bound instanceof InterfaceType )
bounds.add(bound);
int j = 0;
for (Type constraint : bounds) {
if (j == 0) {
out.add(" is ");
} else {
out.add(" and ");
}
if (link) {
writeCrossLink(constraint, Type.TYPE_PARAMETERS, out);
} else {
out.add(constraint.toString(Type.TYPE_PARAMETERS));
}
j++;
}
i++;
}
out.add(">");
}
}
private void writeInnerClassSection(HtmlWriter out)
throws ShadowException, DocumentationException
{
// Link to outer class, if any
if (type.hasOuter()) {
out.fullLine("h4", "Outer class");
out.open("p");
writeCrossLink(type.getOuter(), Type.PACKAGES | Type.TYPE_PARAMETERS, out);
out.closeLine();
}
if (type instanceof ClassType) {
TreeSet<ClassType> innerClasses = new TreeSet<ClassType>();
for( ClassType current : ((ClassType)type).getInnerClasses().values() ) {
if( !current.getModifiers().isPrivate() )
innerClasses.add(current);
}
if (!innerClasses.isEmpty())
out.fullLine("h4", "Visible inner classes");
out.open("p");
int i = 0;
for (Type current : innerClasses) {
if (i > 0)
out.add(", ");
// List the name, optionally attempting a link
writeCrossLink(current, Type.PACKAGES | Type.TYPE_PARAMETERS, out);
i++;
}
out.closeLine();
}
}
private void writeInheritanceSection(HtmlWriter out)
throws ShadowException, DocumentationException
{
List<Type> interfaceList = new ArrayList<Type>();
interfaceList.addAll(type.getInterfaces());
Type extendType = null;
// TODO: Should getAllInterfaces() be used here?
if (type instanceof ClassType)
extendType = ((ClassType)type).getExtendType();
if (extendType != null) {
out.fullLine("h4", "Parent class");
out.open("p");
writeCrossLink(extendType, Type.PACKAGES | Type.TYPE_PARAMETERS, out);
out.closeLine();
}
if (interfaceList.size() > 0) {
out.fullLine("h4", "Interfaces");
out.open("p");
for (int i = 0; i < interfaceList.size(); ++i) {
if (i > 0)
out.add(", ");
// List the name, optionally attempting a link
Type current = interfaceList.get(i);
writeCrossLink(current, Type.PACKAGES | Type.TYPE_PARAMETERS, out);
}
out.closeLine();
}
}
private void writeConstantSummaries(HtmlWriter out)
throws ShadowException, DocumentationException
{
if (!visibleConstants.isEmpty()) {
out.openTab("div", new Attribute("class", "block"));
out.fullLine("h3", "Constant Summary");
out.openTab("table", new Attribute("class", "summarytable"));
writeTableRow(out, true, "Modifiers", "Type",
"Name and Description");
boolean shaded = false;
for (Node constant : visibleConstants) {
if( shaded )
out.openTab("tr", new Attribute("class", "shaded"));
else
out.openTab("tr");
out.open("td");
out.full("code", constant.getModifiers().toString().trim());
out.closeLine();
out.open("td");
out.open("code");
writeCrossLink(constant.getType(), Type.TYPE_PARAMETERS, out);
out.close();
out.closeLine();
out.open("td");
out.open("code");
writeNodeName(constant, true, out);
out.close();
if (constant.hasDocumentation())
writeInlineTags(constant.getDocumentation().getSummary(), out);
out.closeLine();
out.closeUntab();
shaded = !shaded;
}
out.closeUntab();
out.closeUntab();
}
}
private void writeMethodSummaries(HtmlWriter out)
throws ShadowException, DocumentationException
{
if (!constructors.isEmpty())
writeMethodTable("Constructor Summary", constructors, out);
if (!destructors.isEmpty())
writeMethodTable("Destructor Summary", destructors, out);
if (!methods.isEmpty())
writeMethodTable("Method Summary", methods, out);
if (!properties.isEmpty())
writeMethodTable("Property Summary", properties, out);
}
private void writeMethodTable(String name,
List<MethodSignature> methods, HtmlWriter out)
throws ShadowException, DocumentationException
{
out.openTab("div", new Attribute("class", "block"));
out.fullLine("h3", name);
out.openTab("table", new Attribute("class", "summarytable"));
writeTableRow(out, true, "Modifiers", "Return Type",
"Method and Description");
boolean shaded = false;
for (MethodSignature method : methods) {
if( shaded )
out.openTab("tr", new Attribute("class", "shaded"));
else
out.openTab("tr");
out.open("td");
out.full("code", method.getModifiers().toString().trim());
out.closeLine();
out.open("td");
out.open("code");
writeReturns(method, out);
out.close();
out.closeLine();
out.open("td");
out.open("code");
writeMethodName(method, true, out);
writeParameters(method, out);
out.close();
if (method.hasDocumentation())
writeInlineTags(method.getDocumentation().getSummary(), out);
out.closeLine();
out.closeUntab();
shaded = !shaded;
}
out.closeUntab();
out.closeUntab();
}
private void writeConstantDetails(HtmlWriter out)
throws ShadowException, DocumentationException
{
if (!visibleConstants.isEmpty()) {
out.openTab("div", new Attribute("class", "block"));
out.fullLine("h3", "Constant Detail");
for (Node constant : visibleConstants)
writeConstantDetail(constant, out);
out.closeUntab();
}
}
private void writeConstantDetail(Node constant, HtmlWriter out)
throws ShadowException, DocumentationException
{
out.openTab("div", new Attribute("class", "methoddetail"));
out.fullLine("h4", constant.toString(),
new Attribute("id", constant.toString()));
out.open("code");
out.add(constant.getModifiers().toString().trim() + " ");
writeCrossLink(constant.getType(), Type.TYPE_PARAMETERS, out);
out.add(" " + constant.toString());
out.closeLine();
// Documentation text
if (constant.hasDocumentation()) {
writeInlineTags(constant.getDocumentation().getInlineTags(), out);
writeBlockTags(constant.getDocumentation(), out);
}
out.closeUntab();
}
private void writeMethodDetails(HtmlWriter out)
throws ShadowException, DocumentationException
{
if (!constructors.isEmpty())
writeMethodDetailSection("Constructor Detail", constructors, out);
if (!destructors.isEmpty())
writeMethodDetailSection("Destructor Detail", destructors, out);
if (!methods.isEmpty())
writeMethodDetailSection("Method Detail", methods, out);
if (!properties.isEmpty())
writeMethodDetailSection("Property Detail", properties, out);
}
private void writeMethodDetailSection(String name,
List<MethodSignature> methods, HtmlWriter out)
throws ShadowException, DocumentationException
{
out.openTab("div", new Attribute("class", "block"));
out.fullLine("h3", name);
for (MethodSignature method : methods)
writeMethodDetail(method, out);
out.closeUntab();
}
private void writeMethodDetail(MethodSignature method,
HtmlWriter out) throws ShadowException, DocumentationException
{
out.openTab("div", new Attribute("class", "methoddetail"));
out.fullLine("h4", method.getSymbol(),
new Attribute("id", getUniqueID(method)));
out.open("code");
out.add(method.getModifiers().toString().trim() + " "
+ method.getSymbol());
writeParameters(method, out);
out.add(" => " );
writeReturns(method, out);
out.closeLine();
// Documentation text
if (method.hasDocumentation()) {
writeInlineTags(method.getDocumentation().getInlineTags(), out);
writeBlockTags(method.getDocumentation(), out);
}
out.closeUntab();
}
private void writeNodeName(Node node, boolean linkToDetail,
HtmlWriter out) throws DocumentationException, ShadowException
{
if (linkToDetail)
writeLink("#" + node.toString(), node.toString(), out);
else
out.add(node.toString());
}
private void writeMethodName(MethodSignature method, boolean linkToDetail,
HtmlWriter out) throws DocumentationException, ShadowException
{
if (linkToDetail)
writeLink("#" + getUniqueID(method), method.getSymbol(), out);
else
out.add(method.getSymbol());
}
private void writeParameters(MethodSignature method, HtmlWriter out)
throws DocumentationException, ShadowException
{
out.add("(");
int parameterCount = method.getParameterNames().size();
for (int i = 0; i < parameterCount; ++i)
{
if (i != 0)
out.add(", ");
ModifiedType parameter = method.getParameterTypes().get(i);
out.add(parameter.getModifiers().toString());
writeCrossLink(parameter.getType(),Type.TYPE_PARAMETERS, out);
out.add(" " + method.getParameterNames().get(i));
}
out.add(")");
}
private void writeReturns(MethodSignature method, HtmlWriter out)
throws DocumentationException, ShadowException
{
out.add("(");
int returnCount = method.getReturnTypes().size();
for (int i = 0; i < returnCount; ++i)
{
if (i != 0)
out.add(", ");
ModifiedType returnType = method.getReturnTypes().get(i);
out.add(returnType.getModifiers().toString());
writeCrossLink(returnType.getType(),Type.TYPE_PARAMETERS, out);
}
out.add(")");
}
private void writeBlockTags(Documentation documentation,
HtmlWriter out) throws DocumentationException, ShadowException
{
if (documentation.hasBlockTags(BlockTagType.AUTHOR))
writeAuthorSection(documentation.getBlockTags(BlockTagType.AUTHOR), out);
if (documentation.hasBlockTags(BlockTagType.PARAM))
writeParamSection(documentation.getBlockTags(BlockTagType.PARAM), out);
if (documentation.hasBlockTags(BlockTagType.SEE_DOC)
|| documentation.hasBlockTags(BlockTagType.SEE_URL))
writeSeeSection(documentation.getBlockTags(BlockTagType.SEE_DOC),
documentation.getBlockTags(BlockTagType.SEE_URL), out);
if (documentation.hasBlockTags(BlockTagType.THROWS))
writeThrowsSection(documentation.getBlockTags(BlockTagType.THROWS), out);
if (documentation.hasBlockTags(BlockTagType.RETURN))
writeReturnSection(documentation.getBlockTags(BlockTagType.RETURN), out);
}
private void writeParamSection(List<List<String>> paramTags,
HtmlWriter out) throws DocumentationException, ShadowException
{
if (paramTags.size() > 0) {
out.fullLine("h5", "Parameters");
out.openTab("div", new Attribute("class", "blocktagcontent"));
for (List<String> tag : paramTags) {
out.open("p");
out.full("code", tag.get(0), new Attribute("class", "inline"));
if (tag.size() > 1)
out.add(" - " + tag.get(1));
out.closeLine();
}
out.closeUntab();
}
}
private void writeThrowsSection(List<List<String>> throwsTags,
HtmlWriter out) throws DocumentationException, ShadowException
{
if (throwsTags.size() > 0) {
out.fullLine("h5", "Throws");
out.openTab("div", new Attribute("class", "blocktagcontent"));
for (List<String> tag : throwsTags) {
out.open("p");
out.full("code", tag.get(0), new Attribute("class", "inline"));
if (tag.size() > 1)
out.add(" - " + tag.get(1));
out.closeLine();
}
out.closeUntab();
}
}
private void writeReturnSection(List<List<String>> throwsTags,
HtmlWriter out) throws DocumentationException, ShadowException
{
if (throwsTags.size() > 0) {
out.fullLine("h5", "Returns");
out.openTab("div", new Attribute("class", "blocktagcontent"));
for (List<String> tag : throwsTags) {
out.open("p");
out.full("code", tag.get(0), new Attribute("class", "inline"));
if (tag.size() > 1)
out.add(" - " + tag.get(1));
out.closeLine();
}
out.closeUntab();
}
}
private void writeCrossLink(Type to, int options, HtmlWriter out)
throws DocumentationException, ShadowException
{
if( to.isParameterizedIncludingOuterClasses() && linkableTypes.contains(to.getTypeWithoutTypeArguments()) && (options & Type.TYPE_PARAMETERS) != 0) {
Type current = to;
ArrayDeque<Type> types = new ArrayDeque<Type>();
types.push(current);
while( current.hasOuter() ) {
current = current.getOuter();
types.push(current);
}
boolean first = true;
while( !types.isEmpty() ) {
if( first )
first = false;
else
options = options & ~Type.PACKAGES;
current = types.pop();
writeCrossLink(current.getTypeWithoutTypeArguments(), options & ~Type.TYPE_PARAMETERS, out);
if( current.isParameterized() ) {
out.add("<");
boolean comma = false;
for( ModifiedType parameter : current.getTypeParameters() ) {
if( comma )
out.add(",");
else
comma = true;
writeCrossLink(parameter.getType(), options, out);
}
out.add(">");
}
}
}
else if (linkableTypes.contains(to))
// Replace colons in class names with dashes
writeLink(getRelativePath(type, to)
.replaceAll(":", "\\$"), to.toString(options), new Attribute("title", to.toString(Type.PACKAGES | Type.TYPE_PARAMETERS)), out);
else
out.add(to.toString(options));
}
/* Helper methods */
/**
* Determines where this page should be output based on its package and
* a given root directory
*/
private Path constructOutputPath(Path root)
{
return root.resolve(constructOutputPath());
}
private Path constructOutputPath()
{
// Climb up the chain of packages
ArrayDeque<String> packages = new ArrayDeque<String>();
Package currentPackage = type.getPackage();
while (currentPackage != null && !currentPackage.getName().isEmpty()) {
packages.addFirst(currentPackage.getName());
currentPackage = currentPackage.getParent();
}
Path outputPath = Paths.get("");
for (String packageName : packages)
outputPath = outputPath.resolve(packageName);
return outputPath;
}
/** Creates the requested number of repetitions of "../" */
public static String upDir(int count)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; ++i)
builder.append("../");
return builder.toString();
}
/**
* Creates a unique ID based on a method's signature, which can then be used
* as an HTML bookmark
*/
private static String getUniqueID(MethodSignature method)
{
return method.getSymbol()
+ method.getParameterTypes().toString().replaceAll("\\s", "");
}
public Path getRelativePath()
{
return relativePath;
}
}
|
package com.smartnsoft.droid4me.app;
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.smartnsoft.droid4me.app.AppPublics.BroadcastListener;
import com.smartnsoft.droid4me.framework.ActivityResultHandler.CompositeHandler;
import com.smartnsoft.droid4me.log.Logger;
import com.smartnsoft.droid4me.log.LoggerFactory;
import com.smartnsoft.droid4me.menu.MenuHandler.Composite;
import com.smartnsoft.droid4me.menu.StaticMenuCommand;
public abstract class SmartFragment<AggregrateClass>
extends Fragment
implements Droid4mizerInterface, SmartableActivity<AggregrateClass>
{
protected static final Logger log = LoggerFactory.getInstance("SmartFragment");
private Droid4mizer<AggregrateClass, SmartFragment<AggregrateClass>> droid4mizer;
@Override
public void onAttach(Activity activity)
{
if (log.isDebugEnabled())
{
log.debug("SmartFragment::onAttach");
}
super.onAttach(activity);
droid4mizer = new Droid4mizer<AggregrateClass, SmartFragment<AggregrateClass>>(activity, this, this, this, this);
}
@Override
public void onCreate(final Bundle savedInstanceState)
{
droid4mizer.onCreate(new Runnable()
{
public void run()
{
SmartFragment.super.onCreate(savedInstanceState);
}
}, savedInstanceState);
}
@Override
public void onResume()
{
super.onResume();
droid4mizer.onResume();
}
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
droid4mizer.onSaveInstanceState(outState);
}
@Override
public void onStart()
{
super.onStart();
droid4mizer.onStart();
}
@Override
public void onPause()
{
try
{
droid4mizer.onPause();
}
finally
{
super.onPause();
}
}
@Override
public void onStop()
{
try
{
droid4mizer.onStop();
}
finally
{
super.onStop();
}
}
@Override
public void onDestroy()
{
try
{
droid4mizer.onDestroy();
}
finally
{
super.onDestroy();
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater)
{
super.onCreateOptionsMenu(menu, menuInflater);
droid4mizer.onCreateOptionsMenu(true, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
droid4mizer.onPrepareOptionsMenu(true, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
return droid4mizer.onOptionsItemSelected(super.onOptionsItemSelected(item), item);
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
return droid4mizer.onContextItemSelected(super.onContextItemSelected(item), item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
droid4mizer.onActivityResult(requestCode, resultCode, data);
}
/**
* SmartableActivity implementation.
*/
public AggregrateClass getAggregate()
{
return droid4mizer.getAggregate();
}
public void setAggregate(AggregrateClass aggregate)
{
droid4mizer.setAggregate(aggregate);
}
public Handler getHandler()
{
return droid4mizer.getHandler();
}
public void onException(Throwable throwable, boolean fromGuiThread)
{
droid4mizer.onException(throwable, fromGuiThread);
}
public void registerBroadcastListeners(BroadcastListener[] broadcastListeners)
{
droid4mizer.registerBroadcastListeners(broadcastListeners);
}
public void onBusinessObjectsRetrieved()
{
droid4mizer.onBusinessObjectsRetrieved();
}
public int getOnSynchronizeDisplayObjectsCount()
{
return droid4mizer.getOnSynchronizeDisplayObjectsCount();
}
public boolean isRefreshingBusinessObjectsAndDisplay()
{
return droid4mizer.isRefreshingBusinessObjectsAndDisplay();
}
public boolean isFirstLifeCycle()
{
return droid4mizer.isFirstLifeCycle();
}
public final boolean isInteracting()
{
return droid4mizer.isInteracting();
}
public boolean shouldKeepOn()
{
return droid4mizer.shouldKeepOn();
}
public void refreshBusinessObjectsAndDisplay(boolean retrieveBusinessObjects, Runnable onOver, boolean immediately)
{
droid4mizer.refreshBusinessObjectsAndDisplay(retrieveBusinessObjects, onOver, immediately);
}
/**
* Droid4mizeInterface implementation.
*/
public void onBeforeRetrievingDisplayObjects()
{
droid4mizer.onBeforeRetrievingDisplayObjects();
}
public Composite getCompositeActionHandler()
{
return droid4mizer.getCompositeActionHandler();
}
public CompositeHandler getCompositeActivityResultHandler()
{
return droid4mizer.getCompositeActivityResultHandler();
}
public SharedPreferences getPreferences()
{
return droid4mizer.getPreferences();
}
public void onActuallyCreated()
{
}
public void onActuallyDestroyed()
{
}
public List<StaticMenuCommand> getMenuCommands()
{
return null;
}
public final Activity getCheckedActivity()
throws IllegalStateException
{
if (getActivity() == null)
{
getResources();
}
return getActivity();
}
}
|
package stexfires.core.modifier;
import stexfires.core.Record;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* @author Mathias Kalb
* @since 0.1
*/
public class UnaryGroupModifier<T extends Record> extends GroupModifier<T, T> implements UnaryRecordStreamModifier<T> {
public UnaryGroupModifier(Function<? super T, ?> groupByClassifier,
Function<List<T>, ? extends T> aggregateFunction) {
super(groupByClassifier, aggregateFunction);
}
public UnaryGroupModifier(Function<? super T, ?> groupByClassifier,
Predicate<List<? super T>> havingPredicate,
Function<List<T>, ? extends T> aggregateFunction) {
super(groupByClassifier, havingPredicate, aggregateFunction);
}
public static <T extends Record> UnaryGroupModifier<T> first(Function<? super T, ?> groupByClassifier) {
// The list contains always at least one record.
Function<List<T>, T> aggregateFunction = list -> list.get(0);
return new UnaryGroupModifier<>(groupByClassifier, aggregateFunction);
}
public static <T extends Record> UnaryGroupModifier<T> last(Function<? super T, ?> groupByClassifier) {
// The list contains always at least one record.
Function<List<T>, T> aggregateFunction = list -> list.get(list.size() - 1);
return new UnaryGroupModifier<>(groupByClassifier, aggregateFunction);
}
public static <T extends Record> UnaryGroupModifier<T> max(Function<? super T, ?> groupByClassifier,
Comparator<? super T> comparator) {
Objects.requireNonNull(comparator);
// The list contains always at least one record.
@SuppressWarnings("OptionalGetWithoutIsPresent")
Function<List<T>, T> aggregateFunction = list -> list.stream().max(comparator).get();
return new UnaryGroupModifier<>(groupByClassifier, aggregateFunction);
}
public static <T extends Record> UnaryGroupModifier<T> min(Function<? super T, ?> groupByClassifier,
Comparator<? super T> comparator) {
Objects.requireNonNull(comparator);
// The list contains always at least one record.
@SuppressWarnings("OptionalGetWithoutIsPresent")
Function<List<T>, T> aggregateFunction = list -> list.stream().min(comparator).get();
return new UnaryGroupModifier<>(groupByClassifier, aggregateFunction);
}
}
|
package tw.kewang.logback.appender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import com.taskadapter.redmineapi.IssueManager;
import com.taskadapter.redmineapi.RedmineException;
import com.taskadapter.redmineapi.RedmineManager;
import com.taskadapter.redmineapi.RedmineManagerFactory;
import com.taskadapter.redmineapi.bean.Issue;
import com.taskadapter.redmineapi.bean.IssueFactory;
public class RedmineAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
private LayoutWrappingEncoder<ILoggingEvent> encoder;
private Layout<ILoggingEvent> layout;
private String url;
private String apiKey;
private int projectId = -1;
private String title;
private RedmineManager redmineManager;
private IssueManager issueManager;
@Override
public void start() {
if (!checkProperty()) {
addError("No set url / apiKey / projectId / title [" + name + "].");
return;
}
if (encoder == null) {
addError("No encoder set for the appender named [" + name + "].");
return;
}
try {
encoder.init(System.out);
layout = encoder.getLayout();
} catch (Exception e) {
addError("Exception", e);
}
redmineManager = RedmineManagerFactory.createWithApiKey(url, apiKey);
issueManager = redmineManager.getIssueManager();
super.start();
}
private boolean checkProperty() {
return url != null && url.length() != 0 && apiKey != null && apiKey.length() != 0 && title != null &&
title.length() != 0 && projectId != -1;
}
@Override
public void append(ILoggingEvent event) {
createIssue(event);
}
private void createIssue(ILoggingEvent event) {
Issue issue = IssueFactory.create(projectId, title + " - " + event.getTimeStamp());
issue.setDescription(layout.doLayout(event));
try {
issueManager.createIssue(issue);
} catch (RedmineException e) {
addError("Exception", e);
}
}
public LayoutWrappingEncoder<ILoggingEvent> getEncoder() {
return encoder;
}
public void setEncoder(LayoutWrappingEncoder<ILoggingEvent> encoder) {
this.encoder = encoder;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKey() {
return apiKey;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
public int getProjectId() {
return projectId;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
|
package valandur.webapi.message;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.serializer.TextSerializers;
import valandur.webapi.cache.CachedObject;
import valandur.webapi.serialize.JsonDetails;
import valandur.webapi.util.Constants;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/**
* Represents an interactive message which can be sent to players.
*/
@ApiModel("InteractiveMessage")
public class InteractiveMessage extends CachedObject<InteractiveMessage> {
private UUID uuid;
/**
* Gets the unique id of the message. This is generated when the messages is created.
* @return The unique id of the message.
*/
@ApiModelProperty(value = "The unique UUID of this message", required = true)
public UUID getUUID() {
return uuid;
}
private String id;
/**
* The id of the message. Useful to identify it in the response.
* @return The id of the message.
*/
@ApiModelProperty(value = "The id of the message. Used to identify responses.", required = true)
public String getId() {
return id;
}
private String target;
/**
* The target of the message, usually a player uuid. Can be set to "server" to send to all online players.
* @return The uuid of the target, or "server" to send to all online players.
*/
@ApiModelProperty(value = "The target of the message, usually this is a player UUID. Can be set to \"server\" to send to all online players.", required = true)
@JsonDetails
public String getTarget() {
return target;
}
private List<String> targets;
/**
* Gets all the targets this message is sent to, in case it is sent to multiple players.
* @return The list of target UUIDs.
*/
@ApiModelProperty("A list of targets that will receive the message. Usually a list of player UUIDs")
@JsonDetails
public List<String> getTargets() { return targets; }
private String message;
/**
* The message that is sent.
* @return The message content.
*/
@ApiModelProperty(dataType = "string", value = "The actual content of the message")
@JsonDetails
public Text getMessage() {
if (message == null) {
return null;
}
return TextSerializers.FORMATTING_CODE.deserialize(message);
}
private Boolean once;
/**
* Specifies wether the targets can reply multiple times or just once to this message. (This is per target)
* @return True if the targets can only reply once, false otherwise.
*/
@ApiModelProperty("True if this message can only be replied to once per target, false otherwise")
@JsonDetails
public boolean isOnce() {
return once != null && once;
}
private List<InteractiveMessageOption> options;
/**
* A map of answer keys to values. The value is displayed to the player as a clickable option, and upon clicking
* it the key is sent to the message web hook.
* @return A map of option keys to values.
*/
@ApiModelProperty("Clickable options that the player can select from")
@JsonDetails
public List<InteractiveMessageOption> getOptions() {
if (options != null) {
return new ArrayList<>(options);
}
return new ArrayList<>();
}
/**
* True if the message object has options attached, false otherwise.
* @return True if the message object has options, false otherwise.
*/
@JsonIgnore
public boolean hasOptions() {
return options != null;
}
public InteractiveMessage() {
super(null);
this.uuid = UUID.randomUUID();
}
@Override
public String getLink() {
return Constants.BASE_PATH + "/interactive-message/" + uuid;
}
@Override
public Optional<InteractiveMessage> getLive() {
return super.getLive();
}
}
|
package yanagishima.servlet;
import yanagishima.config.YanagishimaConfig;
import yanagishima.util.AccessControlUtil;
import yanagishima.util.HttpRequestUtil;
import yanagishima.util.SparkUtil;
import yanagishima.util.YarnUtil;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
@Singleton
public class HiveQueryDetailServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private YanagishimaConfig yanagishimaConfig;
@Inject
public HiveQueryDetailServlet(YanagishimaConfig yanagishimaConfig) {
this.yanagishimaConfig = yanagishimaConfig;
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String datasource = HttpRequestUtil.getParam(request, "datasource");
if (yanagishimaConfig.isCheckDatasource()) {
if (!AccessControlUtil.validateDatasource(request, datasource)) {
try {
response.sendError(SC_FORBIDDEN);
return;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String engine = HttpRequestUtil.getParam(request, "engine");
String resourceManagerUrl = yanagishimaConfig.getResourceManagerUrl(datasource);
Optional<String> idOptinal = Optional.ofNullable(request.getParameter("id"));
if(engine.equals("hive")) {
idOptinal.ifPresent(id -> {
if (id.startsWith("application_")) {
try {
response.sendRedirect(resourceManagerUrl + "/cluster/app/" + id);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
String userName = null;
Optional<String> hiveUser = Optional.ofNullable(request.getParameter("user"));
if(yanagishimaConfig.isUseAuditHttpHeaderName()) {
userName = request.getHeader(yanagishimaConfig.getAuditHttpHeaderName());
} else {
if (hiveUser.isPresent()) {
userName = hiveUser.get();
}
}
Optional<Map> applicationOptional = YarnUtil.getApplication(resourceManagerUrl, id, userName, yanagishimaConfig.getResourceManagerBegin(datasource));
applicationOptional.ifPresent(application -> {
String applicationId = (String) application.get("id");
try {
response.sendRedirect(resourceManagerUrl + "/cluster/app/" + applicationId);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
});
} else if(engine.equals("spark")) {
String sparkWebUrl = yanagishimaConfig.getSparkWebUrl(datasource);
if(idOptinal.isPresent()) {
String jobId = idOptinal.get();
try {
Integer.parseInt(jobId);
String sparkJdbcApplicationId = SparkUtil.getSparkJdbcApplicationId(sparkWebUrl);
response.sendRedirect(resourceManagerUrl + "/proxy/" + sparkJdbcApplicationId + "/jobs/job?id=" + jobId);
} catch (NumberFormatException e) {
// we can't specify spark jobId when user pushes info button in Query List tab
response.sendRedirect(sparkWebUrl);
}
} else {
response.sendRedirect(sparkWebUrl);
}
} else {
throw new IllegalArgumentException(engine + " is illegal");
}
}
}
|
package me.blackphreak.dynamicdungeon.MapBuilding;
import com.boydti.fawe.FaweAPI;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.selections.CuboidSelection;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat;
import com.sk89q.worldedit.regions.Region;
import me.blackphreak.dynamicdungeon.MapBuilding.Hub.DungeonSession;
import me.blackphreak.dynamicdungeon.Messages.db;
import me.blackphreak.dynamicdungeon.Messages.msg;
import me.blackphreak.dynamicdungeon.Supports.HolographicDisplays.cHologram;
import me.blackphreak.dynamicdungeon.Supports.HolographicDisplays.cHologramManager;
import me.blackphreak.dynamicdungeon.gb;
import me.blackphreak.dynamicdungeon.math;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
public class BuilderV2 {
public BuilderV2() {
}
public static DungeonSession build(Player sessionOwner, String fileNameWithoutExtension) {
try
{
File schematic = new File("plugins/DynamicDungeon/savedDungeons/" + fileNameWithoutExtension + ".schematic");
Clipboard cp = FaweAPI.load(schematic).getClipboard();
Location loc = gb.nextDungeonLocation.clone();
db.log("Building Session at Loc[" + loc.toString() + "] Owner[" + sessionOwner.getName() + "]");
final Vector maxVt = cp.getDimensions();
Location max = loc.clone().add(maxVt.getBlockX(), 0, maxVt.getBlockZ());
db.tlog("maxLoc: ["+max.toString() + "]");
Region region = new CuboidSelection(gb.dgWorld, loc, max).getRegionSelector().getRegion();
EditSession session = ClipboardFormat.SCHEMATIC.load(schematic).paste(region.getWorld(), new Vector(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()), true, true, null);
session.enableQueue();
//update the next loc.
gb.nextDungeonLocation = loc.clone().add(maxVt.getBlockX() + gb.gap, 0 ,0);
db.tlog("nextLoc: [" + gb.nextDungeonLocation.toString() + "]");
DungeonSession dg = new DungeonSession(sessionOwner, region, session, loc, max);
//pasting task done listener
session.addNotifyTask(() ->
{
//flushing the queue
session.flushQueue();
//getting location of spawn point & mob spawner
boolean spawnPointSign = false;
//get all the chunk inside the area.
World world = loc.getWorld();
int minX = loc.getChunk().getX();
int minZ = loc.getChunk().getZ();
int maxX = max.getChunk().getX();
int maxZ = max.getChunk().getZ();
Collection<Chunk> chunks = new HashSet<>();
db.tlog("min: [" + loc.toString() + "]");
db.tlog("max: [" + max.toString() + "]");
db.tlog("minX[" + minX + "], minZ[" + minZ + "] | maxX[" + maxX + "], maxZ[" + maxZ + "]");
// switching pos for min & max
if (minX > maxX)
{
int old_minX = minX;
minX = maxX;
maxX = old_minX;
}
if (minZ > maxZ)
{
int old_minZ = minZ;
minZ = maxZ;
maxZ = old_minZ;
}
// adding chunk to chunks list.
for (int x = minX; x <= maxX; x++)
{
for (int z = minZ; z <= maxZ; z++)
{
chunks.add(world.getChunkAt(x, z));
}
}
db.log("Loading chunks for session...");
for (Chunk chunk : chunks)
{
chunk.load();
db.tlog("Checking Chunk @ [x:" + chunk.getX() + ", z:" + chunk.getZ() + "]");
List<BlockState> signs = Arrays.stream(chunk.getTileEntities())
.filter(s -> s instanceof Sign)
.collect(Collectors.toList());
for (BlockState blockState : signs)
{
Sign sign = (Sign) blockState;
db.tlog("BlockState: " + blockState.getType().name() + " | " + blockState.getLocation().toString() + " | Line0[" + sign.getLine(0) + "]");
switch (sign.getLine(0).toLowerCase())
{
case "[dgmob]": //DunGeon MOB spawner
if (sign.getLine(1).isEmpty())
{
db.log("-+-- Error: Invalid Dungeon Mob Spawner Sign! Please Check!");
db.log(" + Debug:");
db.log(" +-- Sign Location: [" + sign.getX() + ", " + sign.getY() + ", " + sign.getZ() + "]");
db.log(" +-- Spawner Type : [dgmob]");
db.log(" +-- Debug Message: " + "line 2 (Spawner Name) is missing.");
db.logArr(" +-- Lines: ", sign.getLines());
}
else
dg.addSpawnerOnChunk(sign);
blockState.getBlock().setType(Material.AIR);
break;
case "[dgexit]": //DunGeon EXIT
if (sign.getLine(1).isEmpty())
{
db.log("-+-- Error: Invalid Dungeon Exit Sign! Please Check!");
db.log(" + Debug:");
db.log(" +-- Sign Location: [" + sign.getX() + ", " + sign.getY() + ", " + sign.getZ() + "]");
db.log(" +-- Spawner Type : [dgexit]");
db.log(" +-- Debug Message: " + "line 2 (Exit Location) is missing.");
db.logArr(" +-- Lines: ", sign.getLines());
}
else
{
dg.addExitPoint(
sign.getLocation(), //sign location
sign.getLine(1) //target location format:[world,x,y,z]
);
}
blockState.getBlock().setType(Material.AIR);
break;
case "[dgdec]": //DunGeon DECoration
if (sign.getLine(1).isEmpty())
{
db.log("-+-- Error: Invalid Dungeon Decoration Sign! Please Check!");
db.log(" + Debug:");
db.log(" +-- Sign Location: [" + sign.getX() + ", " + sign.getY() + ", " + sign.getZ() + "]");
db.log(" +-- Spawner Type : [dgexit]");
db.log(" +-- Debug Message: " + "line 2 (Decoration Type) is missing.");
db.logArr(" +-- Lines: ", sign.getLines());
}
else
{
//use what decoration? format:[decType]
switch (sign.getLine(1).toLowerCase())
{
case "hd":
// Holographic Display
if (gb.hd == null)
continue;
String hdName = sign.getLine(2); //holographic name
if (hdName.isEmpty())
{
db.log("-+-- Error: Invalid Dungeon Decoration Sign! Please Check!");
db.log(" + Debug:");
db.log(" +-- Sign Location: [" + sign.getX() + ", " + sign.getY() + ", " + sign.getZ() + "]");
db.log(" +-- Spawner Type : [dgdec]");
db.log(" +-- Debug Message: " + "line 3 (Holographic Name) is missing.");
db.logArr(" +-- Lines: ", sign.getLines());
continue;
}
if (!math.isDouble(sign.getLine(3)))
{
db.log("-+-- Error: Invalid Dungeon Decoration Sign! Please Check!");
db.log(" + Debug:");
db.log(" +-- Sign Location: [" + sign.getX() + ", " + sign.getY() + ", " + sign.getZ() + "]");
db.log(" +-- Spawner Type : [dgdec]");
db.log(" +-- Debug Message: " + "line 4 (offset) is invalid, it should be a double.");
db.logArr(" +-- Lines: ", sign.getLines());
continue;
}
double offset = Double.parseDouble(sign.getLine(3)); // offset value -- (double) offset of decoration y axis
cHologram chg = cHologramManager.getOrRegister(hdName).clone();
if (chg == null)
{
db.log("-+-- Error: Invalid Dungeon Decoration Sign! Please Check!");
db.log(" + Debug:");
db.log(" +-- Sign Location: [" + sign.getX() + ", " + sign.getY() + ", " + sign.getZ() + "]");
db.log(" +-- Spawner Type : [dgdec]");
db.log(" +-- Debug Message: " + "Hologram["+hdName+"] not found!");
db.logArr(" +-- Lines: ", sign.getLines());
continue;
}
chg.teleport(sign.getLocation().add(0, offset, 0));
break;
}
blockState.getBlock().setType(Material.AIR);
}
break;
}
if (!spawnPointSign
&& sign.getLine(0).toLowerCase().equals("[dgsp]")) //DunGeon Spawn Point
{
dg.setSpawnLocation(sign.getLocation());
spawnPointSign = true;
blockState.getBlock().setType(Material.AIR);
}
}
chunk.unload();
}
if (!spawnPointSign)
{
msg.send(sessionOwner, "Please contact administrator to fix this [Error: Builder->SLNF]");
db.log("Dungeon creation error, Spawn Location not found!");
//undo the dungeon session and mark as un-buildable dungeon
db.log("Killing Dungeon Session...");
dg.killSession();
}
else
{
db.log("Dungeon Session created.");
msg.send(sessionOwner, "Teleporting to your DungeonSession...");
dg.join(sessionOwner);
}
});
return dg;
}
catch (FileNotFoundException ex)
{
db.log("Dungeon File Not Found! [Name: "+fileNameWithoutExtension+".schematic]");
msg.send(sessionOwner, "Please contact admin to fix this. [DFNFE]"); //dungeon file not found exception
}
catch (Exception ex)
{
db.log("Unexpected Error Occurred, please post the message below to https://github.com/blackphreak/DynamicDungeon/issues");
ex.printStackTrace();
msg.send(sessionOwner, "Please contact admin to fix this. [UEEO]");
DungeonSession dg = gb.getDungeonSessionByPlayer(sessionOwner);
if (dg != null)
{
msg.send(sessionOwner, "Killing Dungeon Session...");
dg.killSession();
}
}
return null;
}
}
|
package org.openspaces.grid.esm;
import org.openspaces.admin.machine.Machine;
public interface ElasticScaleHandler {
/**
* An initialization call, parameterized with the configuration used at deployment.
* @param config The scale configuration.
*/
public void init(ElasticScaleHandlerConfig config);
/**
* A machine can be accepted/not-accepted (filtered) for whatever reason at any point in time.
* This will prevent from a GSC to be started on it.
*
* @param machine The machine to accept to filter.
* @return <code>true</code> to use this machine to start a GSC on; <code>false</code> to skip it.
*/
public boolean accept(Machine machine);
/**
* A scale out request to start a machine. Implementation may choose to block until it has
* scaled out (which will cause the ESM to wait until the call has returned, preventing it from
* handling other processing units). It's advised to scale out asynchronously due to long
* startup delays. As long as the machine has not been discovered, the ESM will repeatedly call
* this method until a new machine has been allocated. It's up to the implementation class to
* maintain the state and not allocate new resources before the pending allocations have
* completed. When a new machine is started, it should start a Grid Service Agent (GSA).
*
* @param context
* Context details
*/
public void scaleOut(ElasticScaleHandlerContext context);
/**
* A scale in request to terminate a machine. Implementation may choose to ignore it, or decide to terminate
* considering cost/benefit factors. Will be called only once per-last GSC on this machine to terminate. Implementation
* may choose to block until it has scaled in (which will cause the ESM to wait until the call has returned,
* preventing it from handling other processing units).
*
* @param machine The machine to terminate.
*/
public void scaleIn(Machine machine);
}
|
package musician101.itembank.commands.ibcommand;
import musician101.itembank.ItemBank;
import musician101.itembank.lib.Commands;
import musician101.itembank.lib.Messages;
import org.bukkit.command.CommandSender;
/**
* The code used when the Help argument is used in the ItemBank command.
*
* @author Musician101
*/
public class HelpCommand
{
public static boolean execute(ItemBank plugin, CommandSender sender, String[] args)
{
if (args.length == 1)
sender.sendMessage(Commands.HELP_LIST);
else
{
String cmd = args[1].toLowerCase();
if (cmd.equalsIgnoreCase(Commands.ACCOUNT_CMD))
sender.sendMessage(Commands.ACCOUNT_HELP);
else if (cmd.equalsIgnoreCase(Commands.ALIAS_CMD))
sender.sendMessage(Commands.ALIAS_HELP);
else if (cmd.equalsIgnoreCase(Commands.CONFIG_CMD))
sender.sendMessage(Commands.CONFIG_HELP);
else if (cmd.equalsIgnoreCase(Commands.DEPOSIT_CMD))
sender.sendMessage(Commands.DEPOSIT_HELP);
else if (cmd.equalsIgnoreCase(Commands.PURGE_CMD))
sender.sendMessage(Commands.PURGE_HELP);
else if (cmd.equalsIgnoreCase(Commands.RELOAD_CMD))
sender.sendMessage(Commands.RELOAD_HELP);
else if (cmd.equalsIgnoreCase(Commands.WITHDRAW_CMD))
sender.sendMessage(Commands.WITHDRAW_HELP);
else
sender.sendMessage(Messages.PREFIX + "Error: Command not recognized.");
}
return true;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.colar.netbeans.fan.handlers;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import net.colar.netbeans.fan.FanLanguage;
import net.colar.netbeans.fan.FanTokenID;
import net.colar.netbeans.fan.antlr.FanLexer;
import net.colar.netbeans.fan.antlr.LexerUtils;
import org.netbeans.api.lexer.Token;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.editor.BaseDocument;
import org.netbeans.editor.Utilities;
import org.netbeans.modules.csl.api.EditorOptions;
import org.netbeans.modules.csl.api.KeystrokeHandler;
import org.netbeans.modules.csl.api.OffsetRange;
import org.netbeans.modules.csl.spi.ParserResult;
import org.netbeans.modules.editor.indent.api.IndentUtils;
/**
* Impl. of keystrokeHandler
* Provides support for closing bracket/quote insertion and the likes
* Also deals with trying to guess/insert proper indentation.
* @author tcolar
*/
public class FanKeyStrokeHandler implements KeystrokeHandler
{
//Note .*? = match anything NON-greedily
private static Pattern IF_1LINER=Pattern.compile("^\\s*if\\s*\\(.*?\\)[^{]*");
private int lastAdditions;
@Override
public boolean beforeCharInserted(Document document, int caretOffset, JTextComponent target, char car) throws BadLocationException
{
BaseDocument doc = (BaseDocument) document;
if (!isInsertMatchingEnabled(doc))
{
return false;
}
lastAdditions = 0;
boolean modified = false;
String toInsert = "";
String prev = null;
if (caretOffset > 0)
{
prev = doc.getText(caretOffset - 1, 1);
}
Token<? extends FanTokenID> token = LexerUtils.getFanTokenAt(document, caretOffset);
// If User types closing item we closed automaticaly, skip it
if (token != null)
{
int ord = token.id().ordinal();
if ((car == '"' && ord == FanLexer.INC_STR) ||
(car == '"' && ord == FanLexer.STR) ||
(car == '"' && ord == FanLexer.QUOTSTR) ||
(car == '`' && ord == FanLexer.INC_URI) ||
(car == '\'' && ord == FanLexer.CHAR) ||
(car == '`' && ord == FanLexer.INC_URI) ||
(car == '`' && ord == FanLexer.URI) ||
(car == ']' && ord == FanLexer.SQ_BRACKET_R) ||
(car == ')' && ord == FanLexer.PAR_R) ||
(car == '}' && ord == FanLexer.BRACKET_R))
{
// just skip the existing same characters
target.getCaret().setDot(caretOffset + 1);
return true;
}
}
// Same but dual characters
if ((car == '/' && prev.equals("*") && token.id().ordinal() == FanLexer.MULTI_COMMENT) ||
(car == '>' && prev.equals("|") && token.id().ordinal() == FanLexer.DSL))
{
// remove previous char and then skip existing one
doc.remove(caretOffset - 1, 1);
target.getCaret().setDot(caretOffset + 1);
return true;
}
// If within those tokens, don't do anything special
if (token.id().ordinal() == FanLexer.STR ||
token.id().ordinal() == FanLexer.CHAR ||
token.id().ordinal() == FanLexer.DOC ||
token.id().ordinal() == FanLexer.DSL ||
token.id().ordinal() == FanLexer.EXEC_COMMENT ||
token.id().ordinal() == FanLexer.INC_COMMENT ||
token.id().ordinal() == FanLexer.INC_DSL ||
token.id().ordinal() == FanLexer.INC_STR ||
token.id().ordinal() == FanLexer.INC_URI ||
token.id().ordinal() == FanLexer.LINE_COMMENT ||
token.id().ordinal() == FanLexer.MULTI_COMMENT ||
token.id().ordinal() == FanLexer.QUOTSTR ||
token.id().ordinal() == FanLexer.STR ||
token.id().ordinal() == FanLexer.URI)
{
return false;
}
// Automatically add closing item/brace when opening one entered
switch (car)
{
case '{':
toInsert = "{}";
break;
case '(':
toInsert = "()";
break;
case '[':
toInsert = "[]";
break;
case '`':
toInsert = "``";
break;
case '\'':
toInsert = "''";
break;
case '"':
toInsert = "\"\"";
break;
case '|':
if (prev.equals("<"))
{
toInsert = "||>";
}
break;
case '*':
if (prev.equals("/"))
{
toInsert = "**/";
}
break;
}
// do the insertion job
if (toInsert.length() > 0)
{
doc.insertString(caretOffset, toInsert, null);
target.getCaret().setDot(caretOffset + 1);
modified = true;
if (toInsert.length() > 0)
{
lastAdditions = toInsert.length() - 1;
}
}
return modified;
}
@Override
public boolean afterCharInserted(Document document, int caretOffset, JTextComponent target, char car) throws BadLocationException
{
// doing all in beforeCharInserted for now.
return false;
}
@Override
public boolean charBackspaced(Document document, int caretOffset, JTextComponent target, char car) throws BadLocationException
{
BaseDocument doc = (BaseDocument) document;
if (!isInsertMatchingEnabled(doc))
{
return false;
}
// If we just auto-added chars in beforeCharInserted() and the user press backspace right away,
// we remove them now.
if (lastAdditions > 0)
{
doc.remove(caretOffset, lastAdditions);
return true;
}
return false;
}
@Override
public int beforeBreak(Document document, int caretOffset, JTextComponent target) throws BadLocationException
{
String NL =/*Character.LINE_SEPARATOR*/ "\n";
int indentSize = IndentUtils.indentLevelSize(document);
Caret caret = target.getCaret();
BaseDocument doc = (BaseDocument) document;
int lineBegin = Utilities.getRowStart(doc, caretOffset);
int lineEnd = Utilities.getRowEnd(doc, caretOffset);
int above = Utilities.getPositionAbove(target, caretOffset, 0);
int prevLineBegin = Utilities.getRowStart(doc, above);
int prevLineEnd = Utilities.getRowEnd(doc, above);
String line = null;
String prevLine = null;
if (lineBegin > -1 && lineEnd > lineBegin)
{
line = doc.getText(lineBegin, lineEnd - lineBegin);
}
if (prevLineBegin > -1 && prevLineEnd > prevLineBegin)
{
prevLine = doc.getText(prevLineBegin, prevLineEnd - prevLineBegin);
}
String lineHead = doc.getText(lineBegin, caretOffset - lineBegin);
String lineTail = doc.getText(caretOffset, lineEnd - caretOffset);
// standard indent (same as the line we pressed return on)
int indent = 0;
if (lineBegin > 0)
{
indent = IndentUtils.lineIndent(document, lineBegin);
}
int dotOffset = 0;
String insert = "";
String trimmedLine = line.trim();
if (line != null)
{
System.err.println("Head: "+lineHead);
// If within doc -> insert the ** on next line
// insert only if the current doc line is not empty("**") - except for first one (empty ok)
boolean isFirstDocLine = prevLine == null || !prevLine.trim().startsWith("**");
if (trimmedLine.startsWith("**") && (isFirstDocLine || trimmedLine.length() > 3))
{
insert = "** ";
} else if (lineHead.trim().endsWith("{"))
{
if (lineTail.trim().startsWith("}"))
{
insert = NL;
dotOffset = -1;
}
indent += indentSize;
}else if(IF_1LINER.matcher(lineHead).matches())
{
// if statement, not followed by {
System.err.print("One liner If");
indent += indentSize;
}
}
// Do the insertion.
String indentStr = IndentUtils.createIndentString(document, indent);
doc.insertString(caretOffset, indentStr + insert, null);
caret.setDot(caretOffset);
return caretOffset + indentStr.length() + insert.length() + 1 + dotOffset;
}
/**
* Helps finding mathcing opening/closing items (ex: {})
* @param document
* @param caretOffset
* @return
*/
@Override
public OffsetRange findMatching(Document document, int caretOffset)
{
TokenSequence ts = LexerUtils.getFanTokenSequence(document);
int searchOffset = 2; // start after rightToken
// Prefer matching the token to the right of caret
Token token = LexerUtils.getFanTokenAt(document, caretOffset + 1);
if (token == null)
{
// if rightToken is null, use left token
token = LexerUtils.getFanTokenAt(document, caretOffset);
searchOffset = 1; // start after leftToken
} else
{
int ord = token.id().ordinal();
// if rightToken is not 'matcheable', use left token
if (ord != FanLexer.PAR_L && ord != FanLexer.PAR_R &&
ord != FanLexer.SQ_BRACKET_L && ord != FanLexer.SQ_BRACKET_R &&
ord != FanLexer.BRACKET_L && ord != FanLexer.BRACKET_R)
{
token = LexerUtils.getFanTokenAt(document, caretOffset);
searchOffset = 1; // start after leftToken
}
}
if (token != null)
{
int ord = token.id().ordinal();
//Ok, now try to find the matching token
switch (ord)
{
case FanLexer.PAR_L:
ts.move(caretOffset + searchOffset);// start after opening char
return LexerUtils.findRangeFromOpening(document, ts, FanLexer.PAR_L, FanLexer.PAR_R);
case FanLexer.PAR_R:
ts.move(caretOffset + searchOffset - 1);// start before opening char (since going backward)
return LexerUtils.findRangeFromClosing(document, ts, FanLexer.PAR_L, FanLexer.PAR_R);
case FanLexer.BRACKET_L:
ts.move(caretOffset + searchOffset);
return LexerUtils.findRangeFromOpening(document, ts, FanLexer.BRACKET_L, FanLexer.BRACKET_R);
case FanLexer.BRACKET_R:
ts.move(caretOffset + searchOffset - 1);
return LexerUtils.findRangeFromClosing(document, ts, FanLexer.BRACKET_L, FanLexer.BRACKET_R);
case FanLexer.SQ_BRACKET_L:
ts.move(caretOffset + searchOffset);
return LexerUtils.findRangeFromOpening(document, ts, FanLexer.SQ_BRACKET_L, FanLexer.SQ_BRACKET_R);
case FanLexer.SQ_BRACKET_R:
ts.move(caretOffset + searchOffset - 1);
return LexerUtils.findRangeFromClosing(document, ts, FanLexer.SQ_BRACKET_L, FanLexer.SQ_BRACKET_R);
}
}
//default - no match
return OffsetRange.NONE;
}
@Override
public List<OffsetRange> findLogicalRanges(ParserResult arg0, int arg1)
{
// not impl yet.
// what is this used for ? - provide using FanStructureAnalyzer ??
return Collections.emptyList();
}
@Override
public int getNextWordOffset(Document arg0, int arg1, boolean arg2)
{
// not impl, default will be fine.
return -1;
}
/**
* wether brcaket matching is turned on
* @param doc
* @return
*/
public boolean isInsertMatchingEnabled(BaseDocument doc)
{
// Default: true
EditorOptions options = EditorOptions.get(FanLanguage.FAN_MIME_TYPE);
if (options != null)
{
return options.getMatchBrackets();
}
return true;
}
// Look backward in tokenstream for first unclosed char
// either { [ or (
// within this ident level ?
private char lastUnclosedToken(int caretOffset)
{
//TODO
throw new UnsupportedOperationException("Not yet implemented");
}
}
|
package org.adligo.models.core.relations.client;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.adligo.models.core.client.EMailAddress;
import org.adligo.models.core.client.I_StorageInfo;
import org.adligo.models.core.client.InvalidParameterException;
import org.adligo.models.core.client.ModelsCoreConstantsObtainer;
import org.adligo.models.core.client.ids.I_StorageIdentifier;
public class EMailMutant implements I_EMail {
private static final long serialVersionUID = 1L;
public static final String SET_ID = "setId";
public static final String ADD_ATTACHMENT = "addAttachment";
public static final String E_MAIL = "EMail";
public static final String ADD_BCC = "addBCC";
public static final String ADD_CC = "addCC";
public static final String ADD_TO = "addTo";
public static final String SET_FROM = "setFrom";
private I_StorageIdentifier id;
private I_StorageInfo storageInfo;
private EMailAddress from;
private String subject;
private String body;
private Set<EMailAddress> toAddresses = new HashSet<EMailAddress>();
private Set<EMailAddress> ccAddresses = new HashSet<EMailAddress>();
private Set<EMailAddress> bccAddresses = new HashSet<EMailAddress>();
private Set<I_StorageIdentifier> attachments = new HashSet<I_StorageIdentifier>();
public EMailMutant() {}
public EMailMutant(I_EMail other) throws InvalidParameterException {
try {
if (other.getId() != null) {
setId(other.getId());
}
setFrom(other.getFrom());
subject = other.getSubject();
body = other.getBody();
toAddresses.addAll(other.getToAddresses());
ccAddresses.addAll(other.getCcAddresses());
bccAddresses.addAll(other.getBccAddresses());
attachments.addAll(other.getAttachments());
} catch (InvalidParameterException e) {
throw new InvalidParameterException(e.getMessage(), E_MAIL, e);
}
if (toAddresses.size() == 0) {
if (ccAddresses.size() == 0) {
if (bccAddresses.size() == 0) {
throw new InvalidParameterException(
ModelsCoreConstantsObtainer.getConstants().getEMailRequiresADestAddress(), E_MAIL);
}
}
}
}
public EMailAddress getFrom() {
return from;
}
public String getSubject() {
return subject;
}
public String getBody() {
return body;
}
public void setFrom(EMailAddress from) throws InvalidParameterException {
if (from == null) {
throw new InvalidParameterException(
ModelsCoreConstantsObtainer.getConstants().getEMailRequiresAFromAddress(), SET_FROM);
}
if (!from.isValid()) {
throw new InvalidParameterException(
ModelsCoreConstantsObtainer.getConstants().getEMailRequiresAValidFromAddress(), SET_FROM);
}
this.from = from;
}
public void setSubject(String subject) throws InvalidParameterException {
this.subject = subject;
}
public void setBody(String body) throws InvalidParameterException {
this.body = body;
}
public Set<I_StorageIdentifier> getAttachments() {
return Collections.unmodifiableSet(attachments);
}
public Set<EMailAddress> getBccAddresses() {
return Collections.unmodifiableSet(bccAddresses);
}
public Set<EMailAddress> getCcAddresses() {
return Collections.unmodifiableSet(ccAddresses);
}
public Set<EMailAddress> getToAddresses() {
return Collections.unmodifiableSet(toAddresses);
}
private void validateAddr(EMailAddress to, String method) throws InvalidParameterException {
if (to == null) {
throw new InvalidParameterException(
ModelsCoreConstantsObtainer.getConstants().getEMailRequiresAValidAddress(), method);
}
if (!to.isValid()) {
throw new InvalidParameterException(
ModelsCoreConstantsObtainer.getConstants().getEMailRequiresAValidAddress(), method);
}
}
public boolean addTo(EMailAddress to) throws InvalidParameterException {
validateAddr(to, ADD_TO);
return toAddresses.add(to);
}
public boolean removeTo(EMailAddress to) {
return toAddresses.remove(to);
}
public boolean setToAddresses(Collection<EMailAddress> tos) throws InvalidParameterException {
toAddresses.clear();
for (EMailAddress ea: tos) {
validateAddr(ea, ADD_TO);
toAddresses.add(ea);
}
return true;
}
public boolean removeAllTo(Collection<EMailAddress> tos) {
return toAddresses.removeAll(tos);
}
public boolean addCcAddresses(EMailAddress to) throws InvalidParameterException {
validateAddr(to, ADD_CC);
return ccAddresses.add(to);
}
public boolean removeCc(EMailAddress to) {
return ccAddresses.remove(to);
}
public boolean setCcAddresses(Collection<EMailAddress> tos) throws InvalidParameterException {
if (tos == null) {
throw new InvalidParameterException(
ModelsCoreConstantsObtainer.getConstants().getEMailRequiresAValidAddress(), ADD_CC);
}
ccAddresses.clear();
for (EMailAddress ea: tos) {
validateAddr(ea, ADD_CC);
ccAddresses.add(ea);
}
return true;
}
public boolean removeAllCc(Collection<EMailAddress> tos) {
return ccAddresses.removeAll(tos);
}
public boolean addBcc(EMailAddress to) throws InvalidParameterException {
validateAddr(to, ADD_BCC);
return bccAddresses.add(to);
}
public boolean removeBcc(EMailAddress to) {
return bccAddresses.remove(to);
}
public boolean setBccAddresses(Collection<EMailAddress> tos) throws InvalidParameterException {
bccAddresses.clear();
for (EMailAddress ea: tos) {
validateAddr(ea, ADD_BCC);
bccAddresses.add(ea);
}
return true;
}
public boolean removeAllBcc(Collection<EMailAddress> tos) {
return bccAddresses.removeAll(tos);
}
public boolean addAttachment(I_StorageIdentifier id) throws InvalidParameterException {
validateAttachemt(id);
return attachments.add(id);
}
private void validateAttachemt(I_StorageIdentifier id)
throws InvalidParameterException {
if (id == null) {
throw new InvalidParameterException(
ModelsCoreConstantsObtainer.getConstants().getEMailRequiresANonNullAttachemt(), ADD_ATTACHMENT);
}
if (!id.hasValue()) {
throw new InvalidParameterException(
ModelsCoreConstantsObtainer.getConstants().getEMailRequiresAValidAttachemt(), ADD_ATTACHMENT);
}
}
public boolean removeAttachment(I_StorageIdentifier id) {
return attachments.remove(id);
}
public boolean setAttachments(Collection<I_StorageIdentifier> tos) throws InvalidParameterException {
attachments.clear();
for (I_StorageIdentifier ea: tos) {
validateAttachemt(ea);
attachments.add(ea);
}
return true;
}
public boolean removeAllAttachments(Set<I_StorageIdentifier> tos) {
return attachments.removeAll(tos);
}
public I_StorageIdentifier getId() {
return id;
}
public void setId(I_StorageIdentifier id) throws InvalidParameterException {
if (id == null) {
throw new InvalidParameterException(
ModelsCoreConstantsObtainer.getConstants().getStorageIdRequired(), SET_ID);
}
this.id = id;
}
@Override
public I_StorageInfo getStorageInfo() {
return storageInfo;
}
public void setStorageInfo(I_StorageInfo info) throws InvalidParameterException {
storageInfo = info;
}
}
|
package com.eqt.ssc.web.rest;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.eqt.ssc.accounts.AccountManager;
import com.eqt.ssc.accounts.AccountManagerFactory;
import com.eqt.ssc.model.SSCAccount;
import com.eqt.ssc.model.Token;
@Path("/")
public class AccountResource {
//our 'dao'
AccountManager man = AccountManagerFactory.getInstance();
public static class ManagedAccounts {
public List<String> accounts = new ArrayList<String>();
}
@GET
@Path("managedAccounts")
@Produces(MediaType.APPLICATION_JSON)
public ManagedAccounts getManagedAccounts() {
ManagedAccounts m = new ManagedAccounts();
List<Token> accounts = man.getAccounts();
for(Token t : accounts)
m.accounts.add(t.getAccountId());
return m;
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("addAccount")
public Response putAccount(SSCAccount account) {
if(account != null) {
try {
man.addAccount(account);
} catch (UnsupportedOperationException e) {
return Response.status(Status.NOT_ACCEPTABLE).build();
}
return Response.ok().build();
}
return Response.status(Status.BAD_REQUEST).build();
}
}
|
package org.aikodi.chameleon.oo.expression;
import java.lang.ref.SoftReference;
import java.util.List;
import org.aikodi.chameleon.core.Config;
import org.aikodi.chameleon.core.declaration.Declaration;
import org.aikodi.chameleon.core.lookup.DeclarationCollector;
import org.aikodi.chameleon.core.lookup.DeclarationSelector;
import org.aikodi.chameleon.core.lookup.DeclaratorSelector;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.reference.CrossReferenceTarget;
import org.aikodi.chameleon.core.reference.CrossReferenceWithTarget;
import org.aikodi.chameleon.core.reference.UnresolvableCrossReference;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.exception.ChameleonProgrammerException;
import org.aikodi.chameleon.oo.method.DeclarationWithParameters;
import org.aikodi.chameleon.oo.statement.CheckedExceptionList;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.generics.ActualTypeArgument;
import org.aikodi.chameleon.util.Lists;
import org.aikodi.chameleon.util.association.Multi;
import org.aikodi.chameleon.util.association.Single;
/**
* @author Marko van Dooren
*
* @param <D>import java.lang.ref.SoftReference;
* The type of declaration invoked by this invocation.
*/
public abstract class MethodInvocation<D extends DeclarationWithParameters>
extends TargetedExpression implements CrossReferenceWithTarget<D> {
public MethodInvocation(CrossReferenceTarget target) {
setTarget(target);
}
public final DeclarationSelector<D> selector() throws LookupException {
if (_selector == null) {
_selector = createSelector();
}
return _selector;
}
protected abstract DeclarationSelector<D> createSelector()
throws LookupException;
protected DeclarationSelector<D> _selector;
@Override
public CheckedExceptionList getDirectCEL() throws LookupException {
throw new Error();
}
@Override
public CheckedExceptionList getDirectAbsCEL() throws LookupException {
throw new Error();
}
@Override
public Verification verifySelf() {
Verification result = Valid.create();
try {
if (getElement() == null) {
result = result.and(new UnresolvableCrossReference(this));
}
} catch(LookupException e) {
result = result.and(new UnresolvableCrossReference(this, e.getMessage()));
} catch(ChameleonProgrammerException e) {
result = result.and(new UnresolvableCrossReference(this, e.getMessage()));
}
return result;
}
/**
* TARGET
*/
private Single<CrossReferenceTarget> _target = new Single<CrossReferenceTarget>(
this);
@Override
public CrossReferenceTarget getTarget() {
return _target.getOtherEnd();
}
@Override
public void setTarget(CrossReferenceTarget target) {
set(_target,target);
}
private Multi<Expression> _parameters = new Multi<Expression>(this,"arguments");
{
_parameters.enableCache();
}
public void addArgument(Expression parameter) {
add(_parameters, parameter);
}
public void addAllArguments(List<? extends Expression> parameters) {
for (Expression parameter : parameters) {
addArgument(parameter);
}
}
public void removeParameter(Expression parameter) {
remove(_parameters,parameter);
}
public List<Expression> getActualParameters() {
return _parameters.getOtherEnds();
}
/*
* @
*
* @ public behavior
*
* @
*
* @ post \result == getActualParameters().size;
*
* @
*/
public int nbActualParameters() {
return _parameters.size();
}
public List<Type> getActualParameterTypes() throws LookupException {
List<Expression> params = getActualParameters();
final List<Type> result = Lists.create();
for (Expression param : params) {
Type type = param.getType();
if (type != null) {
result.add(type);
} else {
// Type ttt = ((ActualParameter)param).getType(); //DEBUG
throw new LookupException("Cannot determine type of expression");
}
}
return result;
}
/*
* @
*
* @ also public behavior
*
* @
*
* @ post
* \result.containsAll(getMethod().getExceptionClause().getExceptionTypes
* (this));
*
* @ post
* (getLanguage().getUncheckedException(getPackage().getDefaultPackage()) !=
* null) ==>
*
* @ result.contains(getLanguage().getUncheckedException(getPackage().
* getDefaultPackage());
*
* @
*/
// public Set getMethodExceptions() throws LookupException {
// Set result = getMethod().getExceptionClause().getExceptionTypes(this);
// Type rte =
// language(ObjectOrientedLanguage.class).getUncheckedException();
// if (rte != null) {
// result.add(rte);
// return result;
/*
* @
*
* @ also public behavior
*
* @
*
* @ post \result.containsAll(getMethodExceptions());
*
* @ post
* (getLanguage().getNullInvocationException(getPackage().getDefaultPackage
* ()) != null) ==>
*
* @ result.contains(getLanguage().getNullInvocationException(getPackage().
* getDefaultPackage());
*
* @
*/
// public Set getDirectExceptions() throws LookupException {
// Set result = getMethodExceptions();
// if(getTarget() != null) {
// Util.addNonNull(language(ObjectOrientedLanguage.class).getNullInvocationException(),
// result);
// return result;
// public Set getDirectExceptions() throws NotResolvedException {
// Set result = getMethodExceptions();
// Type npe =
// getLanguage().getNullInvocationException(getPackage().getDefaultPackage());
// if(npe != null) {
// result.add(npe);
// result.addAll(getTarget().getDirectExceptions());
// Iterator iter = getActualParameters().iterator();
// while(iter.hasNext()) {
// result.addAll(((Expression)iter.next()).getDirectExceptions());
// return result;
@Override
public D getElement() throws LookupException {
D el = getElement(selector());
if (el == null) // debug
getElement(selector());
return el;
}
@Override
public Declaration getDeclarator() throws LookupException {
return getElement(new DeclaratorSelector(selector()));
}
private SoftReference<Declaration> _cache;
@Override
public void flushLocalCache() {
super.flushLocalCache();
_cache = null;
}
public Declaration getCache() {
Declaration result = null;
if (Config.cacheElementReferences() == true) {
result = (_cache == null ? null : _cache.get());
}
return result;
}
public void setCache(Declaration value) {
// if(! value.isDerived()) {
if (Config.cacheElementReferences() == true) {
_cache = new SoftReference<Declaration>(value);
}
// } else {
// _cache = null;
}
/**
* Return the method invoked by this invocation.
*/
/*
* @
*
* @ public behavior
*
* @
*
* @ post \result != null;
*
* @
*
* @ signals (NotResolvedException) (* The method could not be found *);
*
* @
*/
// public abstract D getMethod() throws MetamodelException;
public <X extends Declaration> X getElement(DeclarationSelector<X> selector) throws LookupException {
X result = null;
// OPTIMISATION
boolean cache = selector.equals(selector());
if (cache) {
result = (X) getCache();
}
if (result != null) {
return result;
}
synchronized(this) {
if(result != null) {
return result;
}
DeclarationCollector<X> collector = new DeclarationCollector<X>(selector);
CrossReferenceTarget target = getTarget();
if (target == null) {
lexicalContext().lookUp(collector);
} else {
target.targetContext().lookUp(collector);
}
result = collector.result();
// if (result != null) {
// // OPTIMISATION
if (cache) {
setCache(result);
}
return result;
// } else {
// // repeat lookup for debugging purposes.
// // Config.setCaching(false);
// if (target == null) {
// result = lookupContext().lookUp(selector);
// } else {
// result = target.targetContext().lookUp(selector);
// throw new LookupException("Method returned by invocation is null");
}
}
// protected CrossReferenceWithArguments cloneSelf() {
// return new CrossReferenceWithArguments();
// public void substituteParameter(String name, Expression expr) throws
// MetamodelException {
// if(getTarget()!= null) {
// getTarget().substituteParameter(name, expr);
public List<ActualTypeArgument> typeArguments() {
return _genericArguments.getOtherEnds();
}
public boolean hasTypeArguments() {
return _genericArguments.size() > 0;
}
public void addArgument(ActualTypeArgument arg) {
add(_genericArguments,arg);
}
public void addAllTypeArguments(List<ActualTypeArgument> args) {
for (ActualTypeArgument argument : args) {
addArgument(argument);
}
}
public void removeArgument(ActualTypeArgument arg) {
remove(_genericArguments,arg);
}
private Multi<ActualTypeArgument> _genericArguments = new Multi<ActualTypeArgument>(this,"type arguments");
}
|
package com.structurizr.example;
import com.structurizr.Workspace;
import com.structurizr.api.StructurizrClient;
import com.structurizr.documentation.Format;
import com.structurizr.documentation.StructurizrDocumentationTemplate;
import com.structurizr.model.*;
import com.structurizr.util.MapUtils;
import com.structurizr.view.*;
public class BigBankPlc {
private static final long WORKSPACE_ID = 36141;
private static final String API_KEY = "key";
private static final String API_SECRET = "secret";
private static final String EXISTING_SYSTEM_TAG = "Existing System";
private static final String BANK_STAFF_TAG = "Bank Staff";
private static final String WEB_BROWSER_TAG = "Web Browser";
private static final String MOBILE_APP_TAG = "Mobile App";
private static final String DATABASE_TAG = "Database";
private static final String FAILOVER_TAG = "Failover";
public static void main(String[] args) throws Exception {
Workspace workspace = new Workspace("Big Bank plc", "This is an example workspace to illustrate the key features of Structurizr, based around a fictional online banking system.");
Model model = workspace.getModel();
ViewSet views = workspace.getViews();
model.setEnterprise(new Enterprise("Big Bank plc"));
// people and software systems
Person customer = model.addPerson(Location.External, "Personal Banking Customer", "A customer of the bank, with personal bank accounts.");
SoftwareSystem internetBankingSystem = model.addSoftwareSystem(Location.Internal, "Internet Banking System", "Allows customers to view information about their bank accounts, and make payments.");
customer.uses(internetBankingSystem, "Views account balances, and makes payments using");
SoftwareSystem mainframeBankingSystem = model.addSoftwareSystem(Location.Internal, "Mainframe Banking System", "Stores all of the core banking information about customers, accounts, transactions, etc.");
mainframeBankingSystem.addTags(EXISTING_SYSTEM_TAG);
internetBankingSystem.uses(mainframeBankingSystem, "Gets account information from, and makes payments using");
SoftwareSystem emailSystem = model.addSoftwareSystem(Location.Internal, "E-mail System", "The internal Microsoft Exchange e-mail system.");
internetBankingSystem.uses(emailSystem, "Sends e-mail using");
emailSystem.addTags(EXISTING_SYSTEM_TAG);
emailSystem.delivers(customer, "Sends e-mails to");
SoftwareSystem atm = model.addSoftwareSystem(Location.Internal, "ATM", "Allows customers to withdraw cash.");
atm.addTags(EXISTING_SYSTEM_TAG);
atm.uses(mainframeBankingSystem, "Uses");
customer.uses(atm, "Withdraws cash using");
Person customerServiceStaff = model.addPerson(Location.Internal, "Customer Service Staff", "Customer service staff within the bank.");
customerServiceStaff.addTags(BANK_STAFF_TAG);
customerServiceStaff.uses(mainframeBankingSystem, "Uses");
customer.interactsWith(customerServiceStaff, "Asks questions to", "Telephone");
Person backOfficeStaff = model.addPerson(Location.Internal, "Back Office Staff", "Administration and support staff within the bank.");
backOfficeStaff.addTags(BANK_STAFF_TAG);
backOfficeStaff.uses(mainframeBankingSystem, "Uses");
// containers
Container singlePageApplication = internetBankingSystem.addContainer("Single-Page Application", "Provides all of the Internet banking functionality to customers via their web browser.", "JavaScript and Angular");
singlePageApplication.addTags(WEB_BROWSER_TAG);
Container mobileApp = internetBankingSystem.addContainer("Mobile App", "Provides a limited subset of the Internet banking functionality to customers via their mobile device.", "Xamarin");
mobileApp.addTags(MOBILE_APP_TAG);
Container webApplication = internetBankingSystem.addContainer("Web Application", "Delivers the static content and the Internet banking single page application.", "Java and Spring MVC");
Container apiApplication = internetBankingSystem.addContainer("API Application", "Provides Internet banking functionality via a JSON/HTTPS API.", "Java and Spring MVC");
Container database = internetBankingSystem.addContainer("Database", "Stores user registration information, hashed authentication credentials, access logs, etc.", "Oracle Database Schema");
database.addTags(DATABASE_TAG);
customer.uses(webApplication, "Visits bigbank.com/ib using", "HTTPS");
customer.uses(singlePageApplication, "Views account balances, and makes payments using", "");
customer.uses(mobileApp, "Views account balances, and makes payments using", "");
webApplication.uses(singlePageApplication, "Delivers to the customer's web browser", "");
apiApplication.uses(database, "Reads from and writes to", "JDBC");
apiApplication.uses(mainframeBankingSystem, "Makes API calls to", "XML/HTTPS");
apiApplication.uses(emailSystem, "Sends e-mail using", "SMTP");
// components
// - for a real-world software system, you would probably want to extract the components using
// - static analysis/reflection rather than manually specifying them all
Component signinController = apiApplication.addComponent("Sign In Controller", "Allows users to sign in to the Internet Banking System.", "Spring MVC Rest Controller");
Component accountsSummaryController = apiApplication.addComponent("Accounts Summary Controller", "Provides customers with a summary of their bank accounts.", "Spring MVC Rest Controller");
Component resetPasswordController = apiApplication.addComponent("Reset Password Controller", "Allows users to reset their passwords with a single use URL.", "Spring MVC Rest Controller");
Component securityComponent = apiApplication.addComponent("Security Component", "Provides functionality related to signing in, changing passwords, etc.", "Spring Bean");
Component mainframeBankingSystemFacade = apiApplication.addComponent("Mainframe Banking System Facade", "A facade onto the mainframe banking system.", "Spring Bean");
Component emailComponent = apiApplication.addComponent("E-mail Component", "Sends e-mails to users.", "Spring Bean");
apiApplication.getComponents().stream().filter(c -> "Spring MVC Rest Controller".equals(c.getTechnology())).forEach(c -> singlePageApplication.uses(c, "Makes API calls to", "JSON/HTTPS"));
apiApplication.getComponents().stream().filter(c -> "Spring MVC Rest Controller".equals(c.getTechnology())).forEach(c -> mobileApp.uses(c, "Makes API calls to", "JSON/HTTPS"));
signinController.uses(securityComponent, "Uses");
accountsSummaryController.uses(mainframeBankingSystemFacade, "Uses");
resetPasswordController.uses(securityComponent, "Uses");
resetPasswordController.uses(emailComponent, "Uses");
securityComponent.uses(database, "Reads from and writes to", "JDBC");
mainframeBankingSystemFacade.uses(mainframeBankingSystem, "Uses", "XML/HTTPS");
emailComponent.uses(emailSystem, "Sends e-mail using");
model.addImplicitRelationships();
// deployment nodes and container instances
DeploymentNode developerLaptop = model.addDeploymentNode("Development", "Developer Laptop", "A developer laptop.", "Microsoft Windows 10 or Apple macOS");
DeploymentNode apacheTomcat = developerLaptop.addDeploymentNode("Docker Container - Web Server", "A Docker container.", "Docker")
.addDeploymentNode("Apache Tomcat", "An open source Java EE web server.", "Apache Tomcat 8.x", 1, MapUtils.create("Xmx=512M", "Xms=1024M", "Java Version=8"));
apacheTomcat.add(webApplication);
apacheTomcat.add(apiApplication);
developerLaptop.addDeploymentNode("Docker Container - Database Server", "A Docker container.", "Docker")
.addDeploymentNode("Database Server", "A development database.", "Oracle 12c")
.add(database);
developerLaptop.addDeploymentNode("Web Browser", "", "Google Chrome, Mozilla Firefox, Apple Safari or Microsoft Edge").add(singlePageApplication);
DeploymentNode customerMobileDevice = model.addDeploymentNode("Live", "Customer's mobile device", "", "Apple iOS or Android");
customerMobileDevice.add(mobileApp);
DeploymentNode customerComputer = model.addDeploymentNode("Live", "Customer's computer", "", "Microsoft Windows or Apple macOS");
customerComputer.addDeploymentNode("Web Browser", "", "Google Chrome, Mozilla Firefox, Apple Safari or Microsoft Edge").add(singlePageApplication);
DeploymentNode bigBankDataCenter = model.addDeploymentNode("Live", "Big Bank plc", "", "Big Bank plc data center");
DeploymentNode liveWebServer = bigBankDataCenter.addDeploymentNode("bigbank-web***", "A web server residing in the web server farm, accessed via F5 BIG-IP LTMs.", "Ubuntu 16.04 LTS", 4, MapUtils.create("Location=London and Reading"));
liveWebServer.addDeploymentNode("Apache Tomcat", "An open source Java EE web server.", "Apache Tomcat 8.x", 1, MapUtils.create("Xmx=512M", "Xms=1024M", "Java Version=8"))
.add(webApplication);
DeploymentNode liveApiServer = bigBankDataCenter.addDeploymentNode("bigbank-api***", "A web server residing in the web server farm, accessed via F5 BIG-IP LTMs.", "Ubuntu 16.04 LTS", 8, MapUtils.create("Location=London and Reading"));
liveApiServer.addDeploymentNode("Apache Tomcat", "An open source Java EE web server.", "Apache Tomcat 8.x", 1, MapUtils.create("Xmx=512M", "Xms=1024M", "Java Version=8"))
.add(apiApplication);
DeploymentNode primaryDatabaseServer = bigBankDataCenter.addDeploymentNode("bigbank-db01", "The primary database server.", "Ubuntu 16.04 LTS", 1, MapUtils.create("Location=London"))
.addDeploymentNode("Oracle - Primary", "The primary, live database server.", "Oracle 12c");
primaryDatabaseServer.add(database);
DeploymentNode secondaryDatabaseServer = bigBankDataCenter.addDeploymentNode("bigbank-db02", "The secondary database server.", "Ubuntu 16.04 LTS", 1, MapUtils.create("Location=Reading"))
.addDeploymentNode("Oracle - Secondary", "A secondary, standby database server, used for failover purposes only.", "Oracle 12c");
ContainerInstance secondaryDatabase = secondaryDatabaseServer.add(database);
model.getRelationships().stream().filter(r -> r.getDestination().equals(secondaryDatabase)).forEach(r -> r.addTags(FAILOVER_TAG));
Relationship dataReplicationRelationship = primaryDatabaseServer.uses(secondaryDatabaseServer, "Replicates data to", "");
secondaryDatabase.addTags(FAILOVER_TAG);
// views/diagrams
SystemLandscapeView systemLandscapeView = views.createSystemLandscapeView("SystemLandscape", "The system landscape diagram for Big Bank plc.");
systemLandscapeView.addAllElements();
systemLandscapeView.setPaperSize(PaperSize.A5_Landscape);
SystemContextView systemContextView = views.createSystemContextView(internetBankingSystem, "SystemContext", "The system context diagram for the Internet Banking System.");
systemContextView.setEnterpriseBoundaryVisible(false);
systemContextView.addNearestNeighbours(internetBankingSystem);
systemContextView.setPaperSize(PaperSize.A5_Landscape);
ContainerView containerView = views.createContainerView(internetBankingSystem, "Containers", "The container diagram for the Internet Banking System.");
containerView.add(customer);
containerView.addAllContainers();
containerView.add(mainframeBankingSystem);
containerView.add(emailSystem);
containerView.setPaperSize(PaperSize.A5_Landscape);
ComponentView componentView = views.createComponentView(apiApplication, "Components", "The component diagram for the API Application.");
componentView.add(mobileApp);
componentView.add(singlePageApplication);
componentView.add(database);
componentView.addAllComponents();
componentView.add(mainframeBankingSystem);
componentView.add(emailSystem);
componentView.setPaperSize(PaperSize.A5_Landscape);
systemLandscapeView.addAnimation(internetBankingSystem, customer, mainframeBankingSystem, emailSystem);
systemLandscapeView.addAnimation(atm);
systemLandscapeView.addAnimation(customerServiceStaff, backOfficeStaff);
systemContextView.addAnimation(internetBankingSystem);
systemContextView.addAnimation(customer);
systemContextView.addAnimation(mainframeBankingSystem);
systemContextView.addAnimation(emailSystem);
containerView.addAnimation(customer, mainframeBankingSystem, emailSystem);
containerView.addAnimation(webApplication);
containerView.addAnimation(singlePageApplication);
containerView.addAnimation(mobileApp);
containerView.addAnimation(apiApplication);
containerView.addAnimation(database);
componentView.addAnimation(singlePageApplication, mobileApp, database, emailSystem, mainframeBankingSystem);
componentView.addAnimation(signinController, securityComponent);
componentView.addAnimation(accountsSummaryController, mainframeBankingSystemFacade);
componentView.addAnimation(resetPasswordController, emailComponent);
// dynamic diagrams and deployment diagrams are not available with the Free Plan
DynamicView dynamicView = views.createDynamicView(apiApplication, "SignIn", "Summarises how the sign in feature works in the single-page application.");
dynamicView.add(singlePageApplication, "Submits credentials to", signinController);
dynamicView.add(signinController, "Calls isAuthenticated() on", securityComponent);
dynamicView.add(securityComponent, "select * from users where username = ?", database);
dynamicView.setPaperSize(PaperSize.A5_Landscape);
DeploymentView developmentDeploymentView = views.createDeploymentView(internetBankingSystem, "DevelopmentDeployment", "An example development deployment scenario for the Internet Banking System.");
developmentDeploymentView.setEnvironment("Development");
developmentDeploymentView.add(developerLaptop);
developmentDeploymentView.setPaperSize(PaperSize.A5_Landscape);
DeploymentView liveDeploymentView = views.createDeploymentView(internetBankingSystem, "LiveDeployment", "An example live deployment scenario for the Internet Banking System.");
liveDeploymentView.setEnvironment("Live");
liveDeploymentView.add(bigBankDataCenter);
liveDeploymentView.add(customerMobileDevice);
liveDeploymentView.add(customerComputer);
liveDeploymentView.add(dataReplicationRelationship);
liveDeploymentView.setPaperSize(PaperSize.A5_Landscape);
// colours, shapes and other diagram styling
Styles styles = views.getConfiguration().getStyles();
styles.addElementStyle(Tags.ELEMENT).color("#ffffff");
styles.addElementStyle(Tags.SOFTWARE_SYSTEM).background("#1168bd");
styles.addElementStyle(Tags.CONTAINER).background("#438dd5");
styles.addElementStyle(Tags.COMPONENT).background("#85bbf0").color("#000000");
styles.addElementStyle(Tags.PERSON).background("#08427b").shape(Shape.Person).fontSize(22);
styles.addElementStyle(EXISTING_SYSTEM_TAG).background("#999999");
styles.addElementStyle(BANK_STAFF_TAG).background("#999999");
styles.addElementStyle(WEB_BROWSER_TAG).shape(Shape.WebBrowser);
styles.addElementStyle(MOBILE_APP_TAG).shape(Shape.MobileDeviceLandscape);
styles.addElementStyle(DATABASE_TAG).shape(Shape.Cylinder);
styles.addElementStyle(FAILOVER_TAG).opacity(25);
styles.addRelationshipStyle(FAILOVER_TAG).opacity(25).position(70);
// documentation
// - usually the documentation would be included from separate Markdown/AsciiDoc files, but this is just an example
StructurizrDocumentationTemplate template = new StructurizrDocumentationTemplate(workspace);
template.addContextSection(internetBankingSystem, Format.Markdown,
"Here is some context about the Internet Banking System...\n" +
"\n" +
"\n" +
"### Internet Banking System\n...\n" +
"### Mainframe Banking System\n...\n");
template.addContainersSection(internetBankingSystem, Format.Markdown,
"Here is some information about the containers within the Internet Banking System...\n" +
"\n" +
"### Web Application\n...\n" +
"### Database\n...\n");
template.addComponentsSection(webApplication, Format.Markdown,
"Here is some information about the API Application...\n" +
"\n" +
"### Sign in process\n" +
"Here is some information about the Sign In Controller, including how the sign in process works...\n" +
"");
template.addDevelopmentEnvironmentSection(internetBankingSystem, Format.AsciiDoc,
"Here is some information about how to set up a development environment for the Internet Banking System...\n" +
"image::embed:DevelopmentDeployment[]");
template.addDeploymentSection(internetBankingSystem, Format.AsciiDoc,
"Here is some information about the live deployment environment for the Internet Banking System...\n" +
"image::embed:LiveDeployment[]");
StructurizrClient structurizrClient = new StructurizrClient(API_KEY, API_SECRET);
structurizrClient.putWorkspace(WORKSPACE_ID, workspace);
}
}
|
package rhomobile.mapview;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import com.rho.RhoClassFactory;
import com.rho.RhoConf;
import com.rho.RhoEmptyLogger;
import com.rho.RhoLogger;
import com.rho.net.IHttpConnection;
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.util.Comparator;
import net.rim.device.api.util.SimpleSortingVector;
public class ESRIMapField extends Field implements RhoMapField {
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("ESRIMapField");
private static final int TILE_SIZE = 256;
private static final int MIN_ZOOM = 0;
private static final int MAX_ZOOM = 19;
private static final int CACHE_UPDATE_INTERVAL = 500;
// Maximum size of image cache (number of images stored locally)
private static final int MAX_IMAGE_CACHE_SIZE = 32;
// Mode of decoding EncodedImage to bitmap
private static final int DECODE_MODE = EncodedImage.DECODE_NATIVE |
EncodedImage.DECODE_NO_DITHER | EncodedImage.DECODE_READONLY |
EncodedImage.DECODE_ALPHA;
// Constants required to coordinates calculations
private static final long MIN_LATITUDE = degreesToPixelsY(90, MAX_ZOOM);
private static final long MAX_LATITUDE = degreesToPixelsY(-90, MAX_ZOOM);
private static final long MAX_LONGITUDE = degreesToPixelsX(180, MAX_ZOOM);
// DON'T CHANGE THIS CONSTANT!!!
// This is maximum absolute value of sine ( == sin(85*PI/180) ) allowed by Merkator projection
private static final double MAX_SIN = 0.99627207622;
private static final double PI = Math.PI;
private Hashtable mMapUrls = new Hashtable();
private String mMapType;
// Coordinates of center in pixels of maximum zoom level
private long mLatitude = degreesToPixelsY(0, MAX_ZOOM);
private long mLongitude = degreesToPixelsX(0, MAX_ZOOM);
private int mZoom = 0;
private int mWidth;
private int mHeight;
private static class ByCoordinatesComparator implements Comparator {
public int compare (Object o1, Object o2) {
CachedImage img1 = (CachedImage)o1;
CachedImage img2 = (CachedImage)o2;
if (img1.latitude < img2.latitude) return -1;
if (img1.latitude > img2.latitude) return 1;
if (img1.longitude < img2.longitude) return 1;
if (img1.longitude > img2.longitude) return -1;
if (img1.zoom < img2.zoom) return -1;
if (img1.zoom > img2.zoom) return 1;
return 0;
}
}
private static class ByAccessTimeComparator implements Comparator {
public int compare (Object o1, Object o2) {
long l1 = ((CachedImage)o1).lastUsed;
long l2 = ((CachedImage)o2).lastUsed;
return l1 < l2 ? 1 : l1 > l2 ? -1 : 0;
}
};
private class CachedImage {
public EncodedImage image;
public Bitmap bitmap;
public long latitude;
public long longitude;
public int zoom;
public String key;
public long lastUsed;
public CachedImage(EncodedImage img, long lat, long lon, int z) {
image = img;
bitmap = null;
latitude = lat;
longitude = lon;
zoom = z;
key = makeCacheKey(latitude, longitude, zoom);
lastUsed = System.currentTimeMillis();
}
};
private class ImageCache {
private Hashtable hash;
private SimpleSortingVector cvec;
private SimpleSortingVector tvec;
public ImageCache() {
reinit();
}
private void reinit() {
hash = new Hashtable();
cvec = new SimpleSortingVector();
cvec.setSortComparator(new ByCoordinatesComparator());
cvec.setSort(true);
tvec = new SimpleSortingVector();
tvec.setSortComparator(new ByAccessTimeComparator());
tvec.setSort(true);
}
public ImageCache clone() {
ImageCache cloned = new ImageCache();
for (Enumeration e = hash.elements(); e.hasMoreElements();)
cloned.put((CachedImage)e.nextElement());
return cloned;
}
public Enumeration sortedByCoordinates() {
return cvec.elements();
}
public CachedImage get(String key) {
return (CachedImage)hash.get(key);
}
public void put(CachedImage img) {
put(img, true);
}
private void put(CachedImage img, boolean doCheck) {
hash.put(img.key, img);
cvec.addElement(img);
tvec.addElement(img);
if (doCheck) check();
}
private void check() {
if (hash.size() < MAX_IMAGE_CACHE_SIZE)
return;
SimpleSortingVector vec = tvec;
reinit();
Enumeration e = vec.elements();
while (e.hasMoreElements()) {
CachedImage img = (CachedImage)e.nextElement();
put(img, false);
}
}
};
private ImageCache mImgCache = new ImageCache();
private static abstract class MapCommand {
public abstract String type();
public abstract String description();
}
private static class MapFetchCommand extends MapCommand {
public String baseUrl;
public int zoom;
public long latitude;
public long longitude;
public MapFetchCommand(String baseUrl, int zoom, long latitude, long longitude) {
this.baseUrl = baseUrl;
this.zoom = zoom;
this.latitude = latitude;
this.longitude = longitude;
}
private String makeDescription() {
return "" + zoom + "/" + latitude + "/" + longitude;
}
public String type() {
return "fetch";
}
public String description() {
return "fetch:" + makeDescription();
}
};
private class MapThread extends Thread {
private static final int BLOCK_SIZE = 1024;
private Vector commands = new Vector();
private boolean active = true;
public void process(MapCommand cmd) {
synchronized (commands) {
commands.addElement(cmd);
commands.notify();
}
}
public void stop() {
active = false;
interrupt();
}
public void run() {
try {
while (active) {
MapCommand cmd = null;
synchronized (commands) {
if (commands.isEmpty()) {
try {
commands.wait();
} catch (InterruptedException e) {
// Nothing
}
continue;
}
int last = commands.size() - 1;
cmd = (MapCommand)commands.elementAt(last);
commands.removeElementAt(last);
if (cmd == null)
continue;
}
try {
if (cmd instanceof MapFetchCommand)
processCommand((MapFetchCommand)cmd);
else
LOG.INFO("Received unknown command: " + cmd.type() + ", ignore it");
}
catch (Exception e) {
LOG.ERROR("Processing of map command failed", e);
}
}
}
catch (Exception e) {
LOG.ERROR("Fatal error in map thread", e);
}
finally {
LOG.INFO("Map thread exit");
}
}
private byte[] fetchData(String url) throws IOException {
IHttpConnection conn = RhoClassFactory.getNetworkAccess().connect(url,false);
conn.setRequestMethod("GET");
//conn.setRequestProperty("User-Agent", "Blackberry");
//conn.setRequestProperty("Accept", "*/*");
InputStream is = conn.openInputStream();
int code = conn.getResponseCode();
if (code/100 != 2)
throw new IOException("ESRI map server respond with " + code + " " + conn.getResponseMessage());
int size = conn.getHeaderFieldInt("Content-Length", 0);
byte[] data = new byte[size];
if (size == 0)
size = 1073741824; // 1Gb :)
byte[] buf = new byte[BLOCK_SIZE];
for (int offset = 0; offset < size;) {
int n = is.read(buf, 0, BLOCK_SIZE);
if (n <= 0)
break;
if (offset + n > data.length) {
byte[] newData = new byte[offset + n];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
System.arraycopy(buf, 0, data, offset, n);
offset += n;
}
return data;
}
private void processCommand(MapFetchCommand cmd) throws IOException {
LOG.TRACE("Processing map fetch command (thread #" + hashCode() + "): " + cmd.description());
long ts = toMaxZoom(TILE_SIZE, cmd.zoom);
int row = (int)(cmd.latitude/ts);
int column = (int)(cmd.longitude/ts);
StringBuffer url = new StringBuffer();
url.append(cmd.baseUrl);
url.append("/MapServer/tile/");
url.append(cmd.zoom);
url.append('/');
url.append(row);
url.append('/');
url.append(column);
String finalUrl = url.toString();
byte[] data = fetchData(finalUrl);
EncodedImage img = EncodedImage.createEncodedImage(data, 0, data.length);
img.setDecodeMode(DECODE_MODE);
long lat = row*ts + ts/2;
long lon = column*ts + ts/2;
LOG.TRACE("Map request done, draw just received image: zoom=" + cmd.zoom + ", lat=" + lat + ", lon=" + lon);
CachedImage cachedImage = new CachedImage(img, lat, lon, cmd.zoom);
// Put image to the cache and trigger redraw
synchronized (ESRIMapField.this) {
mImgCache.put(cachedImage);
}
redraw();
}
};
private MapThread mMapThread = new MapThread();
private class CacheUpdate extends Thread {
private boolean active = true;
public void stop() throws InterruptedException {
active = false;
join();
}
public void run() {
LOG.TRACE("Cache update thread started");
while (active) {
try {
Thread.sleep(CACHE_UPDATE_INTERVAL);
}
catch (InterruptedException e) {
// Ignore
}
// ", mLongitude=" + mLongitude + ", mZoom=" + mZoom);
long ts = toMaxZoom(TILE_SIZE, mZoom);
//LOG.TRACE("Tile size on the maximum zoom level: " + ts);
long h = toMaxZoom(mHeight, mZoom);
//LOG.TRACE("Height of the screen on the maximum zoom level: " + h);
long w = toMaxZoom(mWidth, mZoom);
//LOG.TRACE("Width of the screen on the maximum zoom level: " + w);
long totalTiles = MapTools.math_pow2(mZoom);
//LOG.TRACE("Total tiles count on zoom level " + mZoom + ": " + totalTiles);
long tlLat = mLatitude - h/2;
if (tlLat < 0) tlLat = 0;
long tlLon = mLongitude - w/2;
if (tlLon < 0) tlLon = 0;
//LOG.TRACE("tlLat=" + tlLat + ", tlLon=" + tlLon);
for (long lat = (tlLat/ts)*ts, latLim = Math.min(tlLat + h + ts, ts*totalTiles); lat < latLim; lat += ts) {
for (long lon = (tlLon/ts)*ts, lonLim = Math.min(tlLon + w + ts, ts*totalTiles); lon < lonLim; lon += ts) {
String key = makeCacheKey(lat, lon, mZoom);
MapFetchCommand cmd = null;
synchronized (ESRIMapField.this) {
CachedImage img = mImgCache.get(key);
if (img == null) {
//LOG.TRACE("lat=" + lat + ", lon=" + lon + "; key=" + key);
String baseUrl = getMapUrl();
cmd = new MapFetchCommand(baseUrl, mZoom, lat, lon);
CachedImage dummy = new CachedImage(null, lat, lon, mZoom);
mImgCache.put(dummy);
}
}
if (cmd != null)
mMapThread.process(cmd);
}
}
}
LOG.TRACE("Cache update thread stopped");
}
};
private CacheUpdate mCacheUpdate = new CacheUpdate();
public ESRIMapField() {
String url = RhoConf.getInstance().getString("esri_map_url_roadmap");
if (url == null || url.length() == 0)
url = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/";
mMapUrls.put("roadmap", url);
url = RhoConf.getInstance().getString("esri_map_url_satellite");
if (url == null || url.length() == 0)
url = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/";
mMapUrls.put("satellite", url);
mMapType = "roadmap";
LOG.TRACE("ESRIMapField ctor: mLatitude=" + mLatitude + ", mLongitude=" + mLongitude);
mMapThread.start();
mCacheUpdate.start();
}
public void close() {
mMapThread.stop();
try {
mCacheUpdate.stop();
}
catch (InterruptedException e) {
LOG.ERROR("Stopping of cache update thread was interrupted", e);
}
}
public void redraw() {
invalidate();
}
private String getMapUrl() {
String url = (String)mMapUrls.get(mMapType);
if (url == null)
url = (String)mMapUrls.get("roadmap");
return url;
}
protected void paint(Graphics graphics) {
// Draw background
for (int i = 1, lim = 2*Math.max(mWidth, mHeight); i < lim; i += 5) {
graphics.drawLine(0, i, i, 0);
}
ImageCache imgCache;
synchronized (this) {
imgCache = mImgCache.clone();
}
// Draw map tiles
Enumeration e = imgCache.sortedByCoordinates();
while (e.hasMoreElements()) {
// Draw map
CachedImage img = (CachedImage)e.nextElement();
if (img.image == null)
continue;
paintImage(graphics, img);
}
}
private void paintImage(Graphics graphics, CachedImage img) {
// Skip images with zoom level which differ from the current zoom level
if (img.zoom != mZoom)
return;
long left = -toCurrentZoom(mLongitude - img.longitude, mZoom);
long top = -toCurrentZoom(mLatitude - img.latitude, mZoom);
if (img.zoom != mZoom) {
double x = MapTools.math_pow2d(img.zoom - mZoom);
int factor = Fixed32.tenThouToFP((int)(x*10000));
img.image = img.image.scaleImage32(factor, factor);
img.bitmap = null;
}
int imgWidth = img.image.getScaledWidth();
int imgHeight = img.image.getScaledHeight();
left += (mWidth - imgWidth)/2;
top += (mHeight - imgHeight)/2;
int w = mWidth - (int)left;
int h = mHeight - (int)top;
int maxW = mWidth + TILE_SIZE;
int maxH = mHeight + TILE_SIZE;
if (w < 0 || h < 0 || w > maxW || h > maxH) {
// Image will not be displayed, free its bitmap and skip it
img.bitmap = null;
return;
}
if (img.bitmap == null)
img.bitmap = img.image.getBitmap();
graphics.drawBitmap((int)left, (int)top, w, h, img.bitmap, 0, 0);
}
protected void layout(int w, int h) {
mWidth = Math.min(mWidth, w);
mHeight = Math.min(mHeight, h);
setExtent(mWidth, mHeight);
}
public int calculateZoom(double latDelta, double lonDelta) {
int zoom1 = calcZoom(latDelta, mWidth);
int zoom2 = calcZoom(lonDelta, mHeight);
return zoom1 < zoom2 ? zoom1 : zoom2;
}
public Field getBBField() {
return this;
}
public double getCenterLatitude() {
return pixelsToDegreesY(mLatitude, MAX_ZOOM);
}
public double getCenterLongitude() {
return pixelsToDegreesX(mLongitude, MAX_ZOOM);
}
private void validateCoordinates() {
if (mLatitude < MIN_LATITUDE) mLatitude = MIN_LATITUDE;
if (mLatitude > MAX_LATITUDE) mLatitude = MAX_LATITUDE;
}
public void moveTo(double lat, double lon) {
mLatitude = degreesToPixelsY(lat, MAX_ZOOM);
mLongitude = degreesToPixelsX(lon, MAX_ZOOM);
validateCoordinates();
//LOG.TRACE("moveTo(" + lat + ", " + lon + "): mLatitude=" + mLatitude + ", mLongitude=" + mLongitude);
}
public void move(int dx, int dy) {
mLatitude += toMaxZoom(dy, mZoom);
mLongitude += toMaxZoom(dx, mZoom);
validateCoordinates();
//LOG.TRACE("move(" + dx + ", " + dy + "): mLatitude=" + mLatitude + ", mLongitude=" + mLongitude);
}
public void setMapType(String type) {
mMapType = type;
//LOG.TRACE("setMapType: " + mMapType);
}
public void setPreferredSize(int width, int height) {
mWidth = width;
mHeight = height;
}
public int getPreferredWidth() {
return mWidth;
}
public int getPreferredHeight() {
return mHeight;
}
public void setZoom(int zoom) {
mZoom = zoom;
if (mZoom < MIN_ZOOM) mZoom = MIN_ZOOM;
if (mZoom > MAX_ZOOM) mZoom = MAX_ZOOM;
LOG.TRACE("setZoom: " + mZoom);
}
public int getMaxZoom() {
return MAX_ZOOM;
}
public int getMinZoom() {
return MIN_ZOOM;
}
public int getZoom() {
return mZoom;
}
private static int calcZoom(double degrees, int pixels) {
double angleRatio = degrees*TILE_SIZE/pixels;
double twoInZoomExp = 360/angleRatio;
int zoom = (int)MapTools.math_log2(twoInZoomExp);
return zoom;
}
private static long toMaxZoom(long n, int zoom) {
if (n == 0) return 0;
long pow = MapTools.math_pow2(MAX_ZOOM - zoom);
return n*pow;
}
private static long toCurrentZoom(long coord, int zoom) {
if (coord == 0) return 0;
long pow = MapTools.math_pow2(MAX_ZOOM - zoom);
return coord/pow;
}
private static long degreesToPixelsX(double n, int z) {
while (n < -180.0) n += 360.0;
while (n > 180.0) n -= 360.0;
double angleRatio = 360d/MapTools.math_pow2(z);
double val = (n + 180)*TILE_SIZE/angleRatio;
return (long)val;
}
private static long degreesToPixelsY(double n, int z) {
// Merkator projection
double sin_phi = MapTools.math_sin(n*PI/180);
// MAX_SIN - maximum value of sine allowed by Merkator projection
// (~85.0 degrees of north latitude)
if (sin_phi < -MAX_SIN) sin_phi = -MAX_SIN;
if (sin_phi > MAX_SIN) sin_phi = MAX_SIN;
double ath = MapTools.math_atanh(sin_phi);
double val = TILE_SIZE * MapTools.math_pow2(z) * (1 - ath/PI)/2;
return (long)val;
}
private static double pixelsToDegreesX(long n, int z) {
while (n < 0) n += MAX_LONGITUDE;
while (n > MAX_LONGITUDE) n -= MAX_LONGITUDE;
double angleRatio = 360d/MapTools.math_pow2(z);
double val = n*angleRatio/TILE_SIZE - 180.0;
return val;
}
private static double pixelsToDegreesY(long n, int z) {
// Revert calculation of Merkator projection
double ath = PI - 2*PI*n/(TILE_SIZE*MapTools.math_pow2(z));
double th = MapTools.math_tanh(ath);
double val = 180*MapTools.math_asin(th)/PI;
return val;
}
private String makeCacheKey(long lat, long lon, int z) {
while (lon < 0) lon += MAX_LONGITUDE;
while (lon > MAX_LONGITUDE) lon -= MAX_LONGITUDE;
long ts = toMaxZoom(TILE_SIZE, z);
long x = lon/ts;
long y = lat/ts;
StringBuffer buf = new StringBuffer();
buf.append(z);
buf.append(';');
buf.append(x);
buf.append(';');
buf.append(y);
String key = buf.toString();
return key;
}
public long toScreenCoordinateX(double n) {
long v = degreesToPixelsX(n, mZoom);
long center = toCurrentZoom(mLongitude, mZoom);
long begin = center - mWidth/2;
return v - begin;
}
public long toScreenCoordinateY(double n) {
long v = degreesToPixelsY(n, mZoom);
long center = toCurrentZoom(mLatitude, mZoom);
long begin = center - mHeight/2;
return v - begin;
}
}
|
package com.jenzz.buildconstants.sample;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@SuppressWarnings("unused")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Java constants
String javaString = SampleBuildConstants.ASTRING;
boolean javaBoolean = SampleBuildConstants.ABOOLEAN;
int javaNumber = SampleBuildConstants.ANUMBER;
// XML constants
Resources res = getResources();
String xmlString = res.getString(R.string.astring);
boolean xmlBoolean = res.getBoolean(R.bool.aboolean);
int xmlNumber = res.getInteger(R.integer.anumber);
}
}
|
package org.biojava.spice.manypanel.renderer;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.GeneralPath;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.swing.JPanel;
import org.biojava.bio.structure.Chain;
import org.biojava.bio.structure.ChainImpl;
import org.biojava.bio.structure.Group;
import org.biojava.spice.ResourceManager;
public class AlignmentPanel extends JPanel {
final static long serialVersionUID = 98567459640964908l;
static Logger logger = Logger.getLogger("org.biojava.spice");
public static Color COLOR_MATCH_ONE;
public static Color COLOR_MATCH_TWO;
public static Color COLOR_MISMATCH_ONE;
public static Color COLOR_MISMATCH_TWO;
static {
String col1 = ResourceManager.getString("org.biojava.spice.manypanel.renderer.AlignmentPanel.ColorMatchOne");
COLOR_MATCH_ONE= Color.decode(col1);
String col2 = ResourceManager.getString("org.biojava.spice.manypanel.renderer.AlignmentPanel.ColorMatchTwo");
COLOR_MATCH_TWO = Color.decode(col2);
String col3 = ResourceManager.getString("org.biojava.spice.manypanel.renderer.AlignmentPanel.ColorMisMatchOne");
COLOR_MISMATCH_ONE= Color.decode(col3);
String col4 = ResourceManager.getString("org.biojava.spice.manypanel.renderer.AlignmentPanel.ColorMisMatchTwo");
COLOR_MISMATCH_TWO= Color.decode(col4);
}
Chain sequence1;
Chain sequence2;
float scale1;
float scale2;
int length1;
int length2;
Map alignmentMap1;
Map alignmentMap2;
int scrollLeftX1 ;
int scrollLeftX2 ;
public AlignmentPanel() {
super();
sequence1 = new ChainImpl();
sequence2 = new ChainImpl();
length1=0;
length2=0;
this.setBackground(SequenceScalePanel.BACKGROUND_COLOR);
scale1 = 1.0f;
scale2 = 1.0f;
scrollLeftX1 = 0;
scrollLeftX2 = 0;
clearAlignment();
}
public void clearAlignment(){
alignmentMap1 = new HashMap();
alignmentMap2 = new HashMap();
scrollLeftX1 = 0;
scrollLeftX2 = 0;
}
public void setSequence1(Chain c){
synchronized(sequence1){
sequence1 = c;
}
length1=c.getLength();
scrollLeftX1 = 0;
}
public void setSequence2(Chain c){
synchronized (sequence2){
sequence2 = c;
}
length2 = c.getLength();
scrollLeftX2 = 0;
}
public void setScrolled1(int v){
scrollLeftX1 = v;
}
public void setScrolled2(int v){
scrollLeftX2 =v;
}
public void setAlignmentMap1(Map m){
synchronized (alignmentMap1) {
alignmentMap1 = m;
}
}
public void setAlignmentMap2(Map m){
alignmentMap2 = m;
}
public void setScale1(float scale){
scale1 =scale;
this.repaint();
}
public void setScale2(float scale){
scale2=scale;
this.repaint();
}
public void paint(Graphics g){
super.paint(g);
//TODO: find the bug why sometimes start with UniProt does not color alignment correctly
//System.out.println("sequence1 " + sequence1.getSequence());
//System.out.println("sequence2 " + sequence2.getSequence());
Graphics2D g2D = (Graphics2D) g;
g2D.setColor(SequenceScalePanel.SEQUENCE_COLOR);
int aminosize1 = Math.round(1*scale1);
if ( aminosize1 < 1)
aminosize1 = 1;
int aminosize2 = Math.round(scale2);
if ( aminosize2 <1)
aminosize2 = 1;
g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Composite oldComp = g2D.getComposite();
g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.8f));
// paint alignment
int h = this.getHeight();
Set keys1= alignmentMap1.keySet();
Iterator iter = keys1.iterator();
while (iter.hasNext()){
Object o = iter.next();
if ( ! (o instanceof Integer)){
// logger.info("what is that? " + o);
continue;
}
Integer pos1 = (Integer) o;
Object o2 = alignmentMap1.get(pos1);
if ( ! (o2 instanceof Integer)) {
// logger.info("what is that? " + o2);
continue;
}
Integer pos2 = (Integer) o2;
int h1 = pos1.intValue();
int h2 = pos2.intValue();
if ( h1 < 0 )
h1 = 0;
if ( h2 < 0)
h2 = 0;
int p1 = Math.round(h1*scale1) + SequenceScalePanel.DEFAULT_X_START - scrollLeftX1 ;
int p2 = Math.round(h2*scale2) + SequenceScalePanel.DEFAULT_X_START - scrollLeftX2 ;
Group g1 = null;
Group g2 = null;
//logger.info("seq1 length " + sequence1.getLength() + " " + h1);
if ( sequence1.getLength() > h1)
g1 = sequence1.getGroup(h1);
//logger.info("seq2 length " + sequence2.getLength() + " " + h2);
if ( sequence2.getLength() > h2)
g2 = sequence2.getGroup(h2);
if ( ((g1 != null) && (g2 != null))
&&
( g1.getPDBName().equals(g2.getPDBName()))) {
if (h1 % 2 == 0)
g2D.setColor(COLOR_MATCH_ONE);
else
g2D.setColor(COLOR_MATCH_TWO);
} else {
//if (g1 != null && g2 != null)
// System.out.println(h1 + " " + g1 + " "+ h2 + " " + g2);
if (h1 % 2 == 0)
g2D.setColor(COLOR_MISMATCH_ONE);
else
g2D.setColor(COLOR_MISMATCH_TWO);
}
GeneralPath path = new GeneralPath();
path.moveTo(p1,0);
path.lineTo(p2,h);
path.lineTo(p2+aminosize2+1,h);
path.lineTo(p1+aminosize1+1,0);
path.lineTo(p1,0);
g2D.fill(path);
}
g2D.setComposite(oldComp);
}
}
|
package org.jobimtext.example.demo;
import java.io.IOException;
import java.util.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.uima.jcas.tcas.Annotation;
import org.jobimtext.api.map.IThesaurusMap;
import org.jobimtext.example.demo.JoBimDemo.AnnoLabel;
import org.jobimtext.holing.extractor.JobimAnnotationExtractor;
import com.ibm.bluej.util.common.*;
import com.ibm.bluej.util.common.visualization.*;
import edu.antonym.MarketMatrixTensor;
import edu.antonym.RawPILSAVec;
import edu.antonym.prototype.VectorEmbedding;
import edu.antonym.prototype.Vocabulary;
public class SensesRankingViewManager implements TreeSelectionListener {
private BasicJTree jobimView;
private BasicJTree view;
private IThesaurusMap<String, String> dt;
private JobimAnnotationExtractor extractor;
public MarketMatrixTensor embeddingTensor;
public VectorEmbedding embeddingPILSA;
public Vocabulary voc;
public HashMap<String,Double> map = new HashMap<String,Double>();
public SensesRankingViewManager(
BasicJTree jobimView,
BasicJTree view,
IThesaurusMap<String, String> dt,
JobimAnnotationExtractor extractor) throws IOException {
this.jobimView = jobimView;
this.view = view;
this.dt = dt;
this.extractor = extractor;
embeddingTensor = new MarketMatrixTensor(17);
embeddingPILSA = new RawPILSAVec(false);
}
public void valueChanged(TreeSelectionEvent event) {
/*if (dt.getSenses() == null || dt.getPriors() == null) {
view.top.removeAllChildren();
view.refresh(null);
return;
}*/
// remove highlights from sentence
DefaultMutableTreeNode node = (DefaultMutableTreeNode) jobimView
.getLastSelectedPathComponent();
// if nothing is selected
if (node == null) {
view.top.removeAllChildren();
view.refresh(null);
return;
}
try {
if (node.getUserObject() instanceof AnnoLabel) {
Annotation jo = ((AnnoLabel) node.getUserObject()).anno;
view.top.removeAllChildren();
view.top.setUserObject(extractor.extract(jo));
int count = 0;
String joString = extractor.extract(jo);
Map<Integer, List<String>> senses = dt.getSenses(joString);
Map<String,Double> priors = dt.getSimilarTerms(joString,JoBimDemo.MAX_EXPANSIONS);
Map<Integer, Double> senseScores = new HashMap<Integer,Double>();
for (Map.Entry<Integer, List<String>> e : senses.entrySet()) {
if (e.getValue().isEmpty())
continue;
double sumScore = 0;
for (String s : e.getValue()) {
sumScore += Lang.NVL(priors.get(s), 0.0);
}
senseScores.put(e.getKey(), sumScore/e.getValue().size());
}
ArrayList<Pair<Integer,Double>> senseScoresSorted = HashMapUtil.toPairs(senseScores);
SecondPairComparator.sortR(senseScoresSorted);
for (Pair<Integer,Double> sense : senseScoresSorted) {
int key = sense.first;
List<String> l = senses.get(key);
DefaultMutableTreeNode senseNode = BasicJTree
.makeGrouping("Sense "+count++);
view.top.add(senseNode);
for (String s : l) {
DefaultMutableTreeNode vectorNode1 = BasicJTree.makeGrouping("BPTF");
ArrayList<String> ss = processWordsense(joString,s,1);
//DefaultMutableTreeNode expNode1 = new DefaultMutableTreeNode(ss);
int size = ss.size();
if(size<=20){
for(int i=0;i<size;i++){
vectorNode1.add(new DefaultMutableTreeNode(ss.get(i)));
}
}
else{
for(int i=0;i<10;i++){
vectorNode1.add(new DefaultMutableTreeNode(ss.get(i)));
}
vectorNode1.add(new DefaultMutableTreeNode("..."));
for(int i=size-10;i<size;i++){
vectorNode1.add(new DefaultMutableTreeNode(ss.get(i)));
}
}
//vectorNode1.add(expNode1);
senseNode.add(vectorNode1);
DefaultMutableTreeNode vectorNode2 = BasicJTree.makeGrouping("PILSA");
ArrayList<String> sss = processWordsense(joString,s,2);
size = sss.size();
if(size<=20){
for(int i=0;i<size;i++){
vectorNode2.add(new DefaultMutableTreeNode(sss.get(i)));
}
}
else{
for(int i=0;i<10;i++){
vectorNode2.add(new DefaultMutableTreeNode(sss.get(i)));
}
vectorNode2.add(new DefaultMutableTreeNode("..."));
for(int i=size-10;i<size;i++){
vectorNode2.add(new DefaultMutableTreeNode(sss.get(i)));
}
}
//DefaultMutableTreeNode expNode2 = new DefaultMutableTreeNode(sss);
//vectorNode2.add(expNode2);
senseNode.add(vectorNode2);
//System.out.println("senseNode print: " + expNode);
}
}
view.refresh(new FunST<DefaultMutableTreeNode, Boolean>() {
public Boolean f(DefaultMutableTreeNode n) {
return n.getLevel() < 2;
}
});
}
} catch (UnsupportedOperationException e) {
view.top.removeAllChildren();
view.top.setUserObject("Not supported");
view.refresh(null);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public String plainword(String s){
int index = s.indexOf("
return s.substring(0,index);
}
public ArrayList<String> processWordsense(String target,String s, int choice) throws IOException{
if(choice==1){
voc = embeddingTensor.getVocab();
}
else if(choice==2){
voc = embeddingPILSA.getVocab();
}
else{
System.out.println("did not find corresponding embedding");
System.exit(0);
}
String[] words = s.split(", ");
String ss = null;
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> rank = new ArrayList<String>();
int t = voc.lookupWord(plainword(target));
int OOV = voc.OOVindex();
if(t!=OOV){
for(int i=0;i<words.length;i++){
int index = voc.lookupWord(plainword(words[i]));
if(index!=OOV){
if(choice==1){
double sim = embeddingTensor.similarity(t, index);
if (embeddingTensor.getSecondVocab().lookupWord(plainword(words[i])) != OOV)
sim /= 2;
map.put(words[i], sim);
}
else if(choice==2){
double sim = embeddingPILSA.similarity(t, index);
map.put(words[i], sim);
}
result.add(words[i]);
}
else{
//System.out.println("cannot find: "+ words[i]);
}
}
Collections.sort(result,new EntityComparator());
StringBuilder sb = new StringBuilder();
for(int j=0;j<result.size();j++){
//double value = Math.floor(map.get(result.get(j)) * 100000) / 100000;
//sb.append(result.get(j)+":"+value+ " ");
double dscore = map.get(result.get(j));
String score = String.format("%.2f", dscore);
if (dscore >= 0) score = " " + score;
rank.add(score + ": " + result.get(j));
}
}
map.clear();
return rank;
}
public class EntityComparator implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
return NumberUtils.compare(map.get(o2), map.get(o1));
}
}
}
|
package org.securegraph.test;
import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.securegraph.*;
import org.securegraph.mutation.ElementMutation;
import org.securegraph.property.PropertyValue;
import org.securegraph.property.StreamingPropertyValue;
import org.securegraph.query.*;
import org.securegraph.test.util.LargeStringInputStream;
import org.securegraph.type.GeoCircle;
import org.securegraph.type.GeoPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import static org.junit.Assert.*;
import static org.securegraph.test.util.IterableUtils.assertContains;
import static org.securegraph.util.IterableUtils.count;
import static org.securegraph.util.IterableUtils.toList;
@RunWith(JUnit4.class)
public abstract class GraphTestBase {
private static final Logger LOGGER = LoggerFactory.getLogger(GraphTestBase.class);
public static final Visibility VISIBILITY_A = new Visibility("a");
public static final Visibility VISIBILITY_B = new Visibility("b");
public static final Visibility VISIBILITY_EMPTY = new Visibility("");
public final Authorizations AUTHORIZATIONS_A;
public final Authorizations AUTHORIZATIONS_B;
public final Authorizations AUTHORIZATIONS_C;
public final Authorizations AUTHORIZATIONS_A_AND_B;
public final Authorizations AUTHORIZATIONS_EMPTY;
public static final int LARGE_PROPERTY_VALUE_SIZE = 1024 + 1;
protected Graph graph;
protected abstract Graph createGraph() throws Exception;
public Graph getGraph() {
return graph;
}
public GraphTestBase() {
AUTHORIZATIONS_A = createAuthorizations("a");
AUTHORIZATIONS_B = createAuthorizations("b");
AUTHORIZATIONS_C = createAuthorizations("c");
AUTHORIZATIONS_A_AND_B = createAuthorizations("a", "b");
AUTHORIZATIONS_EMPTY = createAuthorizations();
}
protected abstract Authorizations createAuthorizations(String... auths);
@Before
public void before() throws Exception {
graph = createGraph();
}
@After
public void after() throws Exception {
graph.shutdown();
graph = null;
}
@Test
public void testAddVertexWithId() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(v);
assertEquals("v1", v.getId());
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull(v);
assertEquals("v1", v.getId());
assertEquals(VISIBILITY_A, v.getVisibility());
v = graph.getVertex("", AUTHORIZATIONS_A);
assertNull(v);
v = graph.getVertex(null, AUTHORIZATIONS_A);
assertNull(v);
}
@Test
public void testAddVertexWithoutId() {
Vertex v = graph.addVertex(VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(v);
Object vertexId = v.getId();
assertNotNull(vertexId);
v = graph.getVertex(vertexId, AUTHORIZATIONS_A);
assertNotNull(v);
assertNotNull(vertexId);
}
@Test
public void testAddStreamingPropertyValue() throws IOException, InterruptedException {
String expectedLargeValue = IOUtils.toString(new LargeStringInputStream(LARGE_PROPERTY_VALUE_SIZE));
PropertyValue propSmall = new StreamingPropertyValue(new ByteArrayInputStream("value1".getBytes()), String.class);
PropertyValue propLarge = new StreamingPropertyValue(new ByteArrayInputStream(expectedLargeValue.getBytes()), String.class);
String largePropertyName = "propLarge/\\*!@
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("propSmall", propSmall, VISIBILITY_A)
.setProperty(largePropertyName, propLarge, VISIBILITY_A)
.save();
Iterable<Object> propSmallValues = v1.getPropertyValues("propSmall");
assertEquals(1, count(propSmallValues));
Object propSmallValue = propSmallValues.iterator().next();
assertTrue("propSmallValue was " + propSmallValue.getClass().getName(), propSmallValue instanceof StreamingPropertyValue);
StreamingPropertyValue value = (StreamingPropertyValue) propSmallValue;
assertEquals(String.class, value.getValueType());
assertEquals("value1".getBytes().length, value.getLength());
assertEquals("value1", IOUtils.toString(value.getInputStream()));
assertEquals("value1", IOUtils.toString(value.getInputStream()));
Iterable<Object> propLargeValues = v1.getPropertyValues(largePropertyName);
assertEquals(1, count(propLargeValues));
Object propLargeValue = propLargeValues.iterator().next();
assertTrue(largePropertyName + " was " + propLargeValue.getClass().getName(), propLargeValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propLargeValue;
assertEquals(String.class, value.getValueType());
assertEquals(expectedLargeValue.getBytes().length, value.getLength());
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
propSmallValues = v1.getPropertyValues("propSmall");
assertEquals(1, count(propSmallValues));
propSmallValue = propSmallValues.iterator().next();
assertTrue("propSmallValue was " + propSmallValue.getClass().getName(), propSmallValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propSmallValue;
assertEquals(String.class, value.getValueType());
assertEquals("value1".getBytes().length, value.getLength());
assertEquals("value1", IOUtils.toString(value.getInputStream()));
assertEquals("value1", IOUtils.toString(value.getInputStream()));
propLargeValues = v1.getPropertyValues(largePropertyName);
assertEquals(1, count(propLargeValues));
propLargeValue = propLargeValues.iterator().next();
assertTrue(largePropertyName + " was " + propLargeValue.getClass().getName(), propLargeValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propLargeValue;
assertEquals(String.class, value.getValueType());
assertEquals(expectedLargeValue.getBytes().length, value.getLength());
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
}
@Test
public void testAddVertexPropertyWithMetadata() {
Map<String, Object> prop1Metadata = new HashMap<String, Object>();
prop1Metadata.put("metadata1", "metadata1Value");
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save();
Vertex v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
Property prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertNotNull(prop1Metadata);
assertEquals(1, prop1Metadata.keySet().size());
assertEquals("metadata1Value", prop1Metadata.get("metadata1"));
prop1Metadata.put("metadata2", "metadata2Value");
v.prepareMutation()
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertEquals(2, prop1Metadata.keySet().size());
assertEquals("metadata1Value", prop1Metadata.get("metadata1"));
assertEquals("metadata2Value", prop1Metadata.get("metadata2"));
// make sure we clear out old values
prop1Metadata = new HashMap<String, Object>();
v.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A);
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertEquals(0, prop1Metadata.keySet().size());
}
@Test
public void testAddVertexWithProperties() {
Vertex v = graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_B)
.save();
assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1", v.getPropertyValues("prop1").iterator().next());
assertEquals(1, count(v.getProperties("prop2")));
assertEquals("value2", v.getPropertyValues("prop2").iterator().next());
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1", v.getPropertyValues("prop1").iterator().next());
assertEquals(1, count(v.getProperties("prop2")));
assertEquals("value2", v.getPropertyValues("prop2").iterator().next());
}
@Test
public void testAddVertexWithPropertiesWithTwoDifferentVisibilities() {
Vertex v = graph.prepareVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B)
.setProperty("prop1", "value1a", VISIBILITY_A)
.setProperty("prop1", "value1b", VISIBILITY_B)
.save();
assertEquals(2, count(v.getProperties("prop1")));
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(v.getProperties("prop1")));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1a", v.getPropertyValue("prop1"));
v = graph.getVertex("v1", AUTHORIZATIONS_B);
assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1b", v.getPropertyValue("prop1"));
}
@Test
public void testMultivaluedProperties() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.addPropertyValue("propid3a", "prop3", "value3a", VISIBILITY_A)
.save();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("value1a", v.getPropertyValues("prop1").iterator().next());
assertEquals("value2a", v.getPropertyValues("prop2").iterator().next());
assertEquals("value3a", v.getPropertyValues("prop3").iterator().next());
assertEquals(3, count(v.getProperties()));
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2b", VISIBILITY_A)
.save();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getPropertyValues("prop1")));
assertEquals("value1b", v.getPropertyValues("prop1").iterator().next());
assertEquals(1, count(v.getPropertyValues("prop2")));
assertEquals("value2b", v.getPropertyValues("prop2").iterator().next());
assertEquals(1, count(v.getPropertyValues("prop3")));
assertEquals("value3a", v.getPropertyValues("prop3").iterator().next());
assertEquals(3, count(v.getProperties()));
v.addPropertyValue("propid1b", "prop1", "value1a-new", VISIBILITY_A);
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertContains("value1b", v.getPropertyValues("prop1"));
assertContains("value1a-new", v.getPropertyValues("prop1"));
assertEquals(4, count(v.getProperties()));
}
@Test
public void testMultivaluedPropertyOrder() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.addPropertyValue("a", "prop", "a", VISIBILITY_A)
.addPropertyValue("aa", "prop", "aa", VISIBILITY_A)
.addPropertyValue("b", "prop", "b", VISIBILITY_A)
.addPropertyValue("0", "prop", "0", VISIBILITY_A)
.addPropertyValue("A", "prop", "A", VISIBILITY_A)
.addPropertyValue("Z", "prop", "Z", VISIBILITY_A)
.save();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("0", v1.getPropertyValue("prop", 0));
assertEquals("A", v1.getPropertyValue("prop", 1));
assertEquals("Z", v1.getPropertyValue("prop", 2));
assertEquals("a", v1.getPropertyValue("prop", 3));
assertEquals("aa", v1.getPropertyValue("prop", 4));
assertEquals("b", v1.getPropertyValue("prop", 5));
}
@Test
public void testRemoveProperty() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid1b", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.save();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
v.removeProperty("prop1");
assertEquals(1, count(v.getProperties()));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v.getProperties()));
v.removeProperty("propid2a", "prop2");
assertEquals(0, count(v.getProperties()));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v.getProperties()));
}
@Test
public void testAddVertexWithVisibility() {
graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_A);
Iterable<Vertex> cVertices = graph.getVertices(AUTHORIZATIONS_C);
assertEquals(0, count(cVertices));
Iterable<Vertex> aVertices = graph.getVertices(AUTHORIZATIONS_A);
assertEquals(1, count(aVertices));
assertEquals("v1", aVertices.iterator().next().getId());
Iterable<Vertex> bVertices = graph.getVertices(AUTHORIZATIONS_B);
assertEquals(1, count(bVertices));
assertEquals("v2", bVertices.iterator().next().getId());
Iterable<Vertex> allVertices = graph.getVertices(AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(allVertices));
}
@Test
public void testGetVerticesWithIds() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "v1", VISIBILITY_A)
.save();
graph.prepareVertex("v1b", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "v1b", VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "v2", VISIBILITY_A)
.save();
graph.prepareVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "v3", VISIBILITY_A)
.save();
List<Object> ids = new ArrayList<Object>();
ids.add("v2");
ids.add("v1");
Iterable<Vertex> vertices = graph.getVertices(ids, AUTHORIZATIONS_A);
boolean foundV1 = false, foundV2 = false;
for (Vertex v : vertices) {
if (v.getId().equals("v1")) {
assertEquals("v1", v.getPropertyValue("prop1"));
foundV1 = true;
} else if (v.getId().equals("v2")) {
assertEquals("v2", v.getPropertyValue("prop1"));
foundV2 = true;
} else {
assertTrue("Unexpected vertex id: " + v.getId(), false);
}
}
assertTrue("v1 not found", foundV1);
assertTrue("v2 not found", foundV2);
List<Vertex> verticesInOrder = graph.getVerticesInOrder(ids, AUTHORIZATIONS_A);
assertEquals(2, verticesInOrder.size());
assertEquals("v2", verticesInOrder.get(0).getId());
assertEquals("v1", verticesInOrder.get(1).getId());
}
@Test
public void testGetEdgesWithIds() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "e1", VISIBILITY_A)
.save();
graph.prepareEdge("e1a", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "e1a", VISIBILITY_A)
.save();
graph.prepareEdge("e2", v1, v3, "", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "e2", VISIBILITY_A)
.save();
graph.prepareEdge("e3", v2, v3, "", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "e3", VISIBILITY_A)
.save();
List<Object> ids = new ArrayList<Object>();
ids.add("e1");
ids.add("e2");
Iterable<Edge> edges = graph.getEdges(ids, AUTHORIZATIONS_A);
boolean foundE1 = false, foundE2 = false;
for (Edge e : edges) {
if (e.getId().equals("e1")) {
assertEquals("e1", e.getPropertyValue("prop1"));
foundE1 = true;
} else if (e.getId().equals("e2")) {
assertEquals("e2", e.getPropertyValue("prop1"));
foundE2 = true;
} else {
assertTrue("Unexpected vertex id: " + e.getId(), false);
}
}
assertTrue("e1 not found", foundE1);
assertTrue("e2 not found", foundE2);
}
@Test
public void testRemoveVertex() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
graph.removeVertex(v1, AUTHORIZATIONS_A);
assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_A)));
}
@Test
public void testRemoveVertexWithProperties() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "value1", VISIBILITY_B)
.save();
assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
graph.removeVertex(v1, AUTHORIZATIONS_A);
assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
}
@Test
public void testAddEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge e = graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(e);
assertEquals("e1", e.getId());
assertEquals("label1", e.getLabel());
assertEquals("v1", e.getVertexId(Direction.OUT));
assertEquals(v1, e.getVertex(Direction.OUT, AUTHORIZATIONS_A));
assertEquals("v2", e.getVertexId(Direction.IN));
assertEquals(v2, e.getVertex(Direction.IN, AUTHORIZATIONS_A));
assertEquals(VISIBILITY_A, e.getVisibility());
e = graph.getEdge("e1", AUTHORIZATIONS_B);
assertNull(e);
e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertNotNull(e);
assertEquals("e1", e.getId());
assertEquals("label1", e.getLabel());
assertEquals("v1", e.getVertexId(Direction.OUT));
assertEquals(v1, e.getVertex(Direction.OUT, AUTHORIZATIONS_A));
assertEquals("v2", e.getVertexId(Direction.IN));
assertEquals(v2, e.getVertex(Direction.IN, AUTHORIZATIONS_A));
assertEquals(VISIBILITY_A, e.getVisibility());
}
@Test
public void testGetEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1to2label1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1to2label2", v1, v2, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2to1", v2, v1, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(3, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(Direction.IN, AUTHORIZATIONS_A)));
assertEquals(3, count(v1.getEdges(v2, Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(v2, Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.IN, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(v2, Direction.BOTH, "label1", AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.OUT, "label1", AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.IN, "label1", AUTHORIZATIONS_A)));
assertEquals(3, count(v1.getEdges(v2, Direction.BOTH, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
assertEquals(2, count(v1.getEdges(v2, Direction.OUT, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
assertEquals(1, count(v1.getEdges(v2, Direction.IN, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
}
@Test
public void testAddEdgeWithProperties() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("propA", "valueA", VISIBILITY_A)
.setProperty("propB", "valueB", VISIBILITY_B)
.save();
Edge e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
assertEquals(0, count(e.getPropertyValues("propB")));
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
assertEquals("valueB", e.getPropertyValues("propB").iterator().next());
assertEquals("valueA", e.getPropertyValue("propA"));
assertEquals("valueB", e.getPropertyValue("propB"));
}
@Test
public void testRemoveEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
try {
graph.removeEdge("e1", AUTHORIZATIONS_B);
} catch (IllegalArgumentException e) {
// expected
}
assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.removeEdge("e1", AUTHORIZATIONS_A);
assertEquals(0, count(graph.getEdges(AUTHORIZATIONS_A)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v1.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
assertEquals(0, count(v2.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
}
@Test
public void testAddEdgeWithVisibility() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2", v1, v2, "edgeB", VISIBILITY_B, AUTHORIZATIONS_B);
Iterable<Edge> aEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A);
assertEquals(1, count(aEdges));
Edge e1 = aEdges.iterator().next();
assertNotNull(e1);
assertEquals("edgeA", e1.getLabel());
Iterable<Edge> bEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_B);
assertEquals(1, count(bEdges));
Edge e2 = bEdges.iterator().next();
assertNotNull(e2);
assertEquals("edgeB", e2.getLabel());
Iterable<Edge> allEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B);
assertEquals(2, count(allEdges));
}
@Test
public void testGraphQuery() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A).vertices();
assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(1).vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).limit(1).vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(1).limit(1).vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(2).vertices();
assertEquals(0, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A).skip(1).limit(2).vertices();
assertEquals(1, count(vertices));
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A).edges();
assertEquals(1, count(edges));
}
@Test
public void testGraphQueryWithQueryString() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v1.setProperty("description", "This is vertex 1 - dog.", VISIBILITY_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
v2.setProperty("description", "This is vertex 2 - cat.", VISIBILITY_A);
Iterable<Vertex> vertices = graph.query("vertex", AUTHORIZATIONS_A).vertices();
assertEquals(2, count(vertices));
vertices = graph.query("dog", AUTHORIZATIONS_A).vertices();
assertEquals(1, count(vertices));
vertices = graph.query("dog", AUTHORIZATIONS_B).vertices();
assertEquals(0, count(vertices));
}
@Test
public void testFacetedResults() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("gender", "male", VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("gender", "male", VISIBILITY_A)
.save();
graph.prepareVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("gender", "female", VISIBILITY_A)
.save();
graph.prepareVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A)
.save();
graph.flush();
Query q = graph.query(AUTHORIZATIONS_A);
if (q instanceof QuerySupportingFacetedResults) {
((QuerySupportingFacetedResults) q).addFacet(new TermFacet("f1", "gender"));
Iterable<Vertex> results = q.vertices();
assertEquals(4, count(results));
assertTrue("results was not of type IterableWithFacetedResults: " + results.getClass().getName(), results instanceof IterableWithFacetedResults);
FacetedResult facetedResult = ((IterableWithFacetedResults) results).getFacetedResult("f1");
assertNotNull("facetedResults was null for name 'f1'", facetedResult);
assertEquals(2, count(facetedResult.getTerms()));
for (FacetedTerm facetedTerm : facetedResult.getTerms()) {
if (facetedTerm.getTerm().equals("male")) {
assertEquals(2, facetedTerm.getCount());
} else if (facetedTerm.getTerm().equals("female")) {
assertEquals(1, facetedTerm.getCount());
} else {
throw new RuntimeException("Unexpected FacetedTerm: " + facetedTerm.getTerm());
}
}
} else {
LOGGER.warn("query does not support faceted results: " + q.getClass().getName());
}
}
@Test
public void testGraphQueryHas() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 25, VISIBILITY_A)
.setProperty("birthDate", new DateOnly(1989, 1, 5), VISIBILITY_A)
.setProperty("lastAccessed", createDate(2014, 2, 24, 13, 0, 5), VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 30, VISIBILITY_A)
.setProperty("birthDate", new DateOnly(1984, 1, 5), VISIBILITY_A)
.setProperty("lastAccessed", createDate(2014, 2, 25, 13, 0, 5), VISIBILITY_A)
.save();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("birthDate", Compare.EQUAL, createDate(1989, 1, 5))
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("lastAccessed", Compare.EQUAL, createDate(2014, 2, 24, 13, 0, 5))
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN_EQUAL, 25)
.vertices();
assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.IN, new Integer[]{25})
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.IN, new Integer[]{25, 30})
.vertices();
assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.LESS_THAN, 26)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.LESS_THAN_EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.NOT_EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("lastAccessed", Compare.EQUAL, new DateOnly(2014, 2, 24))
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query("*", AUTHORIZATIONS_A)
.has("age", Compare.IN, new Integer[]{25, 30})
.vertices();
assertEquals(2, count(vertices));
}
@Test
public void testGraphQueryVertexHasWithSecurity() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 25, VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 25, VISIBILITY_B)
.save();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryEdgeHasWithSecurity() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A).save();
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A).save();
Vertex v3 = graph.prepareVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A).save();
graph.prepareEdge("e1", v1, v2, "edge", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 25, VISIBILITY_A)
.save();
graph.prepareEdge("e2", v1, v3, "edge", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 25, VISIBILITY_B)
.save();
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.edges();
assertEquals(1, count(edges));
}
@Test
public void testGraphQueryHasWithSpaces() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("name", "Joe Ferner", VISIBILITY_A)
.setProperty("propWithHyphen", "hyphen-word", VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("name", "Joe Smith", VISIBILITY_A)
.save();
Iterable<Vertex> vertices = graph.query("Ferner", AUTHORIZATIONS_A)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query("joe", AUTHORIZATIONS_A)
.vertices();
assertEquals(2, count(vertices));
if (!isUsingDefaultQuery(graph)) {
vertices = graph.query("joe AND ferner", AUTHORIZATIONS_A)
.vertices();
assertEquals(1, count(vertices));
}
if (!isUsingDefaultQuery(graph)) {
vertices = graph.query("joe smith", AUTHORIZATIONS_A)
.vertices();
List<Vertex> verticesList = toList(vertices);
assertEquals(2, verticesList.size());
assertEquals("v2", verticesList.get(0).getId());
assertEquals("v1", verticesList.get(1).getId());
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Ferner")
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Joe")
.has("name", TextPredicate.CONTAINS, "Ferner")
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Joe Ferner")
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("propWithHyphen", TextPredicate.CONTAINS, "hyphen-word")
.vertices();
assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryHasWithSpacesAndFieldedQueryString() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("name", "Joe Ferner", VISIBILITY_A)
.setProperty("propWithHyphen", "hyphen-word", VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("name", "Joe Smith", VISIBILITY_A)
.save();
if (!isUsingDefaultQuery(graph)) {
Iterable<Vertex> vertices = graph.query("name:\"joe ferner\"", AUTHORIZATIONS_A)
.vertices();
assertEquals(1, count(vertices));
}
}
protected boolean isUsingDefaultQuery(Graph graph) {
return graph.query(AUTHORIZATIONS_A) instanceof DefaultGraphQuery;
}
@Test
public void testGraphQueryGeoPoint() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("location", new GeoPoint(38.9186, -77.2297, "Reston, VA"), VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("location", new GeoPoint(38.9544, -77.3464, "Reston, VA"), VISIBILITY_A)
.save();
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.9186, -77.2297, 1))
.vertices());
assertEquals(1, count(vertices));
GeoPoint geoPoint = (GeoPoint) vertices.get(0).getPropertyValue("location");
assertEquals(38.9186, geoPoint.getLatitude(), 0.001);
assertEquals(-77.2297, geoPoint.getLongitude(), 0.001);
assertEquals("Reston, VA", geoPoint.getDescription());
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.9186, -77.2297, 25))
.vertices());
assertEquals(2, count(vertices));
}
private Date createDate(int year, int month, int day) {
return new GregorianCalendar(year, month, day).getTime();
}
private Date createDate(int year, int month, int day, int hour, int min, int sec) {
return new GregorianCalendar(year, month, day, hour, min, sec).getTime();
}
@Test
public void testGraphQueryRange() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 25, VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("age", 30, VISIBILITY_A)
.save();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, 25)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 20, 29)
.vertices();
assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, 30)
.vertices();
assertEquals(2, count(vertices));
}
@Test
public void testVertexQuery() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v1.setProperty("prop1", "value1", VISIBILITY_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
v2.setProperty("prop1", "value2", VISIBILITY_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
v3.setProperty("prop1", "value3", VISIBILITY_A);
Edge ev1v2 = graph.addEdge("e v1->v2", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v3 = graph.addEdge("e v1->v3", v1, v3, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Iterable<Vertex> vertices = v1.query(AUTHORIZATIONS_A).vertices();
assertEquals(2, count(vertices));
assertContains(v2, vertices);
assertContains(v3, vertices);
vertices = v1.query(AUTHORIZATIONS_A)
.has("prop1", "value2")
.vertices();
assertEquals(1, count(vertices));
assertContains(v2, vertices);
Iterable<Edge> edges = v1.query(AUTHORIZATIONS_A).edges();
assertEquals(2, count(edges));
assertContains(ev1v2, edges);
assertContains(ev1v3, edges);
edges = v1.query(AUTHORIZATIONS_A).edges(Direction.OUT);
assertEquals(2, count(edges));
assertContains(ev1v2, edges);
assertContains(ev1v3, edges);
}
@Test
public void testFindPaths() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v2
graph.addEdge(v2, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v4
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
List<Path> paths = toList(graph.findPaths(v1, v4, 2, AUTHORIZATIONS_A));
// v1 -> v2 -> v4
// v1 -> v3 -> v4
assertEquals(2, paths.size());
boolean found2 = false;
boolean found3 = false;
for (Path path : paths) {
assertEquals(3, path.length());
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v1.getId());
} else if (i == 1) {
if (v2.getId().equals(id)) {
found2 = true;
} else if (v3.getId().equals(id)) {
found3 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v4.getId());
}
i++;
}
}
assertTrue("v2 not found in path", found2);
assertTrue("v3 not found in path", found3);
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
paths = toList(graph.findPaths(v4, v1, 2, AUTHORIZATIONS_A));
// v4 -> v2 -> v1
// v4 -> v3 -> v1
assertEquals(2, paths.size());
found2 = false;
found3 = false;
for (Path path : paths) {
assertEquals(3, path.length());
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v4.getId());
} else if (i == 1) {
if (v2.getId().equals(id)) {
found2 = true;
} else if (v3.getId().equals(id)) {
found3 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v1.getId());
}
i++;
}
}
assertTrue("v2 not found in path", found2);
assertTrue("v3 not found in path", found3);
}
@Test
public void testFindPathsMultiplePaths() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v4
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v3
graph.addEdge(v4, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v4 -> v2
graph.addEdge(v2, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v5
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
v5 = graph.getVertex("v5", AUTHORIZATIONS_A);
List<Path> paths = toList(graph.findPaths(v1, v2, 2, AUTHORIZATIONS_A));
// v1 -> v4 -> v2
// v1 -> v3 -> v2
assertEquals(2, paths.size());
boolean found3 = false;
boolean found4 = false;
for (Path path : paths) {
assertEquals(3, path.length());
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v1.getId());
} else if (i == 1) {
if (v3.getId().equals(id)) {
found3 = true;
} else if (v4.getId().equals(id)) {
found4 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v2.getId());
}
i++;
}
}
assertTrue("v3 not found in path", found3);
assertTrue("v4 not found in path", found4);
paths = toList(graph.findPaths(v1, v2, 3, AUTHORIZATIONS_A));
// v1 -> v4 -> v2
// v1 -> v3 -> v2
// v1 -> v3 -> v4 -> v2
// v1 -> v4 -> v3 -> v2
assertEquals(4, paths.size());
found3 = false;
found4 = false;
for (Path path : paths) {
if (path.length() == 3) {
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v1.getId());
} else if (i == 1) {
if (v3.getId().equals(id)) {
found3 = true;
} else if (v4.getId().equals(id)) {
found4 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v2.getId());
}
i++;
}
} else if (path.length() == 4) {
} else {
fail("Invalid path length " + path.length());
}
}
assertTrue("v3 not found in path", found3);
assertTrue("v4 not found in path", found4);
paths = toList(graph.findPaths(v1, v5, 2, AUTHORIZATIONS_A));
assertEquals(0, paths.size());
paths = toList(graph.findPaths(v1, v5, 3, AUTHORIZATIONS_A));
// v1 -> v4 -> v2 -> v5
// v1 -> v3 -> v2 -> v5
assertEquals(2, paths.size());
found3 = false;
found4 = false;
for (Path path : paths) {
assertEquals(4, path.length());
int i = 0;
for (Object id : path) {
if (i == 0) {
assertEquals(id, v1.getId());
} else if (i == 1) {
if (v3.getId().equals(id)) {
found3 = true;
} else if (v4.getId().equals(id)) {
found4 = true;
} else {
fail("center of path is neither v2 or v3 but found " + id);
}
} else if (i == 2) {
assertEquals(id, v2.getId());
} else if (i == 3) {
assertEquals(id, v5.getId());
}
i++;
}
}
assertTrue("v3 not found in path", found3);
assertTrue("v4 not found in path", found4);
}
@Test
public void testGetVerticesFromVertex() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(3, count(v1.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(3, count(v1.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(0, count(v1.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
assertEquals(2, count(v2.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(1, count(v2.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v2.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v3 = graph.getVertex("v3", AUTHORIZATIONS_A);
assertEquals(2, count(v3.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(0, count(v3.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(2, count(v3.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
assertEquals(1, count(v4.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
assertEquals(0, count(v4.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
assertEquals(1, count(v4.getVertices(Direction.IN, AUTHORIZATIONS_A)));
}
@Test
public void testBlankVisibilityString() {
Vertex v = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
assertNotNull(v);
assertEquals("v1", v.getId());
v = graph.getVertex("v1", AUTHORIZATIONS_EMPTY);
assertNotNull(v);
assertEquals("v1", v.getId());
assertEquals(VISIBILITY_EMPTY, v.getVisibility());
}
@Test
public void testElementMutationDoesntChangeObjectUntilSave() {
Vertex v = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
v.setProperty("prop1", "value1", VISIBILITY_A);
ElementMutation<Vertex> m = v.prepareMutation()
.setProperty("prop1", "value2", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_A);
assertEquals(1, count(v.getProperties()));
assertEquals("value1", v.getPropertyValue("prop1"));
m.save();
assertEquals(2, count(v.getProperties()));
assertEquals("value2", v.getPropertyValue("prop1"));
assertEquals("value2", v.getPropertyValue("prop2"));
}
@Test
public void testFindRelatedEdges() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v2 = graph.addEdge("e v1->v2", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v3 = graph.addEdge("e v1->v3", v1, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev2v3 = graph.addEdge("e v2->v3", v2, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev3v1 = graph.addEdge("e v3->v1", v3, v1, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v4", v3, v4, "", VISIBILITY_A, AUTHORIZATIONS_A);
List<Object> vertexIds = new ArrayList<Object>();
vertexIds.add("v1");
vertexIds.add("v2");
vertexIds.add("v3");
Iterable<Object> edges = toList(graph.findRelatedEdges(vertexIds, AUTHORIZATIONS_A));
assertEquals(4, count(edges));
assertContains(ev1v2.getId(), edges);
assertContains(ev1v3.getId(), edges);
assertContains(ev2v3.getId(), edges);
assertContains(ev3v1.getId(), edges);
}
@Test
public void testEmptyPropertyMutation() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
v1.prepareMutation().save();
}
@Test
public void testTextIndex() throws Exception {
graph.defineProperty("none").dataType(String.class).textIndexHint(TextIndexHint.NONE).define();
graph.defineProperty("none").dataType(String.class).textIndexHint(TextIndexHint.NONE).define(); // try calling define twice
graph.defineProperty("both").dataType(String.class).textIndexHint(TextIndexHint.ALL).define();
graph.defineProperty("fullText").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.defineProperty("exactMatch").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("none", "Test Value", VISIBILITY_A)
.setProperty("both", "Test Value", VISIBILITY_A)
.setProperty("fullText", "Test Value", VISIBILITY_A)
.setProperty("exactMatch", "Test Value", VISIBILITY_A)
.save();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("Test Value", v1.getPropertyValue("none"));
assertEquals("Test Value", v1.getPropertyValue("both"));
assertEquals("Test Value", v1.getPropertyValue("fullText"));
assertEquals("Test Value", v1.getPropertyValue("exactMatch"));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", TextPredicate.CONTAINS, "Test").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("fullText", TextPredicate.CONTAINS, "Test").vertices()));
assertEquals("exact match shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", TextPredicate.CONTAINS, "Test").vertices()));
assertEquals("unindexed property shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("none", TextPredicate.CONTAINS, "Test").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", "Test Value").vertices()));
assertEquals("default has predicate is equals which shouldn't work for full text", 0, count(graph.query(AUTHORIZATIONS_A).has("fullText", "Test Value").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", "Test Value").vertices()));
assertEquals("default has predicate is equals which shouldn't work for unindexed", 0, count(graph.query(AUTHORIZATIONS_A).has("none", "Test Value").vertices()));
}
@Test
public void testFieldBoost() throws Exception {
if (!graph.isFieldBoostSupported()) {
LOGGER.warn("Boost not supported");
return;
}
graph.defineProperty("a")
.dataType(String.class)
.textIndexHint(TextIndexHint.ALL)
.boost(1)
.define();
graph.defineProperty("b")
.dataType(String.class)
.textIndexHint(TextIndexHint.ALL)
.boost(2)
.define();
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("a", "Test Value", VISIBILITY_A)
.save();
graph.prepareVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("b", "Test Value", VISIBILITY_A)
.save();
assertVertexIds(graph.query("Test", AUTHORIZATIONS_A).vertices(), new String[]{"v2", "v1"});
}
@Test
public void testValueTypes() throws Exception {
Date date = createDate(2014, 2, 24, 13, 0, 5);
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("int", 5, VISIBILITY_A)
.setProperty("bigDecimal", new BigDecimal(10), VISIBILITY_A)
.setProperty("double", 5.6, VISIBILITY_A)
.setProperty("float", 6.4f, VISIBILITY_A)
.setProperty("string", "test", VISIBILITY_A)
.setProperty("byte", (byte) 5, VISIBILITY_A)
.setProperty("long", (long) 5, VISIBILITY_A)
.setProperty("boolean", true, VISIBILITY_A)
.setProperty("geopoint", new GeoPoint(77, -33), VISIBILITY_A)
.setProperty("short", (short) 5, VISIBILITY_A)
.setProperty("date", date, VISIBILITY_A)
.save();
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("int", 5).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("double", 5.6).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("float", 6.4f).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("string", "test").vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("byte", 5).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("long", 5).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("boolean", true).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("short", 5).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("date", date).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("bigDecimal", 10).vertices()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("geopoint", GeoCompare.WITHIN, new GeoCircle(77, -33, 1)).vertices()));
}
@Test
public void testChangeVisibilityVertex() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.save();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1);
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertNotNull(v1);
// change to same visibility
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
v1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1);
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertNotNull(v1);
}
@Test
public void testChangeVisibilityVertexProperties() {
Map<String, Object> prop1Metadata = new HashMap<String, Object>();
prop1Metadata.put("prop1_key1", "value1");
Map<String, Object> prop2Metadata = new HashMap<String, Object>();
prop2Metadata.put("prop2_key1", "value1");
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_EMPTY)
.setProperty("prop2", "value2", prop2Metadata, VISIBILITY_EMPTY)
.save();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_B)
.save();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1.getProperty("prop1"));
assertNotNull(v1.getProperty("prop2"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertNotNull(v1.getProperty("prop2"));
// alter and set property in one mutation
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_A)
.setProperty("prop1", "value1New", VISIBILITY_A)
.save();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertEquals("value1New", v1.getPropertyValue("prop1"));
// alter visibility to the same visibility
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_A)
.setProperty("prop1", "value1New2", VISIBILITY_A)
.save();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertEquals("value1New2", v1.getPropertyValue("prop1"));
}
@Test
public void testChangeVisibilityEdge() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_A)
.save();
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_EMPTY, AUTHORIZATIONS_A)
.save();
graph.prepareEdge("e1", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A)
.save();
// test that we can see the edge with A and not B
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
// change the edge
Edge e1 = graph.getEdge("e1", AUTHORIZATIONS_A);
e1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save();
// test that we can see the edge with B and not A
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
// change the edge visibility to same
e1 = graph.getEdge("e1", AUTHORIZATIONS_B);
e1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save();
// test that we can see the edge with B and not A
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
}
@Test
public void testChangeVisibilityOnBadPropertyName() {
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "value1", VISIBILITY_EMPTY)
.setProperty("prop2", "value2", VISIBILITY_B)
.save();
try {
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility("propBad", VISIBILITY_B)
.save();
fail("show throw");
} catch (SecureGraphException ex) {
assertNotNull(ex);
}
}
@Test
public void testChangeVisibilityOnStreamingProperty() throws IOException {
String expectedLargeValue = IOUtils.toString(new LargeStringInputStream(LARGE_PROPERTY_VALUE_SIZE));
PropertyValue propSmall = new StreamingPropertyValue(new ByteArrayInputStream("value1".getBytes()), String.class);
PropertyValue propLarge = new StreamingPropertyValue(new ByteArrayInputStream(expectedLargeValue.getBytes()), String.class);
String largePropertyName = "propLarge/\\*!@
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("propSmall", propSmall, VISIBILITY_A)
.setProperty(largePropertyName, propLarge, VISIBILITY_A)
.save();
assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility("propSmall", VISIBILITY_B)
.save();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility(largePropertyName, VISIBILITY_B)
.save();
assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties()));
}
@Test
public void testChangePropertyMetadata() {
Map<String, Object> prop1Metadata = new HashMap<String, Object>();
prop1Metadata.put("prop1_key1", "valueOld");
graph.prepareVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_EMPTY)
.setProperty("prop2", "value2", null, VISIBILITY_EMPTY)
.save();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.alterPropertyMetadata("prop1", "prop1_key1", "valueNew")
.save();
assertEquals("valueNew", v1.getProperty("prop1").getMetadata().get("prop1_key1"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("valueNew", v1.getProperty("prop1").getMetadata().get("prop1_key1"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.alterPropertyMetadata("prop2", "prop2_key1", "valueNew")
.save();
assertEquals("valueNew", v1.getProperty("prop2").getMetadata().get("prop2_key1"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("valueNew", v1.getProperty("prop2").getMetadata().get("prop2_key1"));
}
@Test
public void testIsVisibilityValid() {
assertFalse(graph.isVisibilityValid(VISIBILITY_A, AUTHORIZATIONS_C));
assertTrue(graph.isVisibilityValid(VISIBILITY_B, AUTHORIZATIONS_A_AND_B));
assertTrue(graph.isVisibilityValid(VISIBILITY_B, AUTHORIZATIONS_B));
assertTrue(graph.isVisibilityValid(VISIBILITY_EMPTY, AUTHORIZATIONS_A));
}
protected void assertVertexIds(Iterable<Vertex> vertices, String[] ids) {
List<Vertex> verticesList = toList(vertices);
assertEquals(ids.length, verticesList.size());
for (int i = 0; i < ids.length; i++) {
assertEquals("at offset: " + i, ids[i], verticesList.get(i).getId());
}
}
}
|
package org.opencms.ade.configuration;
import org.opencms.ade.detailpage.CmsDetailPageInfo;
import org.opencms.db.CmsPublishedResource;
import org.opencms.db.CmsResourceState;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.CmsRuntimeException;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
/**
* This is the internal cache class used for storing configuration data. It is not public because it is only meant
* for internal use.<p>
*
* It stores an instance of {@link CmsADEConfigData} for each active configuration file in the sitemap,
* and a single instance which represents the merged configuration from all the modules. When a sitemap configuration
* file is updated, only the single instance for that configuration file is updated, whereas if a module configuration file
* is changed, the configuration of all modules will be read again.<p>
*/
class CmsConfigurationCache {
/** The log instance for this class. */
private static final Log LOG = CmsLog.getLog(CmsConfigurationCache.class);
/** The key that is used for the map entry which indicates that the module configuration needs to be read. */
private static final String MODULE_CONFIG_KEY = "__MODULE_CONFIG_KEY__";
/** The resource type for sitemap configurations. */
protected I_CmsResourceType m_configType;
/** The resource type for module configurations. */
protected I_CmsResourceType m_moduleConfigType;
/** The CMS context used for reading configuration data. */
private CmsObject m_cms;
/** The cached content types for folders. */
private Map<String, String> m_folderTypes = new HashMap<String, String>();
/** The merged configuration from all the modules. */
private CmsADEConfigData m_moduleConfiguration;
/** A cache which stores resources' paths by their structure IDs. */
private Map<CmsUUID, String> m_pathCache = Collections.synchronizedMap(new HashMap<CmsUUID, String>());
/** The configurations from the sitemap / VFS. */
private Map<String, CmsADEConfigData> m_siteConfigurations = new HashMap<String, CmsADEConfigData>();
/** The configuration files which have been changed but not read yet. */
private Map<String, CmsUUID> m_configurationsToRead = new HashMap<String, CmsUUID>();
/**
* Creates a new cache instance.<p>
*
* @param cms the CMS object used for reading the configuration data
* @param configType the sitemap configuration file type
* @param moduleConfigType the module configuration file type
*/
public CmsConfigurationCache(CmsObject cms, I_CmsResourceType configType, I_CmsResourceType moduleConfigType) {
m_cms = cms;
m_configType = configType;
m_moduleConfigType = moduleConfigType;
}
/**
* Looks up the root path for a given structure id.<p>
*
* This is used for correcting the paths of cached resource objects.<p>
*
* @param structureId the structure id
* @return the root path for the structure id
*
* @throws CmsException if the resource with the given id was not found or another error occurred
*/
public String getPathForStructureId(CmsUUID structureId) throws CmsException {
String rootPath = m_pathCache.get(structureId);
if (rootPath != null) {
return rootPath;
}
CmsResource res = m_cms.readResource(structureId);
m_pathCache.put(structureId, res.getRootPath());
return res.getRootPath();
}
/**
* Gets the base path for a given sitemap configuration file.<p>
*
* @param siteConfigFile the root path of the sitemap configuration file
*
* @return the base path for the sitemap configuration file
*/
protected String getBasePath(String siteConfigFile) {
if (siteConfigFile.endsWith(CmsADEManager.CONFIG_SUFFIX)) {
return CmsResource.getParentFolder(CmsResource.getParentFolder(siteConfigFile));
}
return siteConfigFile;
}
/**
* Gets all the detail pages for a given type.<p>
*
* @param type the name of the type
*
* @return the detail pages for that type
*/
protected synchronized List<String> getDetailPages(String type) {
readRemainingConfigurations();
List<String> result = new ArrayList<String>();
for (CmsADEConfigData configData : m_siteConfigurations.values()) {
for (CmsDetailPageInfo pageInfo : configData.getDetailPagesForType(type)) {
result.add(pageInfo.getUri());
}
}
return result;
}
/**
* Gets the merged module configuration.<p>
* @return the merged module configuration instance
*/
protected synchronized CmsADEConfigData getModuleConfiguration() {
return m_moduleConfiguration;
}
/**
* Helper method to retrieve the parent folder type.<p>
*
* @param rootPath the path of a resource
* @return the parent folder content type
*/
protected synchronized String getParentFolderType(String rootPath) {
readRemainingConfigurations();
String parent = CmsResource.getParentFolder(rootPath);
if (parent == null) {
return null;
}
String type = m_folderTypes.get(parent);
if (type == null) {
return null;
}
return type;
}
/**
* Helper method for getting the best matching sitemap configuration object for a given root path, ignoring the module
* configuration.<p>
*
* For example, if there are configurations available for the paths /a, /a/b/c, /a/b/x and /a/b/c/d/e, then
* the method will return the configuration object for /a/b/c when passed the path /a/b/c/d.
*
* If no configuration data is found for the path, null will be returned.<p>
*
* @param path a root path
* @return the configuration data for the given path, or null if none was found
*/
protected synchronized CmsADEConfigData getSiteConfigData(String path) {
if (path == null) {
return null;
}
readRemainingConfigurations();
String normalizedPath = CmsStringUtil.joinPaths("/", path, "/");
List<String> prefixes = new ArrayList<String>();
for (String key : m_siteConfigurations.keySet()) {
if (normalizedPath.startsWith(CmsStringUtil.joinPaths("/", key, "/"))) {
prefixes.add(key);
}
}
if (prefixes.size() == 0) {
return null;
}
Collections.sort(prefixes);
// for any two prefixes of a string, one is a prefix of the other. so the alphabetically last
// prefix is the longest prefix of all.
return m_siteConfigurations.get(prefixes.get(prefixes.size() - 1));
}
/**
* Initializes the cache by reading in all the configuration files.<p>
*/
protected synchronized void initialize() {
m_siteConfigurations.clear();
try {
List<CmsResource> configFileCandidates = m_cms.readResources(
"/",
CmsResourceFilter.DEFAULT.addRequireType(m_configType.getTypeId()));
for (CmsResource candidate : configFileCandidates) {
if (isSitemapConfiguration(candidate.getRootPath(), candidate.getTypeId())) {
update(candidate);
}
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
refreshModuleConfiguration();
try {
initializeFolderTypes();
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
/**
* Initializes the cached folder types.<p>
*
* @throws CmsException if something goes wrong
*/
protected synchronized void initializeFolderTypes() throws CmsException {
LOG.info("Computing folder types for detail pages...");
m_folderTypes.clear();
for (CmsADEConfigData configData : m_siteConfigurations.values()) {
Map<String, String> folderTypes = configData.getFolderTypes();
m_folderTypes.putAll(folderTypes);
}
if (m_moduleConfiguration != null) {
Map<String, String> folderTypes = m_moduleConfiguration.getFolderTypes();
m_folderTypes.putAll(folderTypes);
}
}
/**
* Checks whether the given path/type combination belongs to a module configuration file.<p>
*
* @param rootPath the root path of the resource
* @param type the type id of the resource
*
* @return true if the path/type combination belongs to a module configuration
*/
protected boolean isModuleConfiguration(String rootPath, int type) {
return type == m_moduleConfigType.getTypeId();
}
/**
* Returns true if this an online configuration cache.<p>
*
* @return true if this is an online cache, false if it is an offline cache
*/
protected boolean isOnline() {
return m_cms.getRequestContext().getCurrentProject().isOnlineProject();
}
/**
* Checks whether the given path/type combination belongs to a sitemap configuration.<p>
*
* @param rootPath the root path
* @param type the resource type id
*
* @return true if the path/type belong to an active sitemap configuration
*/
protected boolean isSitemapConfiguration(String rootPath, int type) {
return rootPath.endsWith(CmsADEManager.CONFIG_SUFFIX) && (type == m_configType.getTypeId());
}
/**
* Reloads the module configuration.<p>
*/
protected synchronized void refreshModuleConfiguration() {
LOG.info("Refreshing module configuration.");
CmsConfigurationReader reader = new CmsConfigurationReader(m_cms);
m_moduleConfiguration = reader.readModuleConfigurations();
m_moduleConfiguration.initialize(m_cms);
}
/**
* Removes a published resource from the cache.<p>
*
* @param res the published resource
*/
protected void remove(CmsPublishedResource res) {
remove(res.getStructureId(), res.getRootPath(), res.getType());
}
/**
* Removes a resource from the cache.<p>
*
* @param res the resource to remove
*/
protected void remove(CmsResource res) {
remove(res.getStructureId(), res.getRootPath(), res.getTypeId());
}
/**
* Removes the cache entry for the given resource data.<p>
*
* @param structureId the resource structure id
* @param rootPath the resource root path
* @param type the resource type
*/
protected void remove(CmsUUID structureId, String rootPath, int type) {
if (CmsResource.isTemporaryFileName(rootPath)) {
return;
}
try {
updateFolderTypes(rootPath);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
m_pathCache.remove(structureId);
if (isSitemapConfiguration(rootPath, type)) {
synchronized (this) {
String basePath = getBasePath(rootPath);
removePath(basePath);
LOG.info("Removing config file from cache: " + rootPath);
}
} else if (isModuleConfiguration(rootPath, type)) {
LOG.info("Removing module configuration " + rootPath);
synchronized (this) {
m_configurationsToRead.put(MODULE_CONFIG_KEY, CmsUUID.getNullUUID());
}
}
}
/**
* Updates the cache entry for the given published resource.<p>
*
* @param res a published resource
*/
protected void update(CmsPublishedResource res) {
try {
update(res.getStructureId(), res.getRootPath(), res.getType(), res.getState());
} catch (CmsRuntimeException e) {
// may happen during import of org.opencms.ade.configuration module
LOG.warn(e.getLocalizedMessage(), e);
}
}
/**
* Updates the cache entry for the given resource.<p>
*
* @param res the resource for which the cache entry should be updated
*/
protected void update(CmsResource res) {
try {
update(res.getStructureId(), res.getRootPath(), res.getTypeId(), res.getState());
} catch (CmsRuntimeException e) {
// may happen during import of org.opencms.ade.configuration module
LOG.warn(e.getLocalizedMessage(), e);
}
}
/**
* Updates the cache entry for the given resource data.<p>
*
* @param structureId the structure id of the resource
* @param rootPath the root path of the resource
* @param type the type id of the resource
* @param state the state of the resource
*/
protected void update(CmsUUID structureId, String rootPath, int type, CmsResourceState state) {
if (CmsResource.isTemporaryFileName(rootPath)) {
return;
}
try {
updateFolderTypes(rootPath);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
synchronized (m_pathCache) {
m_pathCache.remove(structureId);
m_pathCache.put(structureId, rootPath);
}
if (isSitemapConfiguration(rootPath, type)) {
synchronized (this) {
// Do not update the configuration right now, because reading configuration files while handling
// an event may lead to cache problems. Instead, the configuration file is read when the configuration
// is queried.
LOG.info("Changed configuration file " + rootPath + "(" + structureId + "), will be read later");
m_configurationsToRead.put(rootPath, structureId);
}
} else if (isModuleConfiguration(rootPath, type)) {
LOG.info("Changed module configuration file " + rootPath + "(" + structureId + ")");
synchronized (this) {
m_configurationsToRead.put(MODULE_CONFIG_KEY, CmsUUID.getNullUUID());
}
}
}
/**
* Updates the cached folder types.<p>
*
* @param rootPath the folder root path
* @throws CmsException if something goes wrong
*/
protected synchronized void updateFolderTypes(String rootPath) throws CmsException {
if (m_folderTypes.containsKey(rootPath)) {
LOG.info("Updating folder types because of a change at " + rootPath);
synchronized (this) {
initializeFolderTypes();
}
}
}
/**
* Reads the configuration files which have changed but not been read yet.<p>
*/
private synchronized void readRemainingConfigurations() {
if (m_configurationsToRead.isEmpty()) {
// do not initialize folder types if there were no changes!
return;
}
for (Map.Entry<String, CmsUUID> entry : m_configurationsToRead.entrySet()) {
String rootPath = entry.getKey();
CmsUUID structureId = entry.getValue();
if (rootPath.equals(MODULE_CONFIG_KEY)) {
refreshModuleConfiguration();
} else {
try {
// remove the original entry first, so that the configuration will be gone if reading the
// configuration file fails.
m_siteConfigurations.remove(rootPath);
CmsResource configRes = m_cms.readResource(structureId);
CmsConfigurationReader reader = new CmsConfigurationReader(m_cms);
LOG.info("Reading configuration file " + rootPath + "(" + structureId + ")");
String basePath = getBasePath(rootPath);
CmsADEConfigData configData = reader.parseSitemapConfiguration(basePath, configRes);
configData.initialize(m_cms);
m_siteConfigurations.put(basePath, configData);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
} catch (CmsRuntimeException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
}
m_configurationsToRead.clear();
// Methods which recursively call this method must be called after this point,
// because it will lead to an infinite recursion otherwise.
try {
initializeFolderTypes();
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
} catch (CmsRuntimeException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
/**
* Remove a sitemap configuration from the cache by its base path.<p>
*
* @param rootPath the base path for the sitemap configuration
*/
private void removePath(String rootPath) {
m_configurationsToRead.remove(rootPath);
m_siteConfigurations.remove(rootPath);
}
}
|
package org.opencms.ade.contenteditor;
import com.alkacon.acacia.shared.AttributeConfiguration;
import com.alkacon.acacia.shared.TabInfo;
import com.alkacon.acacia.shared.Type;
import com.alkacon.vie.shared.I_Type;
import org.opencms.ade.contenteditor.CmsContentTypeVisitor.DisplayTypeEvaluator;
import org.opencms.ade.contenteditor.shared.CmsComplexWidgetData;
import org.opencms.ade.contenteditor.shared.CmsExternalWidgetConfiguration;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsMessages;
import org.opencms.i18n.CmsMultiMessages;
import org.opencms.main.OpenCms;
import org.opencms.widgets.A_CmsWidget;
import org.opencms.widgets.I_CmsADEWidget;
import org.opencms.widgets.I_CmsComplexWidget;
import org.opencms.widgets.I_CmsWidget;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.CmsXmlException;
import org.opencms.xml.content.CmsXmlContentTab;
import org.opencms.xml.content.I_CmsXmlContentHandler;
import org.opencms.xml.content.I_CmsXmlContentHandler.DisplayType;
import org.opencms.xml.types.A_CmsXmlContentValue;
import org.opencms.xml.types.CmsXmlNestedContentDefinition;
import org.opencms.xml.types.I_CmsXmlSchemaType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Visitor to read all types and attribute configurations within a content definition.<p>
*/
public class CmsContentTypeVisitor {
/**
* Helper class to evaluate the widget display type.<p>
*/
protected class DisplayTypeEvaluator {
/** The attribute name. */
private String m_attributeName;
/** The attribute type configuration. */
private AttributeConfiguration m_config;
/** The configured display type. */
private DisplayType m_configuredType;
/** The default display type. */
private DisplayType m_default;
/** The applied rule. */
private EvaluationRule m_rule;
/**
* Constructor.<p>
*
* @param config the attribute type configuration
* @param configuredType the configured display type
* @param defaultType the default display type
* @param rule the applied rule
*/
protected DisplayTypeEvaluator(
AttributeConfiguration config,
DisplayType configuredType,
DisplayType defaultType,
EvaluationRule rule) {
m_config = config;
m_configuredType = configuredType;
m_default = defaultType;
m_rule = rule;
}
/**
* Returns the attribute name.<p>
*
* @return the attribute name
*/
protected String getAttributeName() {
return m_attributeName;
}
/**
* Returns the attribute configuration with the evaluated display type.<p>
*
* @param predecessor the proposed predecessor display type
* @param successor the proposed successor display type
*
* @return the attribute configuration
*/
protected AttributeConfiguration getEvaluatedConfiguration(DisplayType predecessor, DisplayType successor) {
DisplayType resultingType = m_configuredType;
if (resultingType.equals(DisplayType.none)) {
if (m_rule.equals(EvaluationRule.rootLevel)) {
resultingType = DisplayType.wide;
} else {
resultingType = getProposedType();
if ((predecessor != null) && predecessor.equals(DisplayType.none)) {
predecessor = null;
}
if ((successor != null) && successor.equals(DisplayType.none)) {
successor = null;
}
if ((predecessor != null) && predecessor.equals(DisplayType.column)) {
predecessor = DisplayType.singleline;
}
if ((successor != null) && successor.equals(DisplayType.column)) {
successor = DisplayType.singleline;
}
boolean strong = (m_rule.equals(EvaluationRule.none) || (m_rule.equals(EvaluationRule.optional) && m_default.equals(DisplayType.singleline)))
|| (m_rule.equals(EvaluationRule.optional) && m_default.equals(DisplayType.singleline));
if (((predecessor == null) || (successor == null)) && strong) {
resultingType = m_default;
} else if ((predecessor != null) || (successor != null)) {
// check if the proposed type matches neither the type of the predecessor nor the type of the successor
if (!(((predecessor != null) && resultingType.equals(predecessor)) || ((successor != null) && resultingType.equals(successor)))) {
DisplayType match = (predecessor != null)
&& (predecessor.equals(DisplayType.wide) || predecessor.equals(DisplayType.singleline))
? predecessor
: ((successor != null)
&& (successor.equals(DisplayType.wide) || successor.equals(DisplayType.singleline))
? successor
: null);
resultingType = match != null ? match : resultingType;
}
}
}
}
m_config.setDisplayType(resultingType.name());
return m_config;
}
/**
* Returns the proposed display type.<p>
*
* @return the proposed display type
*/
protected DisplayType getProposedType() {
DisplayType resultingType = m_configuredType;
if (resultingType.equals(DisplayType.none)) {
switch (m_rule) {
case rootLevel:
case labelLength:
resultingType = DisplayType.wide;
break;
case optional:
resultingType = DisplayType.singleline;
break;
default:
resultingType = m_default;
}
}
return resultingType;
}
/**
* Sets the attribute name.<p>
*
* @param attributeName the attribute name
*/
protected void setAttributeName(String attributeName) {
m_attributeName = attributeName;
}
}
/** Widget display type evaluation rules. */
protected enum EvaluationRule {
/** Label length rule. */
labelLength,
/** No rule applied. */
none,
/** Optional field rule. */
optional,
/** Root level rule. */
rootLevel
}
/** The attribute configurations. */
private Map<String, AttributeConfiguration> m_attributeConfigurations;
/** The CMS context used for this visitor. */
private CmsObject m_cms;
/** Map from attribute names to complex widget configurations. */
private Map<String, CmsComplexWidgetData> m_complexWidgets = new HashMap<String, CmsComplexWidgetData>();
/** The content handler. */
private I_CmsXmlContentHandler m_contentHandler;
/** The content resource. */
private CmsFile m_file;
/** The content locale. */
private Locale m_locale;
/** The messages. */
private CmsMultiMessages m_messages;
/** The registered types. */
private Map<String, I_Type> m_registeredTypes;
/** The tab informations. */
private List<TabInfo> m_tabInfos;
/** The widget configurations. */
private Map<String, CmsExternalWidgetConfiguration> m_widgetConfigurations;
/** The widgets encountered by this visitor. */
private List<I_CmsWidget> m_widgets = new ArrayList<I_CmsWidget>();
/**
* Constructor.<p>
*
* @param cms the CMS context
* @param file the content file
* @param locale the content locale
*/
public CmsContentTypeVisitor(CmsObject cms, CmsFile file, Locale locale) {
m_file = file;
m_cms = cms;
m_locale = locale;
}
/**
* Gets the CMS context.<p>
*
* @return the CMS context
*/
public CmsObject getCmsObject() {
return m_cms;
}
/**
* Gets the list of widgets which have been processed by this visitor.<p>
*
* @return the list of widget
*/
public List<I_CmsWidget> getCollectedWidgets() {
return Collections.unmodifiableList(m_widgets);
}
/**
* Gets the map of complex widget configurations.<p>
*
* @return a map from attribute names to complex widget configurations
*/
public Map<String, CmsComplexWidgetData> getComplexWidgetData() {
return m_complexWidgets;
}
/**
* Returns the tabInfos.<p>
*
* @return the tabInfos
*/
public List<TabInfo> getTabInfos() {
return m_tabInfos;
}
/**
* Checks if the content type widgets are compatible with the new content editor.<p>
*
* @param xmlContentDefinition the content definition
*
* @return <code>true</code> if the content type widgets are compatible with the new content editor
*
* @throws CmsXmlException if something goes wrong reading the type widget
*/
public boolean isEditorCompatible(CmsXmlContentDefinition xmlContentDefinition) throws CmsXmlException {
boolean result = true;
for (I_CmsXmlSchemaType subType : xmlContentDefinition.getTypeSequence()) {
if (subType.isSimpleType()) {
result = isEditorCompatible((A_CmsXmlContentValue)subType);
} else {
CmsXmlContentDefinition subTypeDefinition = ((CmsXmlNestedContentDefinition)subType).getNestedContentDefinition();
result = isEditorCompatible(subTypeDefinition);
}
if (!result) {
break;
}
}
return result;
}
/**
* Visits all types within the XML content definition.<p>
*
* @param xmlContentDefinition the content definition
* @param messageLocale the locale
*/
/**
* Visits all types within the XML content definition.<p>
*
* @param xmlContentDefinition the content definition
* @param messageLocale the locale
*/
public void visitTypes(CmsXmlContentDefinition xmlContentDefinition, Locale messageLocale) {
m_contentHandler = xmlContentDefinition.getContentHandler();
CmsMessages messages = null;
m_messages = new CmsMultiMessages(messageLocale);
try {
messages = OpenCms.getWorkplaceManager().getMessages(messageLocale);
if (messages != null) {
m_messages.addMessages(messages);
}
messages = m_contentHandler.getMessages(messageLocale);
if (messages != null) {
m_messages.addMessages(messages);
}
} catch (Exception e) {
//ignore
}
// generate a new multi messages object and add the messages from the workplace
m_attributeConfigurations = new HashMap<String, AttributeConfiguration>();
m_widgetConfigurations = new HashMap<String, CmsExternalWidgetConfiguration>();
m_registeredTypes = new HashMap<String, I_Type>();
m_tabInfos = collectTabInfos(xmlContentDefinition);
readTypes(xmlContentDefinition, "");
}
/**
* Returns the attribute configurations.<p>
*
* @return the attribute configurations
*/
protected Map<String, AttributeConfiguration> getAttributeConfigurations() {
return m_attributeConfigurations;
}
/**
* Returns the types of the visited content definition.<p>
*
* @return the types
*/
protected Map<String, I_Type> getTypes() {
return m_registeredTypes;
}
/**
* Returns the external widget configurations.<p>
*
* @return the external widget configurations
*/
protected Collection<CmsExternalWidgetConfiguration> getWidgetConfigurations() {
return m_widgetConfigurations.values();
}
/**
* Returns the tab informations for the given content definition.<p>
*
* @param definition the content definition
*
* @return the tab informations
*/
private List<TabInfo> collectTabInfos(CmsXmlContentDefinition definition) {
List<TabInfo> result = new ArrayList<TabInfo>();
if (definition.getContentHandler().getTabs() != null) {
for (CmsXmlContentTab xmlTab : definition.getContentHandler().getTabs()) {
String tabName = m_messages.keyDefault(A_CmsWidget.LABEL_PREFIX
+ definition.getInnerName()
+ "."
+ xmlTab.getTabName(), xmlTab.getTabName());
result.add(new TabInfo(tabName, xmlTab.getIdName(), xmlTab.getStartName(), xmlTab.isCollapsed()));
}
}
return result;
}
/**
* Returns the help information for this value.<p>
*
* @param value the value
*
* @return the help information
*/
private String getHelp(I_CmsXmlSchemaType value) {
StringBuffer result = new StringBuffer(64);
result.append(A_CmsWidget.LABEL_PREFIX);
result.append(getTypeKey(value));
result.append(A_CmsWidget.HELP_POSTFIX);
return m_messages.keyDefault(result.toString(), null);
}
/**
* Returns the label for this value.<p>
*
* @param value the value
*
* @return the label
*/
private String getLabel(I_CmsXmlSchemaType value) {
StringBuffer result = new StringBuffer(64);
result.append(A_CmsWidget.LABEL_PREFIX);
result.append(getTypeKey(value));
return m_messages.keyDefault(result.toString(), value.getName());
}
/**
* Returns the schema type message key.<p>
*
* @param value the schema type
*
* @return the schema type message key
*/
private String getTypeKey(I_CmsXmlSchemaType value) {
StringBuffer result = new StringBuffer(64);
result.append(value.getContentDefinition().getInnerName());
result.append('.');
result.append(value.getName());
return result.toString();
}
/**
* Checks if the content value widget is compatible with the new content editor.<p>
*
* @param schemaType the content value type
*
* @return <code>true</code> if the content value widget is compatible with the new content editor
*
* @throws CmsXmlException if something goes wrong reading the type widget
*/
private boolean isEditorCompatible(A_CmsXmlContentValue schemaType) throws CmsXmlException {
boolean result = false;
I_CmsXmlContentHandler contentHandler = schemaType.getContentDefinition().getContentHandler();
I_CmsWidget widget = contentHandler.getWidget(schemaType);
result = (widget == null) || (widget instanceof I_CmsADEWidget);
return result;
}
/**
* Returns if an element with the given path will be displayed at root level of a content editor tab.<p>
*
* @param path the element path
*
* @return <code>true</code> if an element with the given path will be displayed at root level of a content editor tab
*/
private boolean isTabRootLevel(String path) {
path = path.substring(1);
if (!path.contains("/")) {
return true;
}
if (m_tabInfos != null) {
for (TabInfo info : m_tabInfos) {
if (info.isCollapsed()
&& path.startsWith(info.getStartName())
&& !path.substring(info.getStartName().length() + 1).contains("/")) {
return true;
}
}
}
return false;
}
/**
* Reads the attribute configuration for the given schema type. May return <code>null</code> if no special configuration was set.<p>
*
* @param schemaType the schema type
* @param path the attribute path
*
* @return the attribute configuration
*/
private DisplayTypeEvaluator readConfiguration(A_CmsXmlContentValue schemaType, String path) {
String widgetName = null;
String widgetConfig = null;
CmsObject cms = getCmsObject();
String label = getLabel(schemaType);
// set the default display type
DisplayType configuredType = DisplayType.none;
DisplayType defaultType = DisplayType.none;
EvaluationRule rule = EvaluationRule.none;
try {
I_CmsXmlContentHandler contentHandler = schemaType.getContentDefinition().getContentHandler();
I_CmsWidget widget = contentHandler.getWidget(schemaType);
configuredType = contentHandler.getDisplayType(schemaType);
if (configuredType.equals(DisplayType.none) && schemaType.isSimpleType()) {
// check the type is on the root level of the document, those will be displayed 'wide'
// the path will always have a leading '/'
// also in case the label has more than 15 characters, we display 'wide'
if (isTabRootLevel(path)) {
rule = EvaluationRule.rootLevel;
} else if (label.length() > 15) {
rule = EvaluationRule.labelLength;
} else if ((schemaType.getMinOccurs() == 0)) {
rule = EvaluationRule.optional;
}
}
if (widget != null) {
widgetName = widget.getClass().getName();
if ((configuredType == DisplayType.column)
&& !(schemaType.isSimpleType() && (schemaType.getMaxOccurs() == 1) && widget.isCompactViewEnabled())) {
// column view is not allowed for this widget
configuredType = DisplayType.singleline;
}
long timer = 0;
if (widget instanceof I_CmsADEWidget) {
if (CmsContentService.LOG.isDebugEnabled()) {
timer = System.currentTimeMillis();
}
I_CmsADEWidget adeWidget = (I_CmsADEWidget)widget;
defaultType = adeWidget.getDefaultDisplayType();
widgetName = adeWidget.getWidgetName();
widgetConfig = adeWidget.getConfiguration(cms, schemaType, m_messages, m_file, m_locale);
if (!adeWidget.isInternal() && !m_widgetConfigurations.containsKey(widgetName)) {
CmsExternalWidgetConfiguration externalConfiguration = new CmsExternalWidgetConfiguration(
widgetName,
adeWidget.getInitCall(),
adeWidget.getJavaScriptResourceLinks(cms),
adeWidget.getCssResourceLinks(cms));
m_widgetConfigurations.put(widgetName, externalConfiguration);
}
if (CmsContentService.LOG.isDebugEnabled()) {
CmsContentService.LOG.debug(Messages.get().getBundle().key(
Messages.LOG_TAKE_READING_WIDGET_CONFIGURATION_TIME_2,
widgetName,
"" + (System.currentTimeMillis() - timer)));
}
}
m_widgets.add(widget);
} else if (contentHandler.getComplexWidget(schemaType) != null) {
I_CmsComplexWidget complexWidget = contentHandler.getComplexWidget(schemaType);
CmsComplexWidgetData widgetData = complexWidget.getWidgetData(m_cms);
CmsExternalWidgetConfiguration externalConfig = widgetData.getExternalWidgetConfiguration();
if (externalConfig != null) {
m_widgetConfigurations.put(complexWidget.getName(), externalConfig);
}
m_complexWidgets.put(CmsContentService.getAttributeName(schemaType), widgetData);
}
} catch (Exception e) {
// may happen if no widget was set for the value
CmsContentService.LOG.debug(e.getMessage(), e);
}
AttributeConfiguration result = new AttributeConfiguration(
label,
getHelp(schemaType),
widgetName,
widgetConfig,
readDefaultValue(schemaType, path),
configuredType.name());
return new DisplayTypeEvaluator(result, configuredType, defaultType, rule);
}
/**
* Reads the default value for the given type.<p>
*
* @param schemaType the schema type
* @param path the element path
*
* @return the default value
*/
private String readDefaultValue(I_CmsXmlSchemaType schemaType, String path) {
return m_contentHandler.getDefault(getCmsObject(), m_file, schemaType, path, m_locale);
}
/**
* Reads the types from the given content definition and adds the to the map of already registered
* types if necessary.<p>
*
* @param xmlContentDefinition the XML content definition
* @param path the element path
*/
private void readTypes(CmsXmlContentDefinition xmlContentDefinition, String path) {
String typeName = CmsContentService.getTypeUri(xmlContentDefinition);
if (m_registeredTypes.containsKey(typeName)) {
return;
}
Type type = new Type(typeName);
type.setChoiceMaxOccurrence(xmlContentDefinition.getChoiceMaxOccurs());
m_registeredTypes.put(typeName, type);
if (type.isChoice()) {
Type choiceType = new Type(typeName + "/" + Type.CHOICE_ATTRIBUTE_NAME);
m_registeredTypes.put(choiceType.getId(), choiceType);
type.addAttribute(
Type.CHOICE_ATTRIBUTE_NAME,
choiceType.getId(),
1,
xmlContentDefinition.getChoiceMaxOccurs());
type = choiceType;
}
ArrayList<DisplayTypeEvaluator> evaluators = new ArrayList<DisplayTypeEvaluator>();
for (I_CmsXmlSchemaType subType : xmlContentDefinition.getTypeSequence()) {
String subTypeName = null;
String childPath = path + "/" + subType.getName();
String subAttributeName = CmsContentService.getAttributeName(subType.getName(), typeName);
DisplayTypeEvaluator ev = readConfiguration((A_CmsXmlContentValue)subType, childPath);
ev.setAttributeName(subAttributeName);
evaluators.add(ev);
if (subType.isSimpleType()) {
subTypeName = CmsContentService.TYPE_NAME_PREFIX + subType.getTypeName();
if (!m_registeredTypes.containsKey(subTypeName)) {
m_registeredTypes.put(subTypeName, new Type(subTypeName));
}
} else {
CmsXmlContentDefinition subTypeDefinition = ((CmsXmlNestedContentDefinition)subType).getNestedContentDefinition();
subTypeName = CmsContentService.getTypeUri(subTypeDefinition);
readTypes(subTypeDefinition, childPath);
}
type.addAttribute(subAttributeName, subTypeName, subType.getMinOccurs(), subType.getMaxOccurs());
}
DisplayType predecessor = null;
for (int i = 0; i < evaluators.size(); i++) {
DisplayTypeEvaluator ev = evaluators.get(i);
DisplayType successor = ((i + 1) < evaluators.size()) ? evaluators.get(i + 1).getProposedType() : null;
AttributeConfiguration evaluated = ev.getEvaluatedConfiguration(predecessor, successor);
m_attributeConfigurations.put(ev.getAttributeName(), evaluated);
predecessor = DisplayType.valueOf(evaluated.getDisplayType());
}
}
}
|
package io.druid.server.coordinator;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Closeables;
import com.google.inject.Inject;
import com.metamx.common.IAE;
import com.metamx.common.Pair;
import com.metamx.common.concurrent.ScheduledExecutorFactory;
import com.metamx.common.concurrent.ScheduledExecutors;
import com.metamx.common.guava.Comparators;
import com.metamx.common.guava.FunctionalIterable;
import com.metamx.common.lifecycle.LifecycleStart;
import com.metamx.common.lifecycle.LifecycleStop;
import com.metamx.emitter.EmittingLogger;
import com.metamx.emitter.service.ServiceEmitter;
import com.metamx.emitter.service.ServiceMetricEvent;
import io.druid.client.DruidDataSource;
import io.druid.client.DruidServer;
import io.druid.client.ImmutableDruidDataSource;
import io.druid.client.ImmutableDruidServer;
import io.druid.client.ServerInventoryView;
import io.druid.client.indexing.IndexingServiceClient;
import io.druid.collections.CountingMap;
import io.druid.common.config.JacksonConfigManager;
import io.druid.concurrent.Execs;
import io.druid.curator.discovery.ServiceAnnouncer;
import io.druid.db.DatabaseRuleManager;
import io.druid.db.DatabaseSegmentManager;
import io.druid.guice.ManageLifecycle;
import io.druid.guice.annotations.Self;
import io.druid.segment.IndexIO;
import io.druid.server.DruidNode;
import io.druid.server.coordinator.helper.DruidCoordinatorBalancer;
import io.druid.server.coordinator.helper.DruidCoordinatorCleanup;
import io.druid.server.coordinator.helper.DruidCoordinatorHelper;
import io.druid.server.coordinator.helper.DruidCoordinatorLogger;
import io.druid.server.coordinator.helper.DruidCoordinatorRuleRunner;
import io.druid.server.coordinator.helper.DruidCoordinatorSegmentInfoLoader;
import io.druid.server.coordinator.helper.DruidCoordinatorSegmentMerger;
import io.druid.server.coordinator.rules.LoadRule;
import io.druid.server.coordinator.rules.Rule;
import io.druid.server.initialization.ZkPathsConfig;
import io.druid.timeline.DataSegment;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.framework.recipes.leader.Participant;
import org.apache.curator.utils.ZKPaths;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
@ManageLifecycle
public class DruidCoordinator
{
public static final String COORDINATOR_OWNER_NODE = "_COORDINATOR";
private static final EmittingLogger log = new EmittingLogger(DruidCoordinator.class);
private final Object lock = new Object();
private final DruidCoordinatorConfig config;
private final ZkPathsConfig zkPaths;
private final JacksonConfigManager configManager;
private final DatabaseSegmentManager databaseSegmentManager;
private final ServerInventoryView<Object> serverInventoryView;
private final DatabaseRuleManager databaseRuleManager;
private final CuratorFramework curator;
private final ServiceEmitter emitter;
private final IndexingServiceClient indexingServiceClient;
private final ScheduledExecutorService exec;
private final LoadQueueTaskMaster taskMaster;
private final Map<String, LoadQueuePeon> loadManagementPeons;
private final AtomicReference<LeaderLatch> leaderLatch;
private final ServiceAnnouncer serviceAnnouncer;
private final DruidNode self;
private volatile boolean started = false;
private volatile int leaderCounter = 0;
private volatile boolean leader = false;
private volatile SegmentReplicantLookup segmentReplicantLookup = null;
@Inject
public DruidCoordinator(
DruidCoordinatorConfig config,
ZkPathsConfig zkPaths,
JacksonConfigManager configManager,
DatabaseSegmentManager databaseSegmentManager,
ServerInventoryView serverInventoryView,
DatabaseRuleManager databaseRuleManager,
CuratorFramework curator,
ServiceEmitter emitter,
ScheduledExecutorFactory scheduledExecutorFactory,
IndexingServiceClient indexingServiceClient,
LoadQueueTaskMaster taskMaster,
ServiceAnnouncer serviceAnnouncer,
@Self DruidNode self
)
{
this(
config,
zkPaths,
configManager,
databaseSegmentManager,
serverInventoryView,
databaseRuleManager,
curator,
emitter,
scheduledExecutorFactory,
indexingServiceClient,
taskMaster,
serviceAnnouncer,
self,
Maps.<String, LoadQueuePeon>newConcurrentMap()
);
}
DruidCoordinator(
DruidCoordinatorConfig config,
ZkPathsConfig zkPaths,
JacksonConfigManager configManager,
DatabaseSegmentManager databaseSegmentManager,
ServerInventoryView serverInventoryView,
DatabaseRuleManager databaseRuleManager,
CuratorFramework curator,
ServiceEmitter emitter,
ScheduledExecutorFactory scheduledExecutorFactory,
IndexingServiceClient indexingServiceClient,
LoadQueueTaskMaster taskMaster,
ServiceAnnouncer serviceAnnouncer,
DruidNode self,
ConcurrentMap<String, LoadQueuePeon> loadQueuePeonMap
)
{
this.config = config;
this.zkPaths = zkPaths;
this.configManager = configManager;
this.databaseSegmentManager = databaseSegmentManager;
this.serverInventoryView = serverInventoryView;
this.databaseRuleManager = databaseRuleManager;
this.curator = curator;
this.emitter = emitter;
this.indexingServiceClient = indexingServiceClient;
this.taskMaster = taskMaster;
this.serviceAnnouncer = serviceAnnouncer;
this.self = self;
this.exec = scheduledExecutorFactory.create(1, "Coordinator-Exec
this.leaderLatch = new AtomicReference<>(null);
this.loadManagementPeons = loadQueuePeonMap;
}
public boolean isLeader()
{
return leader;
}
public Map<String, LoadQueuePeon> getLoadManagementPeons()
{
return loadManagementPeons;
}
public Map<String, CountingMap<String>> getReplicationStatus()
{
final Map<String, CountingMap<String>> retVal = Maps.newHashMap();
if (segmentReplicantLookup == null) {
return retVal;
}
final DateTime now = new DateTime();
for (DataSegment segment : getAvailableDataSegments()) {
List<Rule> rules = databaseRuleManager.getRulesWithDefault(segment.getDataSource());
for (Rule rule : rules) {
if (rule instanceof LoadRule && rule.appliesTo(segment, now)) {
for (Map.Entry<String, Integer> entry : ((LoadRule) rule).getTieredReplicants().entrySet()) {
CountingMap<String> dataSourceMap = retVal.get(entry.getKey());
if (dataSourceMap == null) {
dataSourceMap = new CountingMap<>();
retVal.put(entry.getKey(), dataSourceMap);
}
int diff = Math.max(
entry.getValue() - segmentReplicantLookup.getTotalReplicants(segment.getIdentifier(), entry.getKey()),
0
);
dataSourceMap.add(segment.getDataSource(), diff);
}
break;
}
}
}
return retVal;
}
public CountingMap<String> getSegmentAvailability()
{
final CountingMap<String> retVal = new CountingMap<>();
if (segmentReplicantLookup == null) {
return retVal;
}
for (DataSegment segment : getAvailableDataSegments()) {
int available = (segmentReplicantLookup.getTotalReplicants(segment.getIdentifier()) == 0) ? 0 : 1;
retVal.add(segment.getDataSource(), 1 - available);
}
return retVal;
}
public Map<String, Double> getLoadStatus()
{
// find available segments
Map<String, Set<DataSegment>> availableSegments = Maps.newHashMap();
for (DataSegment dataSegment : getAvailableDataSegments()) {
Set<DataSegment> segments = availableSegments.get(dataSegment.getDataSource());
if (segments == null) {
segments = Sets.newHashSet();
availableSegments.put(dataSegment.getDataSource(), segments);
}
segments.add(dataSegment);
}
// find segments currently loaded
Map<String, Set<DataSegment>> segmentsInCluster = Maps.newHashMap();
for (DruidServer druidServer : serverInventoryView.getInventory()) {
for (DruidDataSource druidDataSource : druidServer.getDataSources()) {
Set<DataSegment> segments = segmentsInCluster.get(druidDataSource.getName());
if (segments == null) {
segments = Sets.newHashSet();
segmentsInCluster.put(druidDataSource.getName(), segments);
}
segments.addAll(druidDataSource.getSegments());
}
}
// compare available segments with currently loaded
Map<String, Double> loadStatus = Maps.newHashMap();
for (Map.Entry<String, Set<DataSegment>> entry : availableSegments.entrySet()) {
String dataSource = entry.getKey();
Set<DataSegment> segmentsAvailable = entry.getValue();
Set<DataSegment> loadedSegments = segmentsInCluster.get(dataSource);
if (loadedSegments == null) {
loadedSegments = Sets.newHashSet();
}
Set<DataSegment> unloadedSegments = Sets.difference(segmentsAvailable, loadedSegments);
loadStatus.put(
dataSource,
100 * ((double) (segmentsAvailable.size() - unloadedSegments.size()) / (double) segmentsAvailable.size())
);
}
return loadStatus;
}
public CoordinatorDynamicConfig getDynamicConfigs()
{
return configManager.watch(
CoordinatorDynamicConfig.CONFIG_KEY,
CoordinatorDynamicConfig.class,
new CoordinatorDynamicConfig.Builder().build()
).get();
}
public void removeSegment(DataSegment segment)
{
log.info("Removing Segment[%s]", segment);
databaseSegmentManager.removeSegment(segment.getDataSource(), segment.getIdentifier());
}
public void removeDatasource(String ds)
{
databaseSegmentManager.removeDatasource(ds);
}
public void enableDatasource(String ds)
{
databaseSegmentManager.enableDatasource(ds);
}
public String getCurrentLeader()
{
try {
final LeaderLatch latch = leaderLatch.get();
if (latch == null) {
return null;
}
Participant participant = latch.getLeader();
if (participant.isLeader()) {
return participant.getId();
}
return null;
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
public void moveSegment(
ImmutableDruidServer fromServer,
ImmutableDruidServer toServer,
String segmentName,
final LoadPeonCallback callback
)
{
try {
if (fromServer.getMetadata().equals(toServer.getMetadata())) {
throw new IAE("Cannot move [%s] to and from the same server [%s]", segmentName, fromServer.getName());
}
final DataSegment segment = fromServer.getSegment(segmentName);
if (segment == null) {
throw new IAE("Unable to find segment [%s] on server [%s]", segmentName, fromServer.getName());
}
final LoadQueuePeon loadPeon = loadManagementPeons.get(toServer.getName());
if (loadPeon == null) {
throw new IAE("LoadQueuePeon hasn't been created yet for path [%s]", toServer.getName());
}
final LoadQueuePeon dropPeon = loadManagementPeons.get(fromServer.getName());
if (dropPeon == null) {
throw new IAE("LoadQueuePeon hasn't been created yet for path [%s]", fromServer.getName());
}
final ServerHolder toHolder = new ServerHolder(toServer, loadPeon);
if (toHolder.getAvailableSize() < segment.getSize()) {
throw new IAE(
"Not enough capacity on server [%s] for segment [%s]. Required: %,d, available: %,d.",
toServer.getName(),
segment,
segment.getSize(),
toHolder.getAvailableSize()
);
}
final String toLoadQueueSegPath = ZKPaths.makePath(
ZKPaths.makePath(
zkPaths.getLoadQueuePath(),
toServer.getName()
), segmentName
);
final String toServedSegPath = ZKPaths.makePath(
ZKPaths.makePath(serverInventoryView.getInventoryManagerConfig().getInventoryPath(), toServer.getName()),
segmentName
);
loadPeon.loadSegment(
segment,
new LoadPeonCallback()
{
@Override
public void execute()
{
try {
if (curator.checkExists().forPath(toServedSegPath) != null &&
curator.checkExists().forPath(toLoadQueueSegPath) == null &&
!dropPeon.getSegmentsToDrop().contains(segment)) {
dropPeon.dropSegment(segment, callback);
} else if (callback != null) {
callback.execute();
}
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
);
}
catch (Exception e) {
log.makeAlert(e, "Exception moving segment %s", segmentName).emit();
if (callback != null) {
callback.execute();
}
}
}
public Set<DataSegment> getOrderedAvailableDataSegments()
{
Set<DataSegment> availableSegments = Sets.newTreeSet(Comparators.inverse(DataSegment.bucketMonthComparator()));
Iterable<DataSegment> dataSegments = getAvailableDataSegments();
for (DataSegment dataSegment : dataSegments) {
if (dataSegment.getSize() < 0) {
log.makeAlert("No size on Segment, wtf?")
.addData("segment", dataSegment)
.emit();
}
availableSegments.add(dataSegment);
}
return availableSegments;
}
public Iterable<DataSegment> getAvailableDataSegments()
{
return Iterables.concat(
Iterables.transform(
databaseSegmentManager.getInventory(),
new Function<DruidDataSource, Iterable<DataSegment>>()
{
@Override
public Iterable<DataSegment> apply(DruidDataSource input)
{
return input.getSegments();
}
}
)
);
}
@LifecycleStart
public void start()
{
synchronized (lock) {
if (started) {
return;
}
started = true;
createNewLeaderLatch();
try {
leaderLatch.get().start();
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
private LeaderLatch createNewLeaderLatch()
{
final LeaderLatch newLeaderLatch = new LeaderLatch(
curator, ZKPaths.makePath(zkPaths.getCoordinatorPath(), COORDINATOR_OWNER_NODE), config.getHost()
);
newLeaderLatch.addListener(
new LeaderLatchListener()
{
@Override
public void isLeader()
{
DruidCoordinator.this.becomeLeader();
}
@Override
public void notLeader()
{
DruidCoordinator.this.stopBeingLeader();
}
},
Execs.singleThreaded("CoordinatorLeader-%s")
);
return leaderLatch.getAndSet(newLeaderLatch);
}
@LifecycleStop
public void stop()
{
synchronized (lock) {
if (!started) {
return;
}
stopBeingLeader();
try {
leaderLatch.get().close();
}
catch (IOException e) {
log.warn(e, "Unable to close leaderLatch, ignoring");
}
started = false;
exec.shutdownNow();
}
}
private void becomeLeader()
{
synchronized (lock) {
if (!started) {
return;
}
log.info("I am the leader of the coordinators, all must bow!");
try {
leaderCounter++;
leader = true;
databaseSegmentManager.start();
databaseRuleManager.start();
serverInventoryView.start();
serviceAnnouncer.announce(self);
final int startingLeaderCounter = leaderCounter;
final List<Pair<? extends CoordinatorRunnable, Duration>> coordinatorRunnables = Lists.newArrayList();
coordinatorRunnables.add(
Pair.of(
new CoordinatorHistoricalManagerRunnable(startingLeaderCounter),
config.getCoordinatorPeriod()
)
);
if (indexingServiceClient != null) {
coordinatorRunnables.add(
Pair.of(
new CoordinatorIndexingServiceRunnable(
makeIndexingServiceHelpers(
configManager.watch(
DatasourceWhitelist.CONFIG_KEY,
DatasourceWhitelist.class
)
),
startingLeaderCounter
),
config.getCoordinatorIndexingPeriod()
)
);
}
for (final Pair<? extends CoordinatorRunnable, Duration> coordinatorRunnable : coordinatorRunnables) {
ScheduledExecutors.scheduleWithFixedDelay(
exec,
config.getCoordinatorStartDelay(),
coordinatorRunnable.rhs,
new Callable<ScheduledExecutors.Signal>()
{
private final CoordinatorRunnable theRunnable = coordinatorRunnable.lhs;
@Override
public ScheduledExecutors.Signal call()
{
if (leader && startingLeaderCounter == leaderCounter) {
theRunnable.run();
}
if (leader && startingLeaderCounter == leaderCounter) { // (We might no longer be leader)
return ScheduledExecutors.Signal.REPEAT;
} else {
return ScheduledExecutors.Signal.STOP;
}
}
}
);
}
}
catch (Exception e) {
log.makeAlert(e, "Unable to become leader")
.emit();
final LeaderLatch oldLatch = createNewLeaderLatch();
Closeables.closeQuietly(oldLatch);
try {
leaderLatch.get().start();
}
catch (Exception e1) {
// If an exception gets thrown out here, then the coordinator will zombie out 'cause it won't be looking for
// the latch anymore. I don't believe it's actually possible for an Exception to throw out here, but
// Curator likes to have "throws Exception" on methods so it might happen...
log.makeAlert(e1, "I am a zombie")
.emit();
}
}
}
}
private void stopBeingLeader()
{
synchronized (lock) {
try {
leaderCounter++;
log.info("I am no longer the leader...");
for (String server : loadManagementPeons.keySet()) {
LoadQueuePeon peon = loadManagementPeons.remove(server);
peon.stop();
}
loadManagementPeons.clear();
serviceAnnouncer.unannounce(self);
serverInventoryView.stop();
databaseRuleManager.stop();
databaseSegmentManager.stop();
leader = false;
}
catch (Exception e) {
log.makeAlert(e, "Unable to stopBeingLeader").emit();
}
}
}
private List<DruidCoordinatorHelper> makeIndexingServiceHelpers(final AtomicReference<DatasourceWhitelist> whitelistRef)
{
List<DruidCoordinatorHelper> helpers = Lists.newArrayList();
helpers.add(new DruidCoordinatorSegmentInfoLoader(DruidCoordinator.this));
if (config.isConvertSegments()) {
helpers.add(new DruidCoordinatorVersionConverter(indexingServiceClient, whitelistRef));
}
if (config.isMergeSegments()) {
helpers.add(new DruidCoordinatorSegmentMerger(indexingServiceClient, whitelistRef));
helpers.add(
new DruidCoordinatorHelper()
{
@Override
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params)
{
CoordinatorStats stats = params.getCoordinatorStats();
log.info("Issued merge requests for %s segments", stats.getGlobalStats().get("mergedCount").get());
params.getEmitter().emit(
new ServiceMetricEvent.Builder().build(
"coordinator/merge/count", stats.getGlobalStats().get("mergedCount")
)
);
return params;
}
}
);
}
return ImmutableList.copyOf(helpers);
}
public static class DruidCoordinatorVersionConverter implements DruidCoordinatorHelper
{
private final IndexingServiceClient indexingServiceClient;
private final AtomicReference<DatasourceWhitelist> whitelistRef;
public DruidCoordinatorVersionConverter(
IndexingServiceClient indexingServiceClient,
AtomicReference<DatasourceWhitelist> whitelistRef
)
{
this.indexingServiceClient = indexingServiceClient;
this.whitelistRef = whitelistRef;
}
@Override
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params)
{
DatasourceWhitelist whitelist = whitelistRef.get();
for (DataSegment dataSegment : params.getAvailableSegments()) {
if (whitelist == null || whitelist.contains(dataSegment.getDataSource())) {
final Integer binaryVersion = dataSegment.getBinaryVersion();
if (binaryVersion == null || binaryVersion < IndexIO.CURRENT_VERSION_ID) {
log.info("Upgrading version on segment[%s]", dataSegment.getIdentifier());
indexingServiceClient.upgradeSegment(dataSegment);
}
}
}
return params;
}
}
public abstract class CoordinatorRunnable implements Runnable
{
private final long startTime = System.currentTimeMillis();
private final List<DruidCoordinatorHelper> helpers;
private final int startingLeaderCounter;
protected CoordinatorRunnable(List<DruidCoordinatorHelper> helpers, final int startingLeaderCounter)
{
this.helpers = helpers;
this.startingLeaderCounter = startingLeaderCounter;
}
@Override
public void run()
{
try {
synchronized (lock) {
final LeaderLatch latch = leaderLatch.get();
if (latch == null || !latch.hasLeadership()) {
log.info("LEGGO MY EGGO. [%s] is leader.", latch == null ? null : latch.getLeader().getId());
stopBeingLeader();
return;
}
}
List<Boolean> allStarted = Arrays.asList(
databaseSegmentManager.isStarted(),
serverInventoryView.isStarted()
);
for (Boolean aBoolean : allStarted) {
if (!aBoolean) {
log.error("InventoryManagers not started[%s]", allStarted);
stopBeingLeader();
return;
}
}
BalancerStrategyFactory factory =
new CostBalancerStrategyFactory(getDynamicConfigs().getBalancerComputeThreads());
// Do coordinator stuff.
DruidCoordinatorRuntimeParams params =
DruidCoordinatorRuntimeParams.newBuilder()
.withStartTime(startTime)
.withDatasources(databaseSegmentManager.getInventory())
.withDynamicConfigs(getDynamicConfigs())
.withEmitter(emitter)
.withBalancerStrategyFactory(factory)
.build();
for (DruidCoordinatorHelper helper : helpers) {
// Don't read state and run state in the same helper otherwise racy conditions may exist
if (leader && startingLeaderCounter == leaderCounter) {
params = helper.run(params);
}
}
}
catch (Exception e) {
log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit();
}
}
}
private class CoordinatorHistoricalManagerRunnable extends CoordinatorRunnable
{
public CoordinatorHistoricalManagerRunnable(final int startingLeaderCounter)
{
super(
ImmutableList.of(
new DruidCoordinatorSegmentInfoLoader(DruidCoordinator.this),
new DruidCoordinatorHelper()
{
@Override
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params)
{
// Display info about all historical servers
Iterable<ImmutableDruidServer> servers = FunctionalIterable
.create(serverInventoryView.getInventory())
.filter(
new Predicate<DruidServer>()
{
@Override
public boolean apply(
DruidServer input
)
{
return input.isAssignable();
}
}
).transform(
new Function<DruidServer, ImmutableDruidServer>()
{
@Override
public ImmutableDruidServer apply(DruidServer input)
{
return input.toImmutableDruidServer();
}
}
);
if (log.isDebugEnabled()) {
log.debug("Servers");
for (ImmutableDruidServer druidServer : servers) {
log.debug(" %s", druidServer);
log.debug(" -- DataSources");
for (ImmutableDruidDataSource druidDataSource : druidServer.getDataSources()) {
log.debug(" %s", druidDataSource);
}
}
}
// Find all historical servers, group them by subType and sort by ascending usage
final DruidCluster cluster = new DruidCluster();
for (ImmutableDruidServer server : servers) {
if (!loadManagementPeons.containsKey(server.getName())) {
String basePath = ZKPaths.makePath(zkPaths.getLoadQueuePath(), server.getName());
LoadQueuePeon loadQueuePeon = taskMaster.giveMePeon(basePath);
log.info("Creating LoadQueuePeon for server[%s] at path[%s]", server.getName(), basePath);
loadManagementPeons.put(server.getName(), loadQueuePeon);
}
cluster.add(new ServerHolder(server, loadManagementPeons.get(server.getName())));
}
segmentReplicantLookup = SegmentReplicantLookup.make(cluster);
// Stop peons for servers that aren't there anymore.
final Set<String> disappeared = Sets.newHashSet(loadManagementPeons.keySet());
for (ImmutableDruidServer server : servers) {
disappeared.remove(server.getName());
}
for (String name : disappeared) {
log.info("Removing listener for server[%s] which is no longer there.", name);
LoadQueuePeon peon = loadManagementPeons.remove(name);
peon.stop();
}
return params.buildFromExisting()
.withDruidCluster(cluster)
.withDatabaseRuleManager(databaseRuleManager)
.withLoadManagementPeons(loadManagementPeons)
.withSegmentReplicantLookup(segmentReplicantLookup)
.withBalancerReferenceTimestamp(DateTime.now())
.build();
}
},
new DruidCoordinatorRuleRunner(DruidCoordinator.this),
new DruidCoordinatorCleanup(DruidCoordinator.this),
new DruidCoordinatorBalancer(DruidCoordinator.this),
new DruidCoordinatorLogger()
),
startingLeaderCounter
);
}
}
private class CoordinatorIndexingServiceRunnable extends CoordinatorRunnable
{
public CoordinatorIndexingServiceRunnable(List<DruidCoordinatorHelper> helpers, final int startingLeaderCounter)
{
super(helpers, startingLeaderCounter);
}
}
}
|
package org.zanata.action;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.CacheMode;
import org.hibernate.FlushMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Transaction;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.annotations.Indexed;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.annotations.security.Restrict;
import org.jboss.seam.deployment.StandardDeploymentStrategy;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
import org.zanata.model.HAccount;
import org.zanata.model.HIterationProject;
import org.zanata.model.HTextFlow;
@Name("adminAction")
@Scope(ScopeType.APPLICATION)
@Startup
@Restrict("#{s:hasRole('admin')}")
public class AdminActionBean
{
private static final int BATCH_SIZE = 500;
@Logger
private Log log;
@In
FullTextSession session;
private Set<Class<?>> indexables = new HashSet<Class<?>>();
@Create
public void create()
{
// TODO: find a version of this that works:
// indexables.addAll(StandardDeploymentStrategy.instance().getAnnotatedClasses().get(Indexed.class.getName()));
indexables.add(HIterationProject.class);
indexables.add(HAccount.class);
indexables.add(HTextFlow.class);
}
/*
* TODO make it an @Asynchronous call and have some boolean isRunning method
* to disable the button if the job is already running
*/
public void reindexDatabase()
{
log.info("Re-indexing started");
// reindex all @Indexed entities
for (Class<?> clazz : indexables)
{
reindex(clazz);
}
log.info("Re-indexing finished");
// TODO: this is a global action - not for a specific user
// should have some sort of global status on this one
FacesMessages.instance().add("Re-indexing finished");
}
private void reindex(Class<?> clazz)
{
log.info("Re-indexing {0}", clazz);
try
{
session.purgeAll(clazz);
session.setFlushMode(FlushMode.MANUAL);
session.setCacheMode(CacheMode.IGNORE);
Transaction transaction = session.beginTransaction();
// Scrollable results will avoid loading too many objects in memory
ScrollableResults results = session.createCriteria(clazz).setFetchSize(BATCH_SIZE).scroll(ScrollMode.FORWARD_ONLY);
int index = 0;
while (results.next())
{
index++;
session.index(results.get(0)); // index each element
if (index % BATCH_SIZE == 0)
{
session.flushToIndexes(); // apply changes to indexes
session.clear(); // clear since the queue is processed
}
}
results.close();
transaction.commit();
}
catch (Exception e)
{
log.warn("Unable to index objects of type {0}", e, clazz.getName());
}
}
}
|
package org.shujito.addressbook.test;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.shujito.addressbook.AddressBookApplication;
import org.shujito.addressbook.controller.AddressBookApiController;
import org.shujito.addressbook.controller.exception.LoginException;
import org.shujito.addressbook.controller.exception.ServerException;
import org.shujito.addressbook.model.Contact;
import org.shujito.addressbook.model.Result;
import org.shujito.addressbook.model.Session;
import org.shujito.addressbook.model.User;
import android.test.InstrumentationTestCase;
public class AddressBookServerTests extends InstrumentationTestCase
{
public static final String TAG = AddressBookServerTests.class.getSimpleName();
private AddressBookApiController mController = null;
@Override
protected void setUp() throws Exception
{
super.setUp();
this.mController = new AddressBookApiController(AddressBookApplication.getInstance());
Thread.sleep(250);
}
public void testAsyncLoginMissingUsername()
{
Result result = this.mController.login("", "only password", null);
assertEquals(AddressBookApiController.STATUS_NO_USERNAME, result.status);
assertEquals("Username required", result.message);
}
public void testAsyncLoginMissingPassword()
{
Result result = this.mController.login("only username", "", null);
assertEquals(AddressBookApiController.STATUS_NO_PASSWORD, result.status);
assertEquals("Password required", result.message);
}
public void testAsyncLoginRequiredFields()
{
Result result = this.mController.login("", "", null);
assertEquals(AddressBookApiController.STATUS_NO_USERNAME | AddressBookApiController.STATUS_NO_PASSWORD, result.status);
assertEquals("Username and password required", result.message);
}
public void testAsyncLoginFailed() throws Exception
{
final CountDownLatch latch = new CountDownLatch(1);
Result result = this.mController.login("unregistered username", "bad password", new AddressBookApiController.LoginCallback()
{
public void onLoginSuccess(AddressBookApiController controller, Session login)
{
fail("The test should not get here");
}
public void onLoginFailure(AddressBookApiController controller, Result result)
{
assertEquals("bad credentials", result.message);
assertEquals(401, result.status);
assertEquals(1, latch.getCount());
latch.countDown();
}
});
assertNull(result);
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
assertEquals(0, latch.getCount());
}
public void testAsyncLoginSuccess() throws Exception
{
final CountDownLatch latch = new CountDownLatch(1);
Result result = this.mController.login("shujito", "shujito", new AddressBookApiController.LoginCallback()
{
public void onLoginSuccess(AddressBookApiController controller, Session login)
{
assertNotNull(login.id);
assertNotNull(login.uid);
assertEquals("/users", login.path);
assertEquals(1, latch.getCount());
latch.countDown();
}
public void onLoginFailure(AddressBookApiController controller, Result result)
{
fail("The test should not get here");
}
});
assertNull(result);
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
assertEquals(0, latch.getCount());
}
public void testSyncLoginMissingUsername() throws ServerException
{
try
{
this.mController.login("", "only password");
fail("The test should not reach this line");
}
catch (LoginException le)
{
assertNotNull(le);
assertEquals("Username required", le.getMessage());
}
}
public void testSyncLoginMissingPassword() throws ServerException
{
try
{
this.mController.login("only username", "");
fail("The test should not reach this line");
}
catch (LoginException le)
{
assertNotNull(le);
assertEquals("Password required", le.getMessage());
}
}
public void testSyncLoginRequiredFields() throws ServerException
{
try
{
this.mController.login("", "");
fail("The test should not reach this line");
}
catch (LoginException le)
{
assertNotNull(le);
assertEquals("Username and password required", le.getMessage());
}
}
public void testSyncLoginFailed() throws LoginException
{
try
{
this.mController.login("bad username", "wrong password");
fail("The test should not reach this line");
}
catch (ServerException se)
{
assertNotNull(se);
assertEquals("bad credentials", se.getMessage());
assertEquals(401, se.getStatusCode());
}
}
public void testSyncLoginSuccess() throws Exception
{
Session session = this.mController.login("shujito", "shujito");
assertNotNull(session);
assertNotNull(session.id);
assertNotNull(session.uid);
assertEquals("/users", session.path);
}
public void testListUsers()
{
List<User> usersList = this.mController.getUsers();
assertNotNull(usersList);
}
public void testListContactsWithoutSession()
{
Session dummy = new Session();
List<Contact> contactsList = this.mController.getContacts(dummy);
assertNotNull(contactsList);
assertEquals(0, contactsList.size());
}
public void testUploadEmptyContactWithoutSession()
{
Session dummy = new Session();
Contact emptyContact = new Contact();
try
{
this.mController.uploadContact(dummy, emptyContact);
fail("The test should not reach this line");
}
catch (ServerException ex)
{
assertNotNull(ex);
assertNull(ex.getMessage());
//assertEquals("Sign in first", ex.getMessage());
assertEquals(400, ex.getStatusCode());
assertEquals("is required", ex.getError(Contact.CONTACT_NAME));
assertEquals("is required", ex.getError(Contact.CONTACT_PHONE));
}
}
public void testUploadContactAllFieldsButRequiredWithoutSession()
{
fail();
}
public void testUploadContactRequiredFieldsWithoutSession()
{
fail();
}
public void testListContactsWithSession() throws Exception
{
Session session = this.mController.login("shujito", "shujito");
assertNotNull(session);
assertNotNull(session.id);
assertNotNull(session.uid);
assertEquals("/users", session.path);
List<Contact> contactsList = this.mController.getContacts(session);
assertNotNull(contactsList);
assertTrue(contactsList.size() > 0);
}
public void testUploadEmptyContactWithSession()
{
fail();
}
public void testUploadContactAllFieldsButRequiredWithSession()
{
fail();
}
public void testUploadContactRequiredFieldsWithSession()
{
fail();
}
@Override
protected void tearDown() throws Exception
{
super.tearDown();
}
}
|
package org.skyve.impl.web;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.skyve.EXT;
import org.skyve.impl.persistence.hibernate.AbstractHibernatePersistence;
import org.skyve.impl.persistence.hibernate.dialect.SkyveDialect;
import org.skyve.impl.persistence.hibernate.dialect.SkyveDialect.RDBMS;
import org.skyve.impl.util.UtilImpl;
import org.skyve.metadata.MetaDataException;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
@Component
public class SpringSecurityListener {
@EventListener
@SuppressWarnings("static-method")
public void onAuthenticationFailure(AuthenticationFailureBadCredentialsEvent evt) {
String username = (String) evt.getAuthentication().getPrincipal();
UtilImpl.LOGGER.warning("Login Attempt failed for user " + username);
recordLoginFailure(username);
}
@EventListener
@SuppressWarnings("static-method")
public void onAuthenticationSuccess(AuthenticationSuccessEvent evt) {
String username = ((User) evt.getAuthentication().getPrincipal()).getUsername();
UtilImpl.LOGGER.info("Login Attempt succeeded for user " + username);
resetLoginFailure(username);
}
private static void recordLoginFailure(String username) {
SkyveDialect dialect = AbstractHibernatePersistence.getDialect(UtilImpl.DATA_STORE.getDialectClassName());
RDBMS rdbms = dialect.getRDBMS();
String sql = null;
if (RDBMS.h2.equals(rdbms)) {
sql = "update ADM_SecurityUser set authenticationFailures = ifNull(authenticationFailures, 0) + 1, lastAuthenticationFailure = ? where bizId = ?";
}
else if (RDBMS.mysql.equals(rdbms)) {
sql = "update ADM_SecurityUser set authenticationFailures = ifNull(authenticationFailures, 0) + 1, lastAuthenticationFailure = ? where bizId = ?";
}
else if (RDBMS.sqlserver.equals(rdbms)) {
sql = "update ADM_SecurityUser set authenticationFailures = coalesce(authenticationFailures, 0) + 1, lastAuthenticationFailure = ? where bizId = ?";
}
else if (RDBMS.postgresql.equals(rdbms)) {
sql = "update ADM_SecurityUser set authenticationFailures = coalesce(authenticationFailures, 0) + 1, lastAuthenticationFailure = ? where bizId = ?";
}
else {
UtilImpl.LOGGER.warning("Login Failure for " + username + " was not recorded because " + rdbms + " is not suported in SpringSecurityListener");
return;
}
// NB select and then update by bizId to ensure row lock across all databases.
try (Connection c = EXT.getDataStoreConnection()) {
String bizId = getBizId(username, c);
if (bizId != null) {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
ps.setString(2, bizId);
ps.executeUpdate();
c.commit();
}
catch (Exception e) {
c.rollback();
throw e;
}
}
}
catch (Exception e) {
throw new MetaDataException(e);
}
}
private static void resetLoginFailure(String username) {
String sql = "update ADM_SecurityUser set authenticationFailures = 0, lastAuthenticationFailure = null where bizId = ?";
// NB select and then update by bizId to ensure row lock across all databases.
try (Connection c = EXT.getDataStoreConnection()) {
String bizId = getBizId(username, c);
if (bizId != null) {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, bizId);
ps.executeUpdate();
c.commit();
}
catch (Exception e) {
c.rollback();
throw e;
}
}
}
catch (Exception e) {
throw new MetaDataException(e);
}
}
private static String getBizId(String principalName, Connection c) throws SQLException {
String result = null;
String bizCustomer = null;
String username = null;
if (principalName != null) {
int slashIndex = principalName.indexOf('/');
if (slashIndex > 0) {
bizCustomer = principalName.substring(0, slashIndex);
username = principalName.substring(slashIndex + 1);
}
}
try (PreparedStatement ps = c.prepareStatement("select bizId from ADM_SecurityUser where bizCustomer = ? and userName = ?")) {
ps.setString(1, bizCustomer);
ps.setString(2, username);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
result = rs.getString(1);
}
}
}
return result;
}
}
|
package org.slc.sli.api.config;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.slc.sli.dal.repository.EntityRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Default implementation of the entity definition store
*
* @author nbrown
*
*/
@Component
public class BasicDefinitionStore implements EntityDefinitionStore {
private static final Logger LOG = LoggerFactory.getLogger(BasicDefinitionStore.class);
private Map<String, EntityDefinition> mapping = new HashMap<String, EntityDefinition>();
private Map<EntityDefinition, Collection<AssociationDefinition>> links = new HashMap<EntityDefinition, Collection<AssociationDefinition>>();
@Autowired
private EntityRepository defaultRepo;
@Override
public EntityDefinition lookupByResourceName(String resourceName) {
return mapping.get(resourceName);
}
@Override
public Collection<AssociationDefinition> getLinked(EntityDefinition defn) {
return links.get(defn);
}
@PostConstruct
@Override
public void init() {
EntityDefinition.setDefaultRepo(defaultRepo);
EntityDefinition.addGlobalTreatment(new IdTreatment());
EntityDefinition section = EntityDefinition.makeEntity("section").exposeAs("sections").build();
addDefinition(section);
EntityDefinition student = EntityDefinition.makeEntity("student").exposeAs("students").build();
addDefinition(student);
EntityDefinition school = EntityDefinition.makeEntity("school").exposeAs("schools").build();
addDefinition(school);
AssociationDefinition studentSchoolAssociation = AssociationDefinition.makeAssoc("student-school-association")
.exposeAs("student-school-associations").storeAs("studentschoolassociation")
.from(student, "getStudent", "getStudentsEnrolled").to(school, "getSchool", "getSchoolsAttended")
.calledFromSource("getStudentEnrollments").calledFromTarget("getSchoolEnrollments").build();
addAssocDefinition(studentSchoolAssociation);
// Adding the security collection
EntityDefinition roles = EntityDefinition.makeEntity("roles").storeAs("roles").build();
addDefinition(roles);
addDefinition(EntityDefinition.makeEntity("realm").build());
}
private void add(EntityDefinition defn) {
mapping.put(defn.getResourceName(), defn);
}
private void addDefinition(EntityDefinition defn) {
LOG.debug("adding definition for {}", defn.getResourceName());
add(defn);
links.put(defn, new LinkedHashSet<AssociationDefinition>());
}
private void addAssocDefinition(AssociationDefinition defn) {
LOG.debug("adding assoc for {}", defn.getResourceName());
add(defn);
EntityDefinition sourceEntity = defn.getSourceEntity();
EntityDefinition targetEntity = defn.getTargetEntity();
links.get(sourceEntity).add(defn);
links.get(targetEntity).add(defn);
mapping.get(sourceEntity.getResourceName()).addLinkedAssoc(defn);
mapping.get(targetEntity.getResourceName()).addLinkedAssoc(defn);
}
}
|
package org.yi.happy.archive.file_system;
import java.io.File;
import java.io.IOException;
/**
* Experiment with {@link RealFileSystem}.
*/
public class RealFileSystemPlay {
/**
* experiement with {@link RealFileSystem}.
*
* @param args
* @throws IOException
*/
public static void main1(String[] args) throws IOException {
RealFileSystem fs = new RealFileSystem();
fs.mkdir("a");
/*
* save a temporary file
*/
fs.save("a/a.tmp", new byte[] { 1 });
/*
* rename to a final file
*/
fs.rename("a/a.tmp", "a/a");
/*
* load the final file
*/
System.out.println(fs.load("a/a")[0]);
/*
* save a temporary file
*/
fs.save("a/a.tmp", new byte[] { 2 });
/*
* rename to a final file
*/
fs.rename("a/a.tmp", "a/a");
/*
* load the final file
*/
System.out.println(fs.load("a/a")[0]);
fs.mkdir("a/b");
fs.rename("a/a", "a/b");
}
/**
*
* @param args
*/
public static void main(String[] args) {
File f = new File("test/");
System.out.println(f);
}
}
|
package choco.kernel.common.util.procedure;
import solver.exception.ContradictionException;
import java.io.Serializable;
/**
* A class that permits to execute a embeded "function"
* @param <E>
*/
public interface Procedure<E> extends Serializable {
/**
* Action to execute in a <code>Delta</code> object, within the <code>forEach</code> method.
* @param e object to deal with in the execution
* @throws solver.exception.ContradictionException if a contradiction occurs
*/
void execute(E e) throws ContradictionException;
}
|
package etomica.dcvgcmd;
import etomica.atom.IAtom;
import etomica.box.Box;
import etomica.potential.IPotential1;
import etomica.space.Boundary;
import etomica.space.Vector;
/**
* This acts as a 1-body WCA potential wall perpendicular to the z direction
* with a hole. The size and placement of the hole can be set. The interior
* of the hole is discontinuous; an atom in the hole that attempts to move out
* the hole and into the wall will experience a discontinuity.
*/
public class P1WCAWall implements IPotential1 {
private double sigma, sigma2;
private double epsilon;
private double cutoff, cutoff2;
private final Boundary boundary;
public P1WCAWall(Box box, double sigma, double epsilon) {
boundary = box.getBoundary();
setSigma(sigma);
setEpsilon(epsilon);
}
public double u(IAtom atom) {
Vector r = atom.getPosition();
double rz = r.getX(2);
double L = boundary.getBoxSize().getX(2);
double Ldz = rz - Math.signum(rz) * L / 2;
double dz2 = Ldz * Ldz;
if (dz2 > cutoff2) return 0;
return energy(dz2);
}
/**
* Computes the force (and adds it to f) for IAtom atom and returns the
* energy due to the field.
*/
public double udu(IAtom atom, Vector f) {
Vector r = atom.getPosition();
double rz = r.getX(2);
double L = boundary.getBoxSize().getX(2);
double dz = rz - L / 2 * Math.signum(rz);
double dz2 = dz * dz;
if (dz2 > cutoff2) return 0.0;
double s2 = sigma2 / dz2;
double s6 = s2 * s2 * s2;
double u = 4 * epsilon * s6 * (s6 - 1.0) + epsilon;
double fz = (48 * epsilon * s6 * (s6 - 0.5)) / dz;
f.setX(2, f.getX(2) + fz);
return u;
}
private double energy(double r2) {
r2 = sigma2 / r2;
double r6 = r2 * r2 * r2;
return 4 * epsilon * r6 * (r6 - 1.0) + epsilon;
}
/**
* Returns the radius.
*
* @return double
*/
public double getSigma() {
return sigma;
}
/**
* Sets the radius.
*
* @param radius The radius to set
*/
public void setSigma(double radius) {
this.sigma = radius;
sigma2 = radius * radius;
cutoff = radius * Math.pow(2, 1. / 6.);
cutoff2 = cutoff * cutoff;
}
/**
* @return Returns the epsilon.
*/
public double getEpsilon() {
return epsilon;
}
/**
* @param epsilon The epsilon to set.
*/
public void setEpsilon(double epsilon) {
this.epsilon = epsilon;
}
}
|
package etomica.util.numerical;
import etomica.util.FunctionDifferentiable;
public class BisectionMethodMinimumBracket {
public BisectionMethodMinimumBracket(){
}
public double[] mnbrak(double[] x, FunctionDifferentiable function){
double GOLD = 1.618034;
double GLIMIT = 100.0;
double TINY = Double.MIN_VALUE;
double denom = 0.0;
double[] newX = x;
newX[0] = x[0];
newX[1] = x[1];
newX[2] = x[2];
double dum=0, u;
double fu, q, r, ulimit;
double fa = function.f(newX[0]);
double fb = function.f(newX[1]);
/*
* Switching the roles of a and b so that able to go
* downhill in the direction from a to b
*/
if (fb > fa){
dum = newX[0];
newX[0] = newX[1];
newX[1] = dum;
dum = fb;
fb = fa;
fa = dum;
}
/*
* Initial guess for newX[2]
* GOLD is 1 plus the fraction of the so-called Golden Mean or Golden Section
* (0.38197 and 0.61893 respectively, if considered from both different ends)
*/
newX[2] = newX[1] + GOLD*(newX[1]-newX[0]);
double fc = function.f(newX[2]);
while (fb >= fc){
r = (newX[1] - newX[0])*(fb - fc);
q = (newX[1] - newX[2])*(fb - fa);
if ((q-r) >=0){
denom = 2*Math.abs(Math.max(Math.abs(q-r), TINY));
} else {
denom = -2*Math.abs(Math.max(Math.abs(q-r), TINY));
}
/*
* Computing u by parabolic extrapolation from newX[0], newX[1], and newX[2]
* TINY is used to avoid division by zero
*/
u = newX[1] - ((newX[1]-newX[2])*q - (newX[1]-newX[0])*r)/denom;
ulimit = newX[1] + GLIMIT*(newX[2]-newX[1]);
if((newX[1]-u)*(u-newX[2]) > 0.0){ // If Parabolic u is between b and c
fu = function.f(u);
if (fu < fc){ // Got a minimum between b and c
newX[0] = newX[1];
newX[1] = u;
fa = fb;
fb = fu;
return newX;
} else if (fu > fb){ // Got a minimum between a and u
newX[2] = u;
fc = fu;
return newX;
}
/*
* When Parabolic fit was not used
* Use default magnification
*/
u = newX[2] + GOLD*(newX[2]-newX[1]);
fu = function.f(u);
} else if ((newX[2]-u)*(u-ulimit) > 0.0){ // If Parabolic fit is between c and its allowed limit
fu = function.f(u);
if (fu < fc){
newX[1] = newX[2];
newX[2] = u;
u = newX[2]+GOLD*(newX[2]-newX[1]);
fb = fc;
fc = fu;
fu = function.f(u);
}
} else if ((u-ulimit)*(ulimit-newX[2]) >= 0.0){ // Limitting parabolic u to the maximum allowed value
u = ulimit;
fu = function.f(u);
} else { // Rejecting parabolic u, use default magnification
u = newX[2]+ GOLD*(newX[2]-newX[1]);
fu = function.f(u);
}
/*
* Eliminating oldest point and continue
*/
newX[0] = newX[1];
newX[1] = newX[2];
newX[2] = u;
fa = fb;
fb = fc;
fc = fu;
}
x[0] = newX[0];
x[1] = newX[1];
x[2] = newX[2];
return newX;
}
}
|
package com.intellij.codeInsight.problems;
import com.intellij.openapi.compiler.CompileScope;
import com.intellij.openapi.compiler.CompilerMessage;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.problems.WolfTheProblemSolver;
import com.intellij.problems.Problem;
import com.intellij.ide.projectView.ProjectViewNode;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
/**
* @author cdr
*/
public class MockWolfTheProblemSolver extends WolfTheProblemSolver {
public boolean isProblemFile(VirtualFile virtualFile) {
return false;
}
public ProblemUpdateTransaction startUpdatingProblemsInScope(CompileScope compileScope) {
return null;
}
public ProblemUpdateTransaction startUpdatingProblemsInScope(VirtualFile virtualFile) {
return new ProblemUpdateTransaction() {
public void addProblem(Problem problem) {
}
public void addProblem(CompilerMessage message) {
}
public void commit() {
}
};
}
public Collection<VirtualFile> getProblemFiles() {
return null;
}
public boolean hasProblemFilesUnder(ProjectViewNode scope) {
return false;
}
public void addProblemListener(ProblemListener listener) {
}
public void removeProblemListener(ProblemListener listener) {
}
public void projectOpened() {
}
public void projectClosed() {
}
@NonNls
@NotNull
public String getComponentName() {
return "mockwolf";
}
public void initComponent() {
}
public void disposeComponent() {
}
}
|
package org.jasig.portal.security.provider;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Vector;
import org.jasig.portal.PropertiesManager;
import org.jasig.portal.security.IAdditionalDescriptor;
import org.jasig.portal.security.IOpaqueCredentials;
import org.jasig.portal.security.IPrincipal;
import org.jasig.portal.security.ISecurityContext;
import org.jasig.portal.security.PortalSecurityException;
import org.jasig.portal.services.LogService;
/**
* <p>This is the basic abstract class for all security contexts that should
* chain to children security contexts.</p>
*
* @author Andrew Newman, newman@yale.edu
* @version $Revision$
* @author Don Fracapane (df7@columbia.edu)
* Added a new method named getSubContextNames() that returns an Enumeration of names
* for the subcontexts.
*/
public abstract class ChainingSecurityContext implements ISecurityContext
{
protected static boolean stopWhenAuthenticated = PropertiesManager.getPropertyAsBoolean("org.jasig.portal.security.provider.ChainingSecurityContext.stopWhenAuthenticated");
protected boolean isauth = false;
protected Vector mySubContexts;
protected ChainingPrincipal myPrincipal;
protected ChainingOpaqueCredentials myOpaqueCredentials;
protected IAdditionalDescriptor myAdditionalDescriptor;
protected Comparator myOrder;
public ChainingSecurityContext() {
myPrincipal = new ChainingPrincipal();
myOpaqueCredentials = new ChainingOpaqueCredentials();
myAdditionalDescriptor = new ChainingAdditionalDescriptor();
mySubContexts = new Vector();
}
public IPrincipal getPrincipalInstance() {
if (this.isauth)
return new ChainingPrincipal();
else
return this.myPrincipal;
}
public IOpaqueCredentials getOpaqueCredentialsInstance() {
if (this.isauth)
return new ChainingOpaqueCredentials();
else
return this.myOpaqueCredentials;
}
/**
* We walk the chain of subcontext assigning principals and opaquecredentials
* from the parent. Note that the contexts themselves should resist
* actually performing the assignment if an assignment has already been made
* to either the credentials or the UID.
*/
public synchronized void authenticate() throws PortalSecurityException {
int i;
Enumeration e = mySubContexts.elements();
boolean error = false;
while (e.hasMoreElements()) {
ISecurityContext sctx = ((Entry) e.nextElement()).getCtx();
// The principal and credential are now set for all subcontexts in Authentication
try {
sctx.authenticate();
} catch (Exception ex) {
error = true;
LogService.log(LogService.ERROR, ex);
}
// Stop attempting to authenticate if authenticated and if the property flag is set
if(stopWhenAuthenticated && sctx.isAuthenticated()) {
break;
}
}
// Zero out the actual credentials if it isn't already null
if (this.myOpaqueCredentials.credentialstring != null){
for (i = 0; i < this.myOpaqueCredentials.credentialstring.length; i++)
this.myOpaqueCredentials.credentialstring[i] = 0;
myOpaqueCredentials.credentialstring = null;
}
if (error && !this.isauth) throw new PortalSecurityException("One of the security subcontexts threw an exception");
return;
}
public IPrincipal getPrincipal() {
if (this.isauth)
return this.myPrincipal;
else
return null;
}
public IOpaqueCredentials getOpaqueCredentials() {
if (this.isauth)
return this.myOpaqueCredentials;
else
return null;
}
public IAdditionalDescriptor getAdditionalDescriptor() {
if (this.isauth)
return this.myAdditionalDescriptor;
else
return null;
}
public boolean isAuthenticated() {
return this.isauth;
}
public synchronized ISecurityContext getSubContext(String name) {
for (int i = 0; i < mySubContexts.size(); i++)
{
Entry entry = (Entry) mySubContexts.get(i);
if (entry.getKey() != null && entry.getKey().equals(name))
{
return(entry.getCtx());
}
}
PortalSecurityException ep = new PortalSecurityException("No such subcontext: " + name);
LogService.log(LogService.DEBUG,ep);
return(null);
}
public synchronized boolean doesSubContextExist(String name) {
for (int i = 0; i < mySubContexts.size(); i++)
{
Entry entry = (Entry)mySubContexts.get(i);
if (entry.getKey() != null && entry.getKey().equals(name))
{
return(true);
}
}
return(false);
}
// Return an enumeration of subcontexts by running the vector and
// creating the enumeration. All this so the subcontexts will
// be returned in the order they appeared in the properties file.
public synchronized Enumeration getSubContexts() {
Enumeration e = mySubContexts.elements();
class Adapter implements Enumeration {
Enumeration base;
public Adapter(Enumeration e) {
this.base = e;
}
public boolean hasMoreElements() {
return base.hasMoreElements();
}
public Object nextElement() {
return ((Entry) base.nextElement()).getCtx();
}
}
return new Adapter(e);
}
public synchronized void addSubContext(String name, ISecurityContext ctx)
throws PortalSecurityException {
// Make sure the subcontext does not already exist in the chain
if(doesSubContextExist(name))
{
PortalSecurityException ep = new PortalSecurityException("Subcontext already exists: " + name);
LogService.log(LogService.ERROR,ep);
throw(ep);
}
else
{
mySubContexts.add(new Entry(name, ctx));
}
}
// I 'spose the public class could just implement all of these interfaces
// but I prefer member classes. -ADN
protected class ChainingPrincipal implements IPrincipal {
protected String globalUID;
protected String UID;
protected String FullName;
public String getUID() {
return this.UID;
}
public String getGlobalUID() {
return this.globalUID;
}
// This is supposed to be the person's "human readable" name. We should
// probably do an account lookup at the very least to return this.
public String getFullName() {
return this.FullName;
}
public void setUID(String UID) {
if (this.UID == null)
this.UID = UID;
}
}
protected class ChainingOpaqueCredentials implements IOpaqueCredentials {
public byte[] credentialstring;
// Since we want to explicitly zero our credentials after authenticate,
// copy the credentials here in case a sub-authenticator doesn't want
// to perform the operation immediately.
public void setCredentials(byte[] credentials) {
int i;
if (this.credentialstring == null) {
this.credentialstring = new byte[credentials.length];
for (i = 0; i < credentials.length; i++)
this.credentialstring[i] = credentials[i];
}
}
public void setCredentials(String credentials) {
if (this.credentialstring == null && credentials!=null)
setCredentials(credentials.getBytes());
}
}
// Returns an Enumeration of the names of the subcontexts.
public synchronized Enumeration getSubContextNames() {
Vector scNames = new Vector();
for (int i = 0; i < mySubContexts.size(); i++)
{
Entry entry = (Entry) mySubContexts.get(i);
if (entry.getKey() != null){
scNames.add(entry.getKey());
}
}
return scNames.elements();
}
protected class ChainingAdditionalDescriptor implements IAdditionalDescriptor {
}
// entries in our subcontext list
private static class Entry implements Serializable {
String key;
ISecurityContext ctx;
public Entry(String key, ISecurityContext ctx) {
this.key = key;
this.ctx = ctx;
}
public ISecurityContext getCtx() {
return this.ctx;
}
public String getKey() {
return this.key;
}
}
}
|
package net.milanaleksic.winlauncher;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class WinLauncherUtil {
private static final String CONFIGURATION_FILENAME = ".launcher";
private static final String WIN_LAUNCHER_ENV_PARAM_WAIT_ON_STARTUP = "winLauncherEnvParamWaitOnStartup";
public static FileLock createSingletonApplicationFileLock() {
try {
File configurationFile = new File(CONFIGURATION_FILENAME);
if (!configurationFile.exists())
throw new WinLauncherException("Locking failure - no configuration file found");
FileLock lock = new RandomAccessFile(configurationFile, "rw").getChannel().tryLock();
if (lock == null)
throw new WinLauncherException("Locking failure - probably another application is already holding the lock");
return lock;
} catch (WinLauncherException ignored) {
throw ignored;
} catch (Exception e) {
throw new WinLauncherException("Locking failure - " + e.getMessage(), e);
}
}
public static void closeSingletonApplicationFileLock(FileLock fileLock) {
try {
if (fileLock != null)
fileLock.channel().close();
} catch (IOException e) {
throw new WinLauncherException("Unlocking failure - " + e.getMessage(), e);
}
}
public static void wrapSingletonApplicationLogic(ApplicationLogic applicationLogic) {
FileLock lock = null;
try {
lock = createSingletonApplicationFileLock();
applicationLogic.setFileLock(lock);
applicationLogic.run();
} catch (Exception e) {
applicationLogic.couldNotRun(e);
} finally {
closeSingletonApplicationFileLock(lock);
}
}
private static String getParentDir() {
String absPath = new File("").getAbsolutePath();
if (absPath.charAt(absPath.length() - 1) == File.separatorChar)
absPath = absPath.substring(0, absPath.length() - 1);
return absPath.substring(0, absPath.lastIndexOf(File.separatorChar)) + File.separatorChar;
}
public static void restartApplication(WinLauncherConfig config) {
try {
String dir;
if (new File(config.getExecutable()).exists())
dir = new File("").getAbsolutePath() + File.separator;
else {
dir = getParentDir();
if (!new File(dir + config.getExecutable()).exists())
throw new WinLauncherException("The WinLauncher executable could not be found");
}
String[] arr = getEnvironmentProperties(config);
String params = getParams(config);
String command = dir + config.getExecutable() + params;
Runtime.getRuntime().exec(command, arr, new File(dir));
} catch (Exception e) {
throw new WinLauncherException("Problem while trying to restart application - (Cause: "+e.getMessage()
+").\r\nConfig: "+config, e);
}
}
private static String[] getEnvironmentProperties(WinLauncherConfig config) {
Map<String, String> env = System.getenv();
List<String> list = new ArrayList<String>();
for (Map.Entry<String, String> entry : env.entrySet()) {
list.add(entry.getKey() + "=" + entry.getValue());
}
list.add(WIN_LAUNCHER_ENV_PARAM_WAIT_ON_STARTUP + "=" + config.getPauseTime());
String[] arr = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
arr[i] = list.get(i);
}
return arr;
}
private static String getParams(WinLauncherConfig config) {
StringBuilder params = new StringBuilder();
if (config.isDebug())
params.append(" debug");
if (config.isDebug())
params.append(" nochangedir");
return params.toString();
}
}
|
package org.xtreemfs.osd.stages;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.xtreemfs.common.Capability;
import org.xtreemfs.common.xloc.XLocations;
import org.xtreemfs.foundation.LRUCache;
import org.xtreemfs.foundation.TimeSync;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.MessageType;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader.ErrorResponse;
import org.xtreemfs.foundation.pbrpc.utils.ErrorUtils;
import org.xtreemfs.foundation.pbrpc.utils.ReusableBufferInputStream;
import org.xtreemfs.foundation.util.OutputUtils;
import org.xtreemfs.osd.AdvisoryLock;
import org.xtreemfs.osd.OSDRequest;
import org.xtreemfs.osd.OSDRequestDispatcher;
import org.xtreemfs.osd.OpenFileTable;
import org.xtreemfs.osd.OpenFileTable.OpenFileTableEntry;
import org.xtreemfs.osd.operations.DeleteOperation;
import org.xtreemfs.osd.operations.EventCloseFile;
import org.xtreemfs.osd.operations.EventCreateFileVersion;
import org.xtreemfs.osd.operations.OSDOperation;
import org.xtreemfs.osd.storage.CowPolicy;
import org.xtreemfs.osd.storage.CowPolicy.cowMode;
import org.xtreemfs.osd.storage.MetadataCache;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SnapConfig;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.Lock;
import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceConstants;
import com.google.protobuf.Message;
public class PreprocStage extends Stage {
public final static int STAGEOP_PARSE_AUTH_OFTOPEN = 1;
public final static int STAGEOP_OFT_DELETE = 2;
public final static int STAGEOP_ACQUIRE_LEASE = 3;
public final static int STAGEOP_RETURN_LEASE = 4;
public final static int STAGEOP_VERIFIY_CLEANUP = 5;
public final static int STAGEOP_ACQUIRE_LOCK = 10;
public final static int STAGEOP_CHECK_LOCK = 11;
public final static int STAGEOP_UNLOCK = 12;
public final static int STAGEOP_PING_FILE = 14;
private final static long OFT_CLEAN_INTERVAL = 1000 * 60;
private final static long OFT_OPEN_EXTENSION = 1000 * 30;
private final Map<String, LRUCache<String, Capability>> capCache;
private final OpenFileTable oft;
// time left to next clean op
private long timeToNextOFTclean;
// last check of the OFT
private long lastOFTcheck;
private volatile long numRequests;
/**
* X-Location cache
*/
private final LRUCache<String, XLocations> xLocCache;
private final MetadataCache metadataCache;
private final OSDRequestDispatcher master;
private final boolean ignoreCaps;
private static final int MAX_CAP_CACHE = 20;
/** Creates a new instance of AuthenticationStage */
public PreprocStage(OSDRequestDispatcher master, MetadataCache metadataCache, int maxRequestsQueueLength) {
super("OSD PreProcSt", maxRequestsQueueLength);
capCache = new HashMap();
oft = new OpenFileTable();
xLocCache = new LRUCache<String, XLocations>(10000);
this.master = master;
this.metadataCache = metadataCache;
this.ignoreCaps = master.getConfig().isIgnoreCaps();
}
public void prepareRequest(OSDRequest request, ParseCompleteCallback listener) {
this.enqueueOperation(STAGEOP_PARSE_AUTH_OFTOPEN, new Object[] { request }, null, listener);
}
public static interface ParseCompleteCallback {
public void parseComplete(OSDRequest result, ErrorResponse error);
}
private void doPrepareRequest(StageRequest rq) {
final OSDRequest request = (OSDRequest) rq.getArgs()[0];
final ParseCompleteCallback callback = (ParseCompleteCallback) rq.getCallback();
numRequests++;
if (parseRequest(request) == false)
return;
if (request.getOperation().requiresCapability()) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "STAGEOP AUTH");
ErrorResponse err = processAuthenticate(request);
if (err != null) {
callback.parseComplete(request, err);
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"authentication of request failed: %s", ErrorUtils.formatError(err));
}
return;
}
}
String fileId = request.getFileId();
if (fileId != null) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "STAGEOP OPEN");
CowPolicy cowPolicy = CowPolicy.PolicyNoCow;
// Open file unless it is a DeleteOperation.
if (!(request.getOperation() instanceof DeleteOperation)) {
// check if snasphots are enabled and a write operation is executed;
// this is required to create new snapshots when files open for
// writing are closed, even if the same files are still open for
// reading
boolean write = request.getCapability() != null
&& request.getCapability().getSnapConfig() != SnapConfig.SNAP_CONFIG_SNAPS_DISABLED
&& ((SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber()
| SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_TRUNC.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_WRONLY
.getNumber()) & request.getCapability().getAccessMode()) > 0;
if (oft.contains(fileId)) {
cowPolicy = oft.refresh(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION, write);
} else {
// find out which COW mode to use, depending on the capability
if (request.getCapability() == null
|| request.getCapability().getSnapConfig() == SnapConfig.SNAP_CONFIG_SNAPS_DISABLED)
cowPolicy = CowPolicy.PolicyNoCow;
else
cowPolicy = new CowPolicy(cowMode.COW_ONCE);
oft.openFile(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION, cowPolicy, write);
request.setFileOpen(true);
}
}
request.setCowPolicy(cowPolicy);
}
callback.parseComplete(request, null);
}
public void pingFile(String fileId) {
this.enqueueOperation(STAGEOP_PING_FILE, new Object[] { fileId }, null, null);
}
private void doPingFile(StageRequest m) {
final String fileId = (String) m.getArgs()[0];
// TODO: check if the file was opened for writing
oft.refresh(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION, false);
}
public void checkDeleteOnClose(String fileId, DeleteOnCloseCallback listener) {
this.enqueueOperation(STAGEOP_OFT_DELETE, new Object[] { fileId }, null, listener);
}
public static interface DeleteOnCloseCallback {
public void deleteOnCloseResult(boolean isDeleteOnClose, ErrorResponse error);
}
private void doCheckDeleteOnClose(StageRequest m) {
final String fileId = (String) m.getArgs()[0];
final DeleteOnCloseCallback callback = (DeleteOnCloseCallback) m.getCallback();
final boolean deleteOnClose = oft.contains(fileId);
if (deleteOnClose)
oft.setDeleteOnClose(fileId);
callback.deleteOnCloseResult(deleteOnClose, null);
}
public static interface LockOperationCompleteCallback {
public void parseComplete(Lock result, ErrorResponse error);
}
public void acquireLock(String clientUuid, int pid, String fileId, long offset, long length,
boolean exclusive, OSDRequest request, LockOperationCompleteCallback listener) {
this.enqueueOperation(STAGEOP_ACQUIRE_LOCK, new Object[] { clientUuid, pid, fileId, offset, length,
exclusive }, request, listener);
}
public void doAcquireLock(StageRequest m) {
final LockOperationCompleteCallback callback = (LockOperationCompleteCallback) m.getCallback();
try {
final String clientUuid = (String) m.getArgs()[0];
final Integer pid = (Integer) m.getArgs()[1];
final String fileId = (String) m.getArgs()[2];
final Long offset = (Long) m.getArgs()[3];
final Long length = (Long) m.getArgs()[4];
final Boolean exclusive = (Boolean) m.getArgs()[5];
OpenFileTableEntry e = oft.getEntry(fileId);
if (e == null) {
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "no entry in OFT, programmatic error"));
return;
}
AdvisoryLock l = e.acquireLock(clientUuid, pid, offset, length, exclusive);
if (l != null) {
Lock lock = Lock.newBuilder().setClientPid(l.getClientPid()).setClientUuid(l.getClientUuid()).setLength(l.getLength()).setOffset(l.getOffset()).setExclusive(l.isExclusive()).build();
callback.parseComplete(lock, null);
}
else
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EAGAIN, "conflicting lock"));
} catch (Exception ex) {
callback.parseComplete(null, ErrorUtils.getInternalServerError(ex));
}
}
public void checkLock(String clientUuid, int pid, String fileId, long offset, long length,
boolean exclusive, OSDRequest request, LockOperationCompleteCallback listener) {
this.enqueueOperation(STAGEOP_CHECK_LOCK, new Object[] { clientUuid, pid, fileId, offset, length,
exclusive }, request, listener);
}
public void doCheckLock(StageRequest m) {
final LockOperationCompleteCallback callback = (LockOperationCompleteCallback) m.getCallback();
try {
final String clientUuid = (String) m.getArgs()[0];
final Integer pid = (Integer) m.getArgs()[1];
final String fileId = (String) m.getArgs()[2];
final Long offset = (Long) m.getArgs()[3];
final Long length = (Long) m.getArgs()[4];
final Boolean exclusive = (Boolean) m.getArgs()[5];
OpenFileTableEntry e = oft.getEntry(fileId);
if (e == null) {
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "no entry in OFT, programmatic error"));
return;
}
AdvisoryLock l = e.checkLock(clientUuid, pid, offset, length, exclusive);
Lock lock = Lock.newBuilder().setClientPid(l.getClientPid()).setClientUuid(l.getClientUuid()).setLength(l.getLength()).setOffset(l.getOffset()).setExclusive(l.isExclusive()).build();
callback.parseComplete(lock, null);
} catch (Exception ex) {
callback.parseComplete(null, ErrorUtils.getInternalServerError(ex));
}
}
public void unlock(String clientUuid, int pid, String fileId, OSDRequest request,
LockOperationCompleteCallback listener) {
this.enqueueOperation(STAGEOP_UNLOCK, new Object[] { clientUuid, pid, fileId }, request, listener);
}
public void doUnlock(StageRequest m) {
final LockOperationCompleteCallback callback = (LockOperationCompleteCallback) m.getCallback();
try {
final String clientUuid = (String) m.getArgs()[0];
final Integer pid = (Integer) m.getArgs()[1];
final String fileId = (String) m.getArgs()[2];
OpenFileTableEntry e = oft.getEntry(fileId);
if (e == null) {
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "no entry in OFT, programmatic error"));
return;
}
e.unlock(clientUuid, pid);
callback.parseComplete(null, null);
} catch (Exception ex) {
callback.parseComplete(null, ErrorUtils.getInternalServerError(ex));
}
}
@Override
public void run() {
notifyStarted();
// interval to check the OFT
timeToNextOFTclean = OFT_CLEAN_INTERVAL;
lastOFTcheck = TimeSync.getLocalSystemTime();
while (!quit) {
try {
final StageRequest op = q.poll(timeToNextOFTclean, TimeUnit.MILLISECONDS);
checkOpenFileTable();
if (op == null) {
// Logging.logMessage(Logging.LEVEL_DEBUG,this,"no request
// -- timer only");
continue;
}
processMethod(op);
} catch (InterruptedException ex) {
break;
} catch (Throwable ex) {
notifyCrashed(ex);
break;
}
}
notifyStopped();
}
private void checkOpenFileTable() {
final long tPassed = TimeSync.getLocalSystemTime() - lastOFTcheck;
timeToNextOFTclean = timeToNextOFTclean - tPassed;
// Logging.logMessage(Logging.LEVEL_DEBUG,this,"time to next OFT:
// "+timeToNextOFTclean);
if (timeToNextOFTclean <= 0) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.proc, this, "OpenFileTable clean");
long currentTime = TimeSync.getLocalSystemTime();
// do OFT clean
List<OpenFileTable.OpenFileTableEntry> closedFiles = oft.clean(currentTime);
// Logging.logMessage(Logging.LEVEL_DEBUG,this,"closing
// "+closedFiles.size()+" files");
for (OpenFileTable.OpenFileTableEntry entry : closedFiles) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this,
"send internal close event for %s, deleteOnClose=%b", entry.getFileId(), entry
.isDeleteOnClose());
LRUCache<String, Capability> cachedCaps = capCache.remove(entry.getFileId());
// send close event
OSDOperation closeEvent = master.getInternalEvent(EventCloseFile.class);
closeEvent.startInternalEvent(new Object[] { entry.getFileId(), entry.isDeleteOnClose(),
metadataCache.getFileInfo(entry.getFileId()), entry.getCowPolicy(), cachedCaps });
}
// check if written files need to be closed; if no files were closed
// completely, generate close events w/o discarding the open state
List<OpenFileTable.OpenFileTableEntry> closedWrittenFiles = oft.cleanWritten(currentTime);
if (closedFiles.size() == 0) {
for (OpenFileTable.OpenFileTableEntry entry : closedWrittenFiles) {
OSDOperation createVersionEvent = master.getInternalEvent(EventCreateFileVersion.class);
createVersionEvent.startInternalEvent(new Object[] { entry.getFileId(),
metadataCache.getFileInfo(entry.getFileId()) });
}
}
timeToNextOFTclean = OFT_CLEAN_INTERVAL;
}
lastOFTcheck = TimeSync.getLocalSystemTime();
}
@Override
protected void processMethod(StageRequest m) {
final int requestedMethod = m.getStageMethod();
switch (requestedMethod) {
case STAGEOP_PARSE_AUTH_OFTOPEN:
doPrepareRequest(m);
break;
case STAGEOP_OFT_DELETE:
doCheckDeleteOnClose(m);
break;
case STAGEOP_ACQUIRE_LOCK:
doAcquireLock(m);
break;
case STAGEOP_CHECK_LOCK:
doCheckLock(m);
break;
case STAGEOP_UNLOCK:
doUnlock(m);
break;
case STAGEOP_PING_FILE:
doPingFile(m);
break;
default:
Logging.logMessage(Logging.LEVEL_ERROR, this, "unknown stageop called: %d", requestedMethod);
break;
}
}
private boolean parseRequest(OSDRequest rq) {
RPCHeader hdr = rq.getRpcRequest().getHeader();
if (hdr.getMessageType() != MessageType.RPC_REQUEST) {
rq.sendError(ErrorType.GARBAGE_ARGS, POSIXErrno.POSIX_ERROR_EIO, "expected RPC request message type but got "+hdr.getMessageType());
return false;
}
RPCHeader.RequestHeader rqHdr = hdr.getRequestHeader();
if (rqHdr.getInterfaceId() != OSDServiceConstants.INTERFACE_ID) {
rq.sendError(ErrorType.INVALID_INTERFACE_ID, POSIXErrno.POSIX_ERROR_EIO, "invalid interface id. Maybe wrong service address/port configured?");
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"invalid version requested (requested=%d avail=%d)", rqHdr.getInterfaceId(),
OSDServiceConstants.INTERFACE_ID);
}
return false;
}
// everything ok, find the right operation
OSDOperation op = master.getOperation(rqHdr.getProcId());
if (op == null) {
rq.sendError(ErrorType.INVALID_PROC_ID, POSIXErrno.POSIX_ERROR_EINVAL, "requested operation is not available on this OSD (proc
+ rqHdr.getProcId() + ")");
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"requested operation is not available on this OSD (proc #%d)", rqHdr.getProcId());
}
return false;
}
rq.setOperation(op);
try {
final Message rqPrototype = OSDServiceConstants.getRequestMessage(rqHdr.getProcId());
if (rqPrototype == null) {
rq.setRequestArgs(null);
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "received request with empty message");
} else {
if (rq.getRPCRequest().getMessage() != null) {
rq.setRequestArgs(rqPrototype.newBuilderForType().mergeFrom(new ReusableBufferInputStream(rq.getRPCRequest().getMessage())).build());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "received request of type %s",
rq.getRequestArgs().getClass().getName());
}
} else {
rq.setRequestArgs(rqPrototype.getDefaultInstanceForType());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "received request of type %s (empty message)",
rq.getRequestArgs().getClass().getName());
}
}
}
ErrorResponse err = op.parseRPCMessage(rq);
if (err != null) {
rq.getRpcRequest().sendError(err);
return false;
}
} catch (Throwable ex) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.proc, this, OutputUtils
.stackTraceToString(ex));
rq.getRpcRequest().sendError(ErrorUtils.getInternalServerError(ex));
return false;
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "request parsed: %d", rq
.getRequestId());
}
return true;
}
private ErrorResponse processAuthenticate(OSDRequest rq) {
final Capability rqCap = rq.getCapability();
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this, "capability: %s", rqCap.getXCap().toString().replace('\n', '/'));
}
// check if the capability has valid arguments
if (rqCap.getFileId().length() == 0) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL, "invalid capability. file_id must not be empty");
}
if (rqCap.getEpochNo() < 0) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL, "invalid capability. epoch must not be < 0");
}
if (ignoreCaps)
return null;
// check if the capability is valid
boolean isValid = false;
// look in capCache
LRUCache<String, Capability> cachedCaps = capCache.get(rqCap.getFileId());
if (cachedCaps != null) {
final Capability cap = cachedCaps.get(rqCap.getSignature());
if (cap != null) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this, "using cached cap: %s %s", cap.getFileId(),
cap.getSignature());
}
isValid = !cap.hasExpired();
}
}
if (!isValid) {
isValid = rqCap.isValid();
if (isValid) {
// add to cache
if (cachedCaps == null) {
cachedCaps = new LRUCache<String, Capability>(MAX_CAP_CACHE);
capCache.put(rqCap.getFileId(), cachedCaps);
}
cachedCaps.put(rqCap.getSignature(), rqCap);
}
}
// depending on the result the event listener is sent
if (!isValid) {
if (rqCap.hasExpired())
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability is not valid (timed out)");
if (!rqCap.hasValidSignature())
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability is not valid (invalid signature)");
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability is not valid (unknown cause)");
}
// check if the capability was issued for the requested file
if (!rqCap.getFileId().equals(rq.getFileId())) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability was issued for another file than the one requested");
}
// check if the capability provides sufficient access rights for
// requested operation
if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_READ) {
if ((rqCap.getAccessMode() & (SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_WRONLY.getNumber())) != 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow read access to file " + rqCap.getFileId());
} else if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_WRITE) {
if ((rqCap.getAccessMode() & (SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber()
| SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_WRONLY.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR
.getNumber())) == 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow write access to file " + rqCap.getFileId());
} else if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_TRUNCATE) {
if ((rqCap.getAccessMode() & SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_TRUNC.getNumber()) == 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow truncate access to file " + rqCap.getFileId());
} else if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_UNLINK) {
// TODO: replace numeric flag with constant
if ((rqCap.getAccessMode() & 010000000) == 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow delete access to file " + rqCap.getFileId());
}
return null;
}
public int getNumOpenFiles() {
return oft.getNumOpenFiles();
}
public long getNumRequests() {
return numRequests;
}
}
|
package org.jasig.portal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.portal.services.SequenceGenerator;
/**
* This class provides access to the entity types used by <code>IBasicEntities</code>
* and the classes in <code>org.jasig.portal.groups</code> and
* <code>org.jasig.portal.concurrency</code>.
* <p>
* Each type is associated with an <code>Integer</code> used to represent the
* type in the portal data store. This class translates between the
* <code>Integer</code> and <code>Class</code> values.
*
* @author Dan Ellentuck
* @version $Revision$
* @see org.jasig.portal.IBasicEntity
*/
public class EntityTypes {
private static final Log log = LogFactory.getLog(EntityTypes.class);
private static EntityTypes singleton;
// Caches for EntityType instances.
private Map entityTypesByID;
private Map entityTypesByType;
// Lock for crud operations.
private Object updateLock = new Object();
// Constant strings for ENTITY TYPE table:
private static String ENTITY_TYPE_TABLE = "UP_ENTITY_TYPE";
private static String TYPE_ID_COLUMN = "ENTITY_TYPE_ID";
private static String TYPE_NAME_COLUMN = "ENTITY_TYPE_NAME";
private static String DESCRIPTIVE_NAME_COLUMN = "DESCRIPTIVE_NAME";
// For retrieving all types:
public static int NULL_TYPE_ID = -1;
public static Class GROUP_ENTITY_TYPE = org.jasig.portal.groups.IEntityGroup.class;
public static Class LEAF_ENTITY_TYPE = org.jasig.portal.groups.IEntity.class;
private class EntityType
{
private Class type;
private Integer typeId;
private String descriptiveName;
private EntityType(Class cl, Integer id, String description) {
super();
type = cl; typeId = id; descriptiveName = description;
}
private Class getType() { return type; }
private Integer getTypeId() { return typeId; }
private String getDescriptiveName() { return descriptiveName; }
public String toString() {
String desc = (descriptiveName) == null ? "" : descriptiveName;
return desc + " (" + getTypeId() + ") " + getType().getName();
}
}
/**
* EntityTypes constructor comment.
*/
private EntityTypes()
{
super();
initialize();
}
/**
* Add the new type if it does not already exist.
*/
public static void addIfNecessary(Class newType, String description)
throws java.lang.Exception
{
singleton().addEntityTypeIfNecessary(newType, description);
}
/**
* Add the new type if it does not already exist in the cache.
*/
private void addEntityType(Class newType, String description)
throws java.lang.Exception
{
if ( getEntityTypesByType().get(newType) == null )
{
int nextKey = getNextKey();
EntityType et = new EntityType(newType, new Integer(nextKey), description);
insertEntityType(et);
primAddEntityType(et);
}
}
/**
* Check if we have the type in our cache. If not, re-retrieve. Someone
* might have added it since we last retrieved. If the type is not
* found, try to add it to the store. If the add is not successful,
* re-retrieve again. If the type is still not found, rethrow the
* SQLException. Synchronize on update lock to serialize adds, deletes
* and updates while letting reads proceed.
*/
public void addEntityTypeIfNecessary(Class newType, String description)
throws java.lang.Exception
{
synchronized (updateLock) {
if ( getEntityTypesByType().get(newType) == null )
{
refresh();
if ( getEntityTypesByType().get(newType) == null )
{
try
{
addEntityType(newType, description);
}
catch (Exception ex)
{
refresh();
if ( getEntityTypesByType().get(newType) == null )
{
String errString = "Attempt to add entity type failed: " + ex.getMessage();
log.error( errString);
throw ex;
}
} // end catch
} // end if
} // end if
} // end synchronized
}
/**
* Synchronize on update lock to serialize adds, deletes and updates
* while letting reads proceed.
*/
public void deleteEntityType(Class type) throws SQLException
{
synchronized (updateLock) {
refresh();
EntityType et = (EntityType)getEntityTypesByType().get(type);
if ( et != null )
{
deleteEntityType(et);
primRemoveEntityType(et);
}
}
}
/**
* delete EntityType from the store.
*/
private void deleteEntityType(EntityType et) throws SQLException
{
Connection conn = null;
PreparedStatement ps = null;
try
{
conn = RDBMServices.getConnection();
try
{
ps = conn.prepareStatement(getDeleteEntityTypeSql());
ps.setInt(1, et.getTypeId().intValue());
ps.setString(2, et.getType().getName());
if (log.isDebugEnabled())
log.debug("EntityTypes.deleteEntityType(): " + ps + "(" +
et.getTypeId() + ", " + et.getType() + ")" );
int rc = ps.executeUpdate();
if ( rc != 1 )
{
String errString = "Problem deleting type " + et;
log.error( errString);
throw new SQLException(errString);
}
}
finally
{
try
{
if (ps != null) { ps.close(); }
}
finally
{
RDBMServices.releaseConnection(conn);
}
}
}
catch (java.sql.SQLException sqle)
{
log.error("Exception deleting entity type [" + et + "]", sqle);
throw sqle;
}
}
/**
* @return java.lang.String
*/
private static java.lang.String getAllColumnNames()
{
return TYPE_ID_COLUMN + ", " + TYPE_NAME_COLUMN + ", " + DESCRIPTIVE_NAME_COLUMN;
}
/**
* @return java.util.Iterator
*/
public java.util.Iterator getAllEntityTypeIDs()
{
return entityTypesByID.keySet().iterator();
}
/**
* @return java.util.Iterator
*/
public java.util.Iterator getAllEntityTypes()
{
Collection types = new ArrayList(getEntityTypesByType().size());
for (Iterator i = entityTypesByID.values().iterator(); i.hasNext(); )
{
EntityType et = (EntityType) i.next();
types.add(et.getType());
}
return types.iterator();
}
/**
* @return java.lang.String
*/
private static java.lang.String getDeleteEntityTypeSql()
{
return "DELETE FROM " + ENTITY_TYPE_TABLE + " WHERE " +
TYPE_ID_COLUMN + " = ? AND " + TYPE_NAME_COLUMN + " = ?";
}
/**
* Interface to the entity types cache.
* @return java.lang.String
*/
public static String getDescriptiveName(Class type)
{
return singleton().getDescriptiveNameForType(type);
}
/**
* Interface to the entity types cache.
* @return java.lang.String
*/
public String getDescriptiveNameForType(Class type)
{
EntityType et = (EntityType)getEntityTypesByType().get(type);
return et.getDescriptiveName();
}
/**
* Interface to the entity types cache.
* @return java.lang.Integer
*/
public Integer getEntityIDFromType(Class type)
{
EntityType et = (EntityType)getEntityTypesByType().get(type);
return (et == null) ? null : et.getTypeId();
}
/**
* Interface to the entity types cache.
* @return java.lang.Class
*/
public static Class getEntityType(Integer typeID)
{
return singleton().getEntityTypeFromID(typeID);
}
/**
* Interface to the entity types cache.
* @return java.lang.Class
*/
public Class getEntityTypeFromID(Integer id)
{
EntityType et = (EntityType)getEntityTypesByID().get(id);
return (et == null) ? null : et.getType();
}
/**
* Interface to the entity types cache.
* @return java.lang.Class
*/
public static Integer getEntityTypeID(Class type)
{
return singleton().getEntityIDFromType(type);
}
/**
* @return java.util.Map
*/
private synchronized Map getEntityTypesByID()
{
return entityTypesByID;
}
private Map cloneHashMap(Map m)
{
return ((Map)((HashMap)m).clone());
}
/**
* @return java.util.Map
*/
private synchronized Map getEntityTypesByType()
{
return entityTypesByType;
}
/**
* @return java.lang.String
*/
private static String getInsertEntityTypeSql()
{
return "INSERT INTO " + ENTITY_TYPE_TABLE + " (" + getAllColumnNames() + ") VALUES (?, ?, ?)";
}
/**
* @return int
* @exception java.lang.Exception
*/
private int getNextKey() throws java.lang.Exception
{
return SequenceGenerator.instance().getNextInt(ENTITY_TYPE_TABLE);
}
/**
* @return java.lang.String
*/
private static java.lang.String getSelectEntityTypesSql()
{
return "SELECT " + getAllColumnNames() + " FROM " + ENTITY_TYPE_TABLE;
}
/**
* @return java.lang.String
*/
private static java.lang.String getUpdateEntityTypeSql()
{
return "UPDATE " + ENTITY_TYPE_TABLE + " SET " + DESCRIPTIVE_NAME_COLUMN +
" = ? WHERE " + TYPE_ID_COLUMN + " = ?";
}
/**
* Cache entityTypes.
*/
private void initialize()
{
initializeCaches();
Connection conn = null;
Integer typeID = null;
Class entityType = null;
String description = null;
EntityType et = null;
try
{
conn = RDBMServices.getConnection();
Statement stmnt = conn.createStatement();
try
{
ResultSet rs = stmnt.executeQuery(getSelectEntityTypesSql());
try
{
while (rs.next())
{
typeID = new Integer(rs.getInt(1));
entityType = Class.forName(rs.getString(2));
description = rs.getString(3);
et = new EntityType(entityType, typeID, description);
primAddEntityType(et);
}
}
finally
{ rs.close(); }
}
finally
{ stmnt.close(); }
}
catch (Exception ex)
{ log.error("Exception initializing cache of entity types.", ex); }
finally
{ RDBMServices.releaseConnection(conn); }
}
/**
* Cache entityTypes.
*/
private void initializeCaches()
{
entityTypesByID = new HashMap(10);
entityTypesByType = new HashMap(10);
}
/**
* Cache entityTypes.
*/
private void insertEntityType(EntityType et) throws SQLException
{
Connection conn = null;
PreparedStatement ps = null;
try
{
conn = RDBMServices.getConnection();
try
{
ps = conn.prepareStatement(getInsertEntityTypeSql());
ps.setInt(1, et.getTypeId().intValue());
ps.setString(2, et.getType().getName());
ps.setString(3, et.getDescriptiveName());
if (log.isDebugEnabled())
log.debug("EntityTypes.insertEntityType(): " + ps + "(" +
et.getTypeId() + ", " + et.getType() + ", " +
et.getDescriptiveName() + ")" );
int rc = ps.executeUpdate();
if ( rc != 1 )
{
String errString = "Problem adding entity type " + et;
log.error( errString);
throw new SQLException(errString);
}
}
finally
{
try
{
if (ps != null) { ps.close(); }
}
finally
{
RDBMServices.releaseConnection(conn);
}
}
}
catch (java.sql.SQLException sqle)
{
log.error("Error inserting entity type " + et, sqle);
throw sqle;
}
}
/**
* Copy on write to prevent ConcurrentModificationExceptions.
*/
private void primAddEntityType(EntityType et)
{
Map typesByType = cloneHashMap(getEntityTypesByType());
typesByType.put(et.getType(), et);
Map typesByID = cloneHashMap(getEntityTypesByID());
typesByID.put(et.getTypeId(), et);
setEntityTypesByType(typesByType);
setEntityTypesByID(typesByID);
}
/**
* Copy on write to prevent ConcurrentModificationExceptions.
*/
private void primRemoveEntityType(EntityType et)
{
Map typesByType = cloneHashMap(getEntityTypesByType());
typesByType.remove(et.getType());
Map typesByID = cloneHashMap(getEntityTypesByID());
typesByID.remove(et.getTypeId());
setEntityTypesByType(typesByType);
setEntityTypesByID(typesByID);
}
/**
* Interface to the entity types cache.
*/
public static synchronized void refresh()
{
singleton().initialize();
}
public synchronized void setEntityTypesByID(Map m)
{
entityTypesByID = m;
}
public synchronized void setEntityTypesByType(Map m)
{
entityTypesByType = m;
}
/**
* @return org.jasig.portal.groups.EntityTypes
*/
public static synchronized EntityTypes singleton()
{
if ( singleton == null )
{ singleton = new EntityTypes(); }
return singleton;
}
/**
* Synchronize on update lock to serialize adds, deletes and updates
* while letting reads proceed.
*/
public void updateEntityType(Class type, String newDescription) throws Exception
{
synchronized (updateLock) {
refresh();
EntityType et = (EntityType)getEntityTypesByType().get(type);
if ( et == null )
{
addEntityType(type, newDescription);
}
else
{
et.descriptiveName = newDescription;
updateEntityType(et);
primAddEntityType(et);
}
}
}
/**
* Cache entityTypes.
*/
private void updateEntityType(EntityType et) throws SQLException
{
Connection conn = null;
PreparedStatement ps = null;
try
{
conn = RDBMServices.getConnection();
try
{
ps = conn.prepareStatement(getUpdateEntityTypeSql());
ps.setString(1, et.getDescriptiveName());
ps.setInt(2, et.getTypeId().intValue());
if (log.isDebugEnabled())
log.debug("EntityTypes.updateEntityType(): " + ps + "(" +
et.getType() + ", " + et.getDescriptiveName() + ", " +
et.getTypeId() + ")" );
int rc = ps.executeUpdate();
if ( rc != 1 )
{
String errString = "Problem updating type " + et;
log.error( errString);
throw new SQLException(errString);
}
}
finally
{
try
{
if (ps != null) { ps.close(); }
}
finally
{
RDBMServices.releaseConnection(conn);
}
}
}
catch (java.sql.SQLException sqle)
{
log.error("Exception updating entity type [" + et + "]", sqle);
throw sqle;
}
}
}
|
package org.broadinstitute.sting.gatk.refdata;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.StingException;
import org.broadinstitute.sting.utils.genotype.DiploidGenotype;
import org.broadinstitute.sting.utils.genotype.Genotype;
import org.broadinstitute.sting.utils.genotype.VariantBackedByGenotype;
import org.broadinstitute.sting.utils.genotype.vcf.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Map;
/**
* @author aaron
* <p/>
* Class RodVCF
* <p/>
* An implementation of the ROD for VCF.
*/
public class RodVCF extends BasicReferenceOrderedDatum implements VariationRod, VariantBackedByGenotype, Iterator<RodVCF> {
// our VCF related information
private VCFReader mReader;
public VCFRecord mCurrentRecord;
public RodVCF(String name) {
super(name);
}
private RodVCF(String name, VCFRecord currentRecord, VCFReader reader) {
super(name);
mCurrentRecord = currentRecord;
mReader = reader;
}
public void assertNotNull() {
if ( mCurrentRecord == null ) {
throw new UnsupportedOperationException("The current Record is null");
}
}
@Override
public boolean parseLine(Object header, String[] parts) throws IOException {
throw new UnsupportedOperationException("RodVCF does not support the parseLine method");
}
public Object initialize(final File source) throws FileNotFoundException {
if ( mReader == null )
mReader = new VCFReader(source);
return mReader.getHeader();
}
@Override
public String toString() {
return (mCurrentRecord != null ? mCurrentRecord.toStringEncoding(mReader.getHeader()) : "");
}
public static RodVCF createIterator(String name, File file) {
RodVCF vcf = new RodVCF(name);
try {
vcf.initialize(file);
} catch (FileNotFoundException e) {
throw new StingException("Unable to find file " + file);
}
return vcf;
}
public boolean hasNonRefAlleleFrequency() {
assertNotNull();
return mCurrentRecord.getNonRefAlleleFrequency() > 0.0;
}
/**
* get the frequency of this variant
*
* @return VariantFrequency with the stored frequency
*/
public double getNonRefAlleleFrequency() {
assertNotNull();
return mCurrentRecord.getNonRefAlleleFrequency();
}
public boolean hasStrandBias() {
assertNotNull();
return this.mCurrentRecord.getInfoValues().containsKey(VCFRecord.STRAND_BIAS_KEY);
}
/**
* get the strand bias of this variant
*
* @return StrandBias with the stored slod
*/
public double getStrandBias() {
return hasStrandBias() ? Double.valueOf(this.mCurrentRecord.getInfoValues().get(VCFRecord.STRAND_BIAS_KEY)) : 0.0;
}
/** @return the VARIANT_TYPE of the current variant */
public VARIANT_TYPE getType() {
assertNotNull();
return mCurrentRecord.getType();
}
public String getID() {
assertNotNull();
return mCurrentRecord.getID();
}
/**
* are we a SNP? If not we're a Indel/deletion
*
* @return true if we're a SNP
*/
public boolean isSNP() {
assertNotNull();
return mCurrentRecord.isSNP();
}
/**
* are we an insertion?
*
* @return true if we are, false otherwise
*/
public boolean isInsertion() {
assertNotNull();
return mCurrentRecord.isInsertion();
}
/**
* are we an insertion?
*
* @return true if we are, false otherwise
*/
public boolean isDeletion() {
assertNotNull();
return mCurrentRecord.isDeletion();
}
@Override
public GenomeLoc getLocation() {
assertNotNull();
return mCurrentRecord.getLocation();
}
/**
* get the reference base(s) at this position
*
* @return the reference base or bases, as a string
*/
public String getReference() {
assertNotNull();
return mCurrentRecord.getReference();
}
/** are we bi-allelic? */
public boolean isBiallelic() {
assertNotNull();
return mCurrentRecord.isBiallelic();
}
/**
* get the -1 * (log 10 of the error value)
*
* @return the log based error estimate
*/
public double getNegLog10PError() {
assertNotNull();
return mCurrentRecord.getNegLog10PError();
}
public double getQual() {
assertNotNull();
return mCurrentRecord.getQual();
}
public boolean hasAlternateAllele() {
assertNotNull();
return mCurrentRecord.hasAlternateAllele();
}
/**
* gets the alternate alleles. This method should return all the alleles present at the location,
* NOT including the reference base. This is returned as a string list with no guarantee ordering
* of alleles (i.e. the first alternate allele is not always going to be the allele with the greatest
* frequency).
*
* @return an alternate allele list
*/
public List<String> getAlternateAlleleList() {
assertNotNull();
return mCurrentRecord.getAlternateAlleleList();
}
/**
* gets the alleles. This method should return all the alleles present at the location,
* including the reference base. The first allele should always be the reference allele, followed
* by an unordered list of alternate alleles.
*
* @return an alternate allele list
*/
public List<String> getAlleleList() {
assertNotNull();
return mCurrentRecord.getAlleleList();
}
/**
* are we truely a variant, given a reference
*
* @return false if we're a variant(indel, delete, SNP, etc), true if we're not
*/
public boolean isReference() {
assertNotNull();
return mCurrentRecord.isReference();
}
/**
* are we an insertion or a deletion? yes, then return true. No? Well, false then.
*
* @return true if we're an insertion or deletion
*/
public boolean isIndel() {
assertNotNull();
return mCurrentRecord.isIndel();
}
public char getAlternativeBaseForSNP() {
assertNotNull();
return mCurrentRecord.getAlternativeBaseForSNP();
}
public char getReferenceForSNP() {
assertNotNull();
return mCurrentRecord.getReferenceForSNP();
}
public boolean hasGenotypeData() {
assertNotNull();
return mCurrentRecord.hasGenotypeData();
}
/**
* get the genotype
*
* @return a map in lexigraphical order of the genotypes
*/
public Genotype getCalledGenotype() {
assertNotNull();
return mCurrentRecord.getCalledGenotype();
}
/**
* get the genotypes
*
* @return a list of the genotypes
*/
public List<Genotype> getGenotypes() {
assertNotNull();
return mCurrentRecord.getGenotypes();
}
/**
* get the genotypes
*
* @return a list of the genotypes
*/
public List<VCFGenotypeRecord> getVCFGenotypeRecords() {
assertNotNull();
return mCurrentRecord.getVCFGenotypeRecords();
}
/**
* do we have the specified genotype? not all backedByGenotypes
* have all the genotype data.
*
* @param x the genotype
*
* @return true if available, false otherwise
*/
public boolean hasGenotype(DiploidGenotype x) {
assertNotNull();
return mCurrentRecord.hasGenotype(x);
}
public String[] getSampleNames() {
assertNotNull();
return mCurrentRecord.getSampleNames();
}
public Map<String, String> getInfoValues() {
assertNotNull();
return mCurrentRecord.getInfoValues();
}
public String[] getFilteringCodes() {
assertNotNull();
return mCurrentRecord.getFilteringCodes();
}
public boolean isFiltered() {
assertNotNull();
return mCurrentRecord.isFiltered();
}
public boolean hasFilteringCodes() {
assertNotNull();
return mCurrentRecord.hasFilteringCodes();
}
public String getFilterString() {
assertNotNull();
return mCurrentRecord.getFilterString();
}
public VCFHeader getHeader() {
return mReader.getHeader();
}
public boolean hasNext() {
return mReader.hasNext();
}
/**
* @return the next element in the iteration.
* @throws NoSuchElementException - iterator has no more elements.
*/
public RodVCF next() {
if (!this.hasNext()) throw new NoSuchElementException("RodVCF next called on iterator with no more elements");
return new RodVCF(name, mReader.next(), mReader);
}
public void remove() {
throw new UnsupportedOperationException("The remove operation is not supported for a VCF rod");
}
}
|
package com.dqc.qlibrary.utils;
import com.apkfuns.logutils.LogUtils;
/**
* Android
*
* @author DragonsQC
*/
public class QLog {
public static void init(boolean configAllowLog, String configTagPrefix) {
LogUtils.getLogConfig()
.configAllowLog(configAllowLog)
.configTagPrefix(configTagPrefix)
.configShowBorders(true);
}
/**
*
* <p/>
* verbose
*
* @param o
*/
public static void v(Object o) {
LogUtils.v(o);
}
/**
*
* <p/>
* debug
*
* @param o
*/
public static void d(Object o) {
LogUtils.d(o);
}
/**
*
* <p/>
* info
*
* @param o
*/
public static void i(Object o) {
LogUtils.i(o);
}
/**
*
* <p/>
* warning
*
* @param o
*/
public static void w(Object o) {
LogUtils.w(o);
}
/**
*
* <p/>
* error
*
* @param o
*/
public static void e(Object o) {
LogUtils.e(o);
}
/**
*
* <p/>
* json
*
* @param json
*/
public static void json(String json) {
LogUtils.json(json);
}
}
|
package net.ossrs.yasea;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.util.Log;
import com.github.faucamp.simplertmp.DefaultRtmpPublisher;
import com.github.faucamp.simplertmp.RtmpHandler;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class SrsFlvMuxer {
private static final int VIDEO_ALLOC_SIZE = 128 * 1024;
private static final int AUDIO_ALLOC_SIZE = 4 * 1024;
private volatile boolean connected = false;
private DefaultRtmpPublisher publisher;
private RtmpHandler mHandler;
private Thread worker;
private final Object txFrameLock = new Object();
private SrsFlv flv = new SrsFlv();
private boolean needToFindKeyFrame = true;
private SrsFlvFrame mVideoSequenceHeader;
private SrsFlvFrame mAudioSequenceHeader;
private SrsAllocator mVideoAllocator = new SrsAllocator(VIDEO_ALLOC_SIZE);
private SrsAllocator mAudioAllocator = new SrsAllocator(AUDIO_ALLOC_SIZE);
private ConcurrentLinkedQueue<SrsFlvFrame> mFlvTagCache = new ConcurrentLinkedQueue<>();
private static final int VIDEO_TRACK = 100;
private static final int AUDIO_TRACK = 101;
private static final String TAG = "SrsFlvMuxer";
/**
* constructor.
* @param handler the rtmp event handler.
*/
public SrsFlvMuxer(RtmpHandler handler) {
mHandler = handler;
publisher = new DefaultRtmpPublisher(handler);
}
/**
* get cached video frame number in publisher
*/
public AtomicInteger getVideoFrameCacheNumber() {
return publisher == null ? null : publisher.getVideoFrameCacheNumber();
}
/**
* set video resolution for publisher
* @param width width
* @param height height
*/
public void setVideoResolution(int width, int height) {
if (publisher != null) {
publisher.setVideoResolution(width, height);
}
}
/**
* Adds a track with the specified format.
* @param format The media format for the track.
* @return The track index for this newly added track.
*/
public int addTrack(MediaFormat format) {
if (format.getString(MediaFormat.KEY_MIME).contentEquals(SrsEncoder.VCODEC)) {
flv.setVideoTrack(format);
return VIDEO_TRACK;
} else {
flv.setAudioTrack(format);
return AUDIO_TRACK;
}
}
private void disconnect() {
try {
publisher.close();
} catch (IllegalStateException e) {
}
connected = false;
mVideoSequenceHeader = null;
mAudioSequenceHeader = null;
Log.i(TAG, "worker: disconnect ok.");
}
private boolean connect(String url) {
if (!connected) {
Log.i(TAG, String.format("worker: connecting to RTMP server by url=%s\n", url));
if (publisher.connect(url)) {
connected = publisher.publish("live");
}
mVideoSequenceHeader = null;
mAudioSequenceHeader = null;
}
return connected;
}
private void sendFlvTag(SrsFlvFrame frame) {
if (!connected || frame == null) {
return;
}
if (frame.isVideo()) {
if (frame.isKeyFrame()) {
Log.i(TAG, String.format("worker: send frame type=%d, dts=%d, size=%dB",
frame.type, frame.dts, frame.flvTag.array().length));
}
publisher.publishVideoData(frame.flvTag.array(), frame.flvTag.size(), frame.dts);
mVideoAllocator.release(frame.flvTag);
} else if (frame.isAudio()) {
publisher.publishAudioData(frame.flvTag.array(), frame.flvTag.size(), frame.dts);
mAudioAllocator.release(frame.flvTag);
}
}
/**
* start to the remote server for remux.
*/
public void start(final String rtmpUrl) {
worker = new Thread(new Runnable() {
@Override
public void run() {
if (!connect(rtmpUrl)) {
return;
}
while (!Thread.interrupted()) {
while (!mFlvTagCache.isEmpty()) {
SrsFlvFrame frame = mFlvTagCache.poll();
if (frame.isSequenceHeader()) {
if (frame.isVideo()) {
mVideoSequenceHeader = frame;
sendFlvTag(mVideoSequenceHeader);
} else if (frame.isAudio()) {
mAudioSequenceHeader = frame;
sendFlvTag(mAudioSequenceHeader);
}
} else {
if (frame.isVideo() && mVideoSequenceHeader != null) {
sendFlvTag(frame);
} else if (frame.isAudio() && mAudioSequenceHeader != null) {
sendFlvTag(frame);
}
}
}
// Waiting for next frame
synchronized (txFrameLock) {
try {
// isEmpty() may take some time, so we set timeout to detect next frame
txFrameLock.wait(500);
} catch (InterruptedException ie) {
worker.interrupt();
}
}
}
}
});
worker.start();
}
/**
* stop the muxer, disconnect RTMP connection.
*/
public void stop() {
mFlvTagCache.clear();
if (worker != null) {
worker.interrupt();
try {
worker.join();
} catch (InterruptedException e) {
e.printStackTrace();
worker.interrupt();
}
worker = null;
}
flv.reset();
needToFindKeyFrame = true;
Log.i(TAG, "SrsFlvMuxer closed");
new Thread(new Runnable() {
@Override
public void run() {
disconnect();
}
}).start();
}
/**
* send the annexb frame over RTMP.
* @param trackIndex The track index for this sample.
* @param byteBuf The encoded sample.
* @param bufferInfo The buffer information related to this sample.
*/
public void writeSampleData(int trackIndex, ByteBuffer byteBuf, MediaCodec.BufferInfo bufferInfo) {
if (bufferInfo.offset > 0) {
Log.w(TAG, String.format("encoded frame %dB, offset=%d pts=%dms",
bufferInfo.size, bufferInfo.offset, bufferInfo.presentationTimeUs / 1000
));
}
if (VIDEO_TRACK == trackIndex) {
flv.writeVideoSample(byteBuf, bufferInfo);
} else {
flv.writeAudioSample(byteBuf, bufferInfo);
}
}
// E.4.3.1 VIDEODATA
// Frame Type UB [4]
// Type of video frame. The following values are defined:
// 1 = key frame (for AVC, a seekable frame)
// 2 = inter frame (for AVC, a non-seekable frame)
// 3 = disposable inter frame (H.263 only)
// 4 = generated key frame (reserved for server use only)
// 5 = video info/command frame
private class SrsCodecVideoAVCFrame
{
// set to the zero to reserved, for array map.
public final static int Reserved = 0;
public final static int Reserved1 = 6;
public final static int KeyFrame = 1;
public final static int InterFrame = 2;
public final static int DisposableInterFrame = 3;
public final static int GeneratedKeyFrame = 4;
public final static int VideoInfoFrame = 5;
}
// AVCPacketType IF CodecID == 7 UI8
// The following values are defined:
// 0 = AVC sequence header
// 1 = AVC NALU
// 2 = AVC end of sequence (lower level NALU sequence ender is
// not required or supported)
private class SrsCodecVideoAVCType
{
// set to the max value to reserved, for array map.
public final static int Reserved = 3;
public final static int SequenceHeader = 0;
public final static int NALU = 1;
public final static int SequenceHeaderEOF = 2;
}
/**
* E.4.1 FLV Tag, page 75
*/
private class SrsCodecFlvTag
{
// set to the zero to reserved, for array map.
public final static int Reserved = 0;
// 8 = audio
public final static int Audio = 8;
// 9 = video
public final static int Video = 9;
// 18 = script data
public final static int Script = 18;
};
// E.4.3.1 VIDEODATA
// CodecID UB [4]
// Codec Identifier. The following values are defined:
// 2 = Sorenson H.263
// 3 = Screen video
// 4 = On2 VP6
// 5 = On2 VP6 with alpha channel
// 6 = Screen video version 2
// 7 = AVC
private class SrsCodecVideo
{
// set to the zero to reserved, for array map.
public final static int Reserved = 0;
public final static int Reserved1 = 1;
public final static int Reserved2 = 9;
// for user to disable video, for example, use pure audio hls.
public final static int Disabled = 8;
public final static int SorensonH263 = 2;
public final static int ScreenVideo = 3;
public final static int On2VP6 = 4;
public final static int On2VP6WithAlphaChannel = 5;
public final static int ScreenVideoVersion2 = 6;
public final static int AVC = 7;
}
/**
* the aac object type, for RTMP sequence header
* for AudioSpecificConfig, @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 33
* for audioObjectType, @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 23
*/
private class SrsAacObjectType
{
public final static int Reserved = 0;
// @see @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 23
public final static int AacMain = 1;
public final static int AacLC = 2;
public final static int AacSSR = 3;
// AAC HE = LC+SBR
public final static int AacHE = 5;
// AAC HEv2 = LC+SBR+PS
public final static int AacHEV2 = 29;
}
private class SrsAacProfile
{
public final static int Reserved = 3;
// @see 7.1 Profiles, aac-iso-13818-7.pdf, page 40
public final static int Main = 0;
public final static int LC = 1;
public final static int SSR = 2;
}
/**
* the FLV/RTMP supported audio sample rate.
* Sampling rate. The following values are defined:
* 0 = 5.5 kHz = 5512 Hz
* 1 = 11 kHz = 11025 Hz
* 2 = 22 kHz = 22050 Hz
* 3 = 44 kHz = 44100 Hz
*/
private class SrsCodecAudioSampleRate
{
public final static int R5512 = 5512;
public final static int R11025 = 11025;
public final static int R22050 = 22050;
public final static int R44100 = 44100;
public final static int R32000 = 32000;
public final static int R16000 = 16000;
}
private class SrsAvcNaluType
{
// Unspecified
public final static int Reserved = 0;
// Coded slice of a non-IDR picture slice_layer_without_partitioning_rbsp( )
public final static int NonIDR = 1;
// Coded slice data partition A slice_data_partition_a_layer_rbsp( )
public final static int DataPartitionA = 2;
// Coded slice data partition B slice_data_partition_b_layer_rbsp( )
public final static int DataPartitionB = 3;
// Coded slice data partition C slice_data_partition_c_layer_rbsp( )
public final static int DataPartitionC = 4;
// Coded slice of an IDR picture slice_layer_without_partitioning_rbsp( )
public final static int IDR = 5;
// Supplemental enhancement information (SEI) sei_rbsp( )
public final static int SEI = 6;
// Sequence parameter set seq_parameter_set_rbsp( )
public final static int SPS = 7;
// Picture parameter set pic_parameter_set_rbsp( )
public final static int PPS = 8;
// Access unit delimiter access_unit_delimiter_rbsp( )
public final static int AccessUnitDelimiter = 9;
// End of sequence end_of_seq_rbsp( )
public final static int EOSequence = 10;
// End of stream end_of_stream_rbsp( )
public final static int EOStream = 11;
// Filler data filler_data_rbsp( )
public final static int FilterData = 12;
// Sequence parameter set extension seq_parameter_set_extension_rbsp( )
public final static int SPSExt = 13;
// Prefix NAL unit prefix_nal_unit_rbsp( )
public final static int PrefixNALU = 14;
// Subset sequence parameter set subset_seq_parameter_set_rbsp( )
public final static int SubsetSPS = 15;
// Coded slice of an auxiliary coded picture without partitioning slice_layer_without_partitioning_rbsp( )
public final static int LayerWithoutPartition = 19;
// Coded slice extension slice_layer_extension_rbsp( )
public final static int CodedSliceExt = 20;
}
/**
* the search result for annexb.
*/
private class SrsAnnexbSearch {
public int nb_start_code = 0;
public boolean match = false;
}
/**
* the demuxed tag frame.
*/
private class SrsFlvFrameBytes {
public ByteBuffer data;
public int size;
}
/**
* the muxed flv frame.
*/
private class SrsFlvFrame {
// the tag bytes.
public SrsAllocator.Allocation flvTag;
// the codec type for audio/aac and video/avc for instance.
public int avc_aac_type;
// the frame type, keyframe or not.
public int frame_type;
// the tag type, audio, video or data.
public int type;
// the dts in ms, tbn is 1000.
public int dts;
public boolean isKeyFrame() {
return isVideo() && frame_type == SrsCodecVideoAVCFrame.KeyFrame;
}
public boolean isSequenceHeader() {
return avc_aac_type == 0;
}
public boolean isVideo() {
return type == SrsCodecFlvTag.Video;
}
public boolean isAudio() {
return type == SrsCodecFlvTag.Audio;
}
}
/**
* the raw h.264 stream, in annexb.
*/
private class SrsRawH264Stream {
private final static String TAG = "SrsFlvMuxer";
private SrsAnnexbSearch annexb = new SrsAnnexbSearch();
private SrsFlvFrameBytes seq_hdr = new SrsFlvFrameBytes();
private SrsFlvFrameBytes sps_hdr = new SrsFlvFrameBytes();
private SrsFlvFrameBytes sps_bb = new SrsFlvFrameBytes();
private SrsFlvFrameBytes pps_hdr = new SrsFlvFrameBytes();
private SrsFlvFrameBytes pps_bb = new SrsFlvFrameBytes();
public boolean isSps(SrsFlvFrameBytes frame) {
return frame.size >= 1 && (frame.data.get(0) & 0x1f) == SrsAvcNaluType.SPS;
}
public boolean isPps(SrsFlvFrameBytes frame) {
return frame.size >= 1 && (frame.data.get(0) & 0x1f) == SrsAvcNaluType.PPS;
}
public SrsFlvFrameBytes muxNaluHeader(SrsFlvFrameBytes frame) {
SrsFlvFrameBytes nalu_hdr = new SrsFlvFrameBytes();
nalu_hdr.data = ByteBuffer.allocateDirect(4);
nalu_hdr.size = 4;
// 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
// lengthSizeMinusOne, or NAL_unit_length, always use 4bytes size
int NAL_unit_length = frame.size;
// mux the avc NALU in "ISO Base Media File Format"
// from H.264-AVC-ISO_IEC_14496-15.pdf, page 20
// NALUnitLength
nalu_hdr.data.putInt(NAL_unit_length);
// reset the buffer.
nalu_hdr.data.rewind();
return nalu_hdr;
}
public void muxSequenceHeader(ByteBuffer sps, ByteBuffer pps, int dts, int pts,
ArrayList<SrsFlvFrameBytes> frames) {
// 5bytes sps/pps header:
// configurationVersion, AVCProfileIndication, profile_compatibility,
// AVCLevelIndication, lengthSizeMinusOne
// 3bytes size of sps:
// numOfSequenceParameterSets, sequenceParameterSetLength(2B)
// Nbytes of sps.
// sequenceParameterSetNALUnit
// 3bytes size of pps:
// numOfPictureParameterSets, pictureParameterSetLength
// Nbytes of pps:
// pictureParameterSetNALUnit
// decode the SPS:
// @see: 7.3.2.1.1, H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 62
if (seq_hdr.data == null) {
seq_hdr.data = ByteBuffer.allocate(5);
seq_hdr.size = 5;
}
seq_hdr.data.rewind();
// @see: Annex A Profiles and levels, H.264-AVC-ISO_IEC_14496-10.pdf, page 205
// Baseline profile profile_idc is 66(0x42).
// Main profile profile_idc is 77(0x4d).
// Extended profile profile_idc is 88(0x58).
byte profile_idc = sps.get(1);
//u_int8_t constraint_set = frame[2];
byte level_idc = sps.get(3);
// generate the sps/pps header
// 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
// configurationVersion
seq_hdr.data.put((byte) 0x01);
// AVCProfileIndication
seq_hdr.data.put(profile_idc);
// profile_compatibility
seq_hdr.data.put((byte) 0x00);
// AVCLevelIndication
seq_hdr.data.put(level_idc);
// lengthSizeMinusOne, or NAL_unit_length, always use 4bytes size,
// so we always set it to 0x03.
seq_hdr.data.put((byte) 0x03);
// reset the buffer.
seq_hdr.data.rewind();
frames.add(seq_hdr);
// sps
if (sps_hdr.data == null) {
sps_hdr.data = ByteBuffer.allocate(3);
sps_hdr.size = 3;
}
sps_hdr.data.rewind();
// 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
// numOfSequenceParameterSets, always 1
sps_hdr.data.put((byte) 0x01);
// sequenceParameterSetLength
sps_hdr.data.putShort((short) sps.array().length);
sps_hdr.data.rewind();
frames.add(sps_hdr);
// sequenceParameterSetNALUnit
sps_bb.size = sps.array().length;
sps_bb.data = sps.duplicate();
frames.add(sps_bb);
// pps
if (pps_hdr.data == null) {
pps_hdr.data = ByteBuffer.allocate(3);
pps_hdr.size = 3;
}
pps_hdr.data.rewind();
// 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
// numOfPictureParameterSets, always 1
pps_hdr.data.put((byte) 0x01);
// pictureParameterSetLength
pps_hdr.data.putShort((short) pps.array().length);
pps_hdr.data.rewind();
frames.add(pps_hdr);
// pictureParameterSetNALUnit
pps_bb.size = pps.array().length;
pps_bb.data = pps.duplicate();
frames.add(pps_bb);
}
public SrsAllocator.Allocation muxFlvTag(ArrayList<SrsFlvFrameBytes> frames, int frame_type,
int avc_packet_type, int dts, int pts) {
// for h264 in RTMP video payload, there is 5bytes header:
// 1bytes, FrameType | CodecID
// 1bytes, AVCPacketType
// 3bytes, CompositionTime, the cts.
// @see: E.4.3 Video Tags, video_file_format_spec_v10_1.pdf, page 78
int size = 5;
for (int i = 0; i < frames.size(); i++) {
size += frames.get(i).size;
}
SrsAllocator.Allocation allocation = mVideoAllocator.allocate(size);
// @see: E.4.3 Video Tags, video_file_format_spec_v10_1.pdf, page 78
// Frame Type, Type of video frame.
// CodecID, Codec Identifier.
// set the rtmp header
allocation.put((byte) ((frame_type << 4) | SrsCodecVideo.AVC));
// AVCPacketType
allocation.put((byte)avc_packet_type);
// CompositionTime
// pts = dts + cts, or
// cts = pts - dts.
// where cts is the header in rtmp video packet payload header.
int cts = pts - dts;
allocation.put((byte)(cts >> 16));
allocation.put((byte)(cts >> 8));
allocation.put((byte)cts);
// h.264 raw data.
for (int i = 0; i < frames.size(); i++) {
SrsFlvFrameBytes frame = frames.get(i);
frame.data.get(allocation.array(), allocation.size(), frame.size);
allocation.appendOffset(frame.size);
}
return allocation;
}
private SrsAnnexbSearch searchStartcode(ByteBuffer bb, MediaCodec.BufferInfo bi) {
annexb.match = false;
annexb.nb_start_code = 0;
if (bi.size - 4 > 0) {
if (bb.get(0) == 0x00 && bb.get(1) == 0x00 && bb.get(2) == 0x00 && bb.get(3) == 0x01) {
// match N[00] 00 00 00 01, where N>=0
annexb.match = true;
annexb.nb_start_code = 4;
}
}
return annexb;
}
private SrsAnnexbSearch searchAnnexb(ByteBuffer bb, MediaCodec.BufferInfo bi) {
annexb.match = false;
annexb.nb_start_code = 0;
for (int i = bb.position(); i < bi.size - 3; i++) {
// not match.
if (bb.get(i) != 0x00 || bb.get(i + 1) != 0x00 || bb.get(i + 2) != 0x00) {
continue;
}
// match N[00] 00 00 01, where N>=0
if (bb.get(i + 3) == 0x01) {
annexb.match = true;
annexb.nb_start_code = i + 4 - bb.position();
break;
}
}
return annexb;
}
public SrsFlvFrameBytes demuxAnnexb(ByteBuffer bb, MediaCodec.BufferInfo bi, boolean isOnlyChkHeader) {
SrsFlvFrameBytes tbb = new SrsFlvFrameBytes();
if (bb.position() < bi.size) {
// each frame must prefixed by annexb format.
// about annexb, @see H.264-AVC-ISO_IEC_14496-10.pdf, page 211.
SrsAnnexbSearch tbbsc = isOnlyChkHeader ? searchStartcode(bb, bi) : searchAnnexb(bb, bi);
// tbbsc.nb_start_code always 4 , after 00 00 00 01
if (!tbbsc.match || tbbsc.nb_start_code < 3) {
Log.e(TAG, "annexb not match.");
}
// the start codes.
for (int i = 0; i < tbbsc.nb_start_code; i++) {
bb.get();
}
// find out the frame size.
tbb.data = bb.slice();
tbb.size = bi.size - bb.position();
}
return tbb;
}
}
private class SrsRawAacStreamCodec {
public byte protection_absent;
// SrsAacObjectType
public int aac_object;
public byte sampling_frequency_index;
public byte channel_configuration;
public short frame_length;
public byte sound_format;
public byte sound_rate;
public byte sound_size;
public byte sound_type;
// 0 for sh; 1 for raw data.
public byte aac_packet_type;
public byte[] frame;
}
/**
* remux the annexb to flv tags.
*/
private class SrsFlv {
private MediaFormat videoTrack;
private MediaFormat audioTrack;
private int achannel;
private int asample_rate;
private SrsRawH264Stream avc = new SrsRawH264Stream();
private ArrayList<SrsFlvFrameBytes> ipbs = new ArrayList<>();
private SrsAllocator.Allocation audio_tag;
private SrsAllocator.Allocation video_tag;
private ByteBuffer h264_sps;
private boolean h264_sps_changed;
private ByteBuffer h264_pps;
private boolean h264_pps_changed;
private boolean h264_sps_pps_sent;
private boolean aac_specific_config_got;
public SrsFlv() {
reset();
}
public void reset() {
h264_sps_changed = false;
h264_pps_changed = false;
h264_sps_pps_sent = false;
aac_specific_config_got = false;
}
public void setVideoTrack(MediaFormat format) {
videoTrack = format;
}
public void setAudioTrack(MediaFormat format) {
audioTrack = format;
achannel = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
asample_rate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
}
public void writeAudioSample(final ByteBuffer bb, MediaCodec.BufferInfo bi) {
int pts = (int)(bi.presentationTimeUs / 1000);
int dts = pts;
audio_tag = mAudioAllocator.allocate(bi.size + 2);
byte aac_packet_type = 1; // 1 = AAC raw
if (!aac_specific_config_got) {
// @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf
// AudioSpecificConfig (), page 33
// 1.6.2.1 AudioSpecificConfig
// audioObjectType; 5 bslbf
byte ch = (byte)(bb.get(0) & 0xf8);
// 3bits left.
// samplingFrequencyIndex; 4 bslbf
byte samplingFrequencyIndex = 0x04;
if (asample_rate == SrsCodecAudioSampleRate.R22050) {
samplingFrequencyIndex = 0x07;
} else if (asample_rate == SrsCodecAudioSampleRate.R11025) {
samplingFrequencyIndex = 0x0a;
} else if (asample_rate == SrsCodecAudioSampleRate.R32000) {
samplingFrequencyIndex = 0x05;
} else if (asample_rate == SrsCodecAudioSampleRate.R16000) {
samplingFrequencyIndex = 0x08;
}
ch |= (samplingFrequencyIndex >> 1) & 0x07;
audio_tag.put(ch, 2);
ch = (byte)((samplingFrequencyIndex << 7) & 0x80);
// 7bits left.
// channelConfiguration; 4 bslbf
byte channelConfiguration = 1;
if (achannel == 2) {
channelConfiguration = 2;
}
ch |= (channelConfiguration << 3) & 0x78;
// 3bits left.
// GASpecificConfig(), page 451
// 4.4.1 Decoder configuration (GASpecificConfig)
// frameLengthFlag; 1 bslbf
// dependsOnCoreCoder; 1 bslbf
// extensionFlag; 1 bslbf
audio_tag.put(ch, 3);
aac_specific_config_got = true;
aac_packet_type = 0; // 0 = AAC sequence header
writeAdtsHeader(audio_tag.array(), 4);
audio_tag.appendOffset(7);
} else {
bb.get(audio_tag.array(), 2, bi.size);
audio_tag.appendOffset(bi.size + 2);
}
byte sound_format = 10; // AAC
byte sound_type = 0; // 0 = Mono sound
if (achannel == 2) {
sound_type = 1; // 1 = Stereo sound
}
byte sound_size = 1; // 1 = 16-bit samples
byte sound_rate = 3; // 44100, 22050, 11025, 5512
if (asample_rate == 22050) {
sound_rate = 2;
} else if (asample_rate == 11025) {
sound_rate = 1;
} else if (asample_rate == 5512) {
sound_rate = 0;
}
// for audio frame, there is 1 or 2 bytes header:
// 1bytes, SoundFormat|SoundRate|SoundSize|SoundType
// 1bytes, AACPacketType for SoundFormat == 10, 0 is sequence header.
byte audio_header = (byte) (sound_type & 0x01);
audio_header |= (sound_size << 1) & 0x02;
audio_header |= (sound_rate << 2) & 0x0c;
audio_header |= (sound_format << 4) & 0xf0;
audio_tag.put(audio_header, 0);
audio_tag.put(aac_packet_type, 1);
writeRtmpPacket(SrsCodecFlvTag.Audio, dts, 0, aac_packet_type, audio_tag);
}
private void writeAdtsHeader(byte[] frame, int offset) {
// adts sync word 0xfff (12-bit)
frame[offset] = (byte) 0xff;
frame[offset + 1] = (byte) 0xf0;
// versioin 0 for MPEG-4, 1 for MPEG-2 (1-bit)
frame[offset + 1] |= 0 << 3;
// layer 0 (2-bit)
frame[offset + 1] |= 0 << 1;
// protection absent: 1 (1-bit)
frame[offset + 1] |= 1;
// profile: audio_object_type - 1 (2-bit)
frame[offset + 2] = (SrsAacObjectType.AacLC - 1) << 6;
// sampling frequency index: 4 (4-bit)
frame[offset + 2] |= (4 & 0xf) << 2;
// channel configuration (3-bit)
frame[offset + 2] |= (2 & (byte) 0x4) >> 2;
frame[offset + 3] = (byte) ((2 & (byte) 0x03) << 6);
// original: 0 (1-bit)
frame[offset + 3] |= 0 << 5;
// home: 0 (1-bit)
frame[offset + 3] |= 0 << 4;
frame[offset + 3] |= 0 << 3;
frame[offset + 3] |= 0 << 2;
// frame size (13-bit)
frame[offset + 3] |= ((frame.length - 2) & 0x1800) >> 11;
frame[offset + 4] = (byte) (((frame.length - 2) & 0x7f8) >> 3);
frame[offset + 5] = (byte) (((frame.length - 2) & 0x7) << 5);
// buffer fullness (0x7ff for variable bitrate)
frame[offset + 5] |= (byte) 0x1f;
frame[offset + 6] = (byte) 0xfc;
// number of data block (nb - 1)
frame[offset + 6] |= 0x0;
}
public void writeVideoSample(final ByteBuffer bb, MediaCodec.BufferInfo bi) {
if (bi.size < 4) return;
int pts = (int) (bi.presentationTimeUs / 1000);
int dts = pts;
int type = SrsCodecVideoAVCFrame.InterFrame;
SrsFlvFrameBytes frame = avc.demuxAnnexb(bb, bi, true);
int nal_unit_type = (int)(frame.data.get(0) & 0x1f);
if (nal_unit_type == SrsAvcNaluType.NonIDR)
{
} else if (nal_unit_type == SrsAvcNaluType.IDR)
{
type = SrsCodecVideoAVCFrame.KeyFrame;
} else if (nal_unit_type == SrsAvcNaluType.SPS || nal_unit_type == SrsAvcNaluType.PPS)
{
if (!frame.data.equals(h264_sps)) {
byte[] sps = new byte[frame.size];
frame.data.get(sps);
h264_sps_changed = true;
h264_sps = ByteBuffer.wrap(sps);
writeH264SpsPps(dts, pts);
}
frame = avc.demuxAnnexb(bb, bi, false);
if (!frame.data.equals(h264_pps)) {
byte[] pps = new byte[frame.size];
frame.data.get(pps);
h264_pps_changed = true;
h264_pps = ByteBuffer.wrap(pps);
writeH264SpsPps(dts, pts);
}
return;
} else
return;
ipbs.add(avc.muxNaluHeader(frame));
ipbs.add(frame);
writeH264IpbFrame(ipbs, type, dts, pts);
ipbs.clear();
}
private void writeH264SpsPps(int dts, int pts) {
// when sps or pps changed, update the sequence header,
// for the pps maybe not changed while sps changed.
// so, we must check when each video ts message frame parsed.
if (h264_sps_pps_sent && !h264_sps_changed && !h264_pps_changed) {
return;
}
// when not got sps/pps, wait.
if (h264_pps == null || h264_sps == null) {
return;
}
// h264 raw to h264 packet.
ArrayList<SrsFlvFrameBytes> frames = new ArrayList<>();
avc.muxSequenceHeader(h264_sps, h264_pps, dts, pts, frames);
// h264 packet to flv packet.
int frame_type = SrsCodecVideoAVCFrame.KeyFrame;
int avc_packet_type = SrsCodecVideoAVCType.SequenceHeader;
video_tag = avc.muxFlvTag(frames, frame_type, avc_packet_type, dts, pts);
// the timestamp in rtmp message header is dts.
writeRtmpPacket(SrsCodecFlvTag.Video, dts, frame_type, avc_packet_type, video_tag);
// reset sps and pps.
h264_sps_changed = false;
h264_pps_changed = false;
h264_sps_pps_sent = true;
Log.i(TAG, String.format("flv: h264 sps/pps sent, sps=%dB, pps=%dB",
h264_sps.array().length, h264_pps.array().length));
}
private void writeH264IpbFrame(ArrayList<SrsFlvFrameBytes> frames, int type, int dts, int pts) {
// when sps or pps not sent, ignore the packet.
if (!h264_sps_pps_sent) {
return;
}
video_tag = avc.muxFlvTag(frames, type, SrsCodecVideoAVCType.NALU, dts, pts);
// the timestamp in rtmp message header is dts.
writeRtmpPacket(SrsCodecFlvTag.Video, dts, type, SrsCodecVideoAVCType.NALU, video_tag);
}
private void writeRtmpPacket(int type, int dts, int frame_type, int avc_aac_type, SrsAllocator.Allocation tag) {
SrsFlvFrame frame = new SrsFlvFrame();
frame.flvTag = tag;
frame.type = type;
frame.dts = dts;
frame.frame_type = frame_type;
frame.avc_aac_type = avc_aac_type;
if (frame.isVideo()) {
if (needToFindKeyFrame) {
if (frame.isKeyFrame()) {
needToFindKeyFrame = false;
flvTagCacheAdd(frame);
}
} else {
flvTagCacheAdd(frame);
}
} else if (frame.isAudio()) {
flvTagCacheAdd(frame);
}
}
private void flvTagCacheAdd(SrsFlvFrame frame) {
mFlvTagCache.add(frame);
if (frame.isVideo()) {
getVideoFrameCacheNumber().incrementAndGet();
}
synchronized (txFrameLock) {
txFrameLock.notifyAll();
}
}
}
}
|
package com.jme3.water;
import com.jme3.asset.AssetManager;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.light.DirectionalLight;
import com.jme3.light.Light;
import com.jme3.material.Material;
import com.jme3.math.*;
import com.jme3.post.Filter;
import com.jme3.post.Filter.Pass;
import com.jme3.renderer.Camera;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.Renderer;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.texture.Image.Format;
import com.jme3.texture.Texture.WrapMode;
import com.jme3.texture.Texture2D;
import com.jme3.util.TempVars;
import java.io.IOException;
public class WaterFilter extends Filter {
private Pass reflectionPass;
protected Spatial reflectionScene;
protected ViewPort reflectionView;
private Texture2D normalTexture;
private Texture2D foamTexture;
private Texture2D causticsTexture;
private Texture2D heightTexture;
private Plane plane;
private Camera reflectionCam;
protected Ray ray = new Ray();
private Vector3f targetLocation = new Vector3f();
private ReflectionProcessor reflectionProcessor;
private Matrix4f biasMatrix = new Matrix4f(0.5f, 0.0f, 0.0f, 0.5f,
0.0f, 0.5f, 0.0f, 0.5f,
0.0f, 0.0f, 0.0f, 0.5f,
0.0f, 0.0f, 0.0f, 1.0f);
private Matrix4f textureProjMatrix = new Matrix4f();
private boolean underWater;
private RenderManager renderManager;
private ViewPort viewPort;
private float time = 0;
//properties
private float speed = 1;
private Vector3f lightDirection = new Vector3f(0, -1, 0);
private ColorRGBA lightColor = ColorRGBA.White;
private float waterHeight = 0.0f;
private ColorRGBA waterColor = new ColorRGBA(0.0078f, 0.3176f, 0.5f, 1.0f);
private ColorRGBA deepWaterColor = new ColorRGBA(0.0039f, 0.00196f, 0.145f, 1.0f);
private Vector3f colorExtinction = new Vector3f(5.0f, 20.0f, 30.0f);
private float waterTransparency = 0.1f;
private float maxAmplitude = 1.5f;
private float shoreHardness = 0.1f;
private boolean useFoam = true;
private float foamIntensity = 0.5f;
private float foamHardness = 1.0f;
private Vector3f foamExistence = new Vector3f(0.45f, 4.35f, 1.5f);
private float waveScale = 0.005f;
private float sunScale = 3.0f;
private float shininess = 0.7f;
private Vector2f windDirection = new Vector2f(0.0f, -1.0f);
private int reflectionMapSize = 512;
private boolean useRipples = true;
private float normalScale = 3.0f;
private boolean useHQShoreline = true;
private boolean useSpecular = true;
private boolean useRefraction = true;
private float refractionStrength = 0.0f;
private float refractionConstant = 0.5f;
private float reflectionDisplace = 30;
private float underWaterFogDistance = 120;
private boolean useCaustics = true;
private float causticsIntensity = 0.5f;
//positional attributes
private Vector3f center;
private float radius;
private AreaShape shapeType = AreaShape.Circular;
public enum AreaShape{
Circular,
Square
}
/**
* Create a Water Filter
*/
public WaterFilter() {
super("WaterFilter");
}
public WaterFilter(Node reflectionScene, Vector3f lightDirection) {
super("WaterFilter");
this.reflectionScene = reflectionScene;
this.lightDirection = lightDirection;
}
@Override
protected boolean isRequiresDepthTexture() {
return true;
}
@Override
protected void preFrame(float tpf) {
time = time + (tpf * speed);
material.setFloat("Time", time);
Camera sceneCam = viewPort.getCamera();
biasMatrix.mult(sceneCam.getViewProjectionMatrix(), textureProjMatrix);
material.setMatrix4("TextureProjMatrix", textureProjMatrix);
material.setVector3("CameraPosition", sceneCam.getLocation());
//material.setFloat("WaterHeight", waterHeight);
//update reflection cam
//plane = new Plane(Vector3f.UNIT_Y, new Vector3f(0, waterHeight, 0).dot(Vector3f.UNIT_Y));
//reflectionProcessor.setReflectionClipPlane(plane);
WaterUtils.updateReflectionCam(reflectionCam, plane, sceneCam);
//if we're under water no need to compute reflection
if (sceneCam.getLocation().y >= waterHeight) {
boolean rtb = true;
if (!renderManager.isHandleTranslucentBucket()) {
renderManager.setHandleTranslucentBucket(true);
rtb = false;
}
renderManager.renderViewPort(reflectionView, tpf);
if (!rtb) {
renderManager.setHandleTranslucentBucket(false);
}
renderManager.setCamera(sceneCam, false);
renderManager.getRenderer().setFrameBuffer(viewPort.getOutputFrameBuffer());
underWater = false;
} else {
underWater = true;
}
}
@Override
protected Material getMaterial() {
return material;
}
private DirectionalLight findLight(Node node) {
for (Light light : node.getWorldLightList()) {
if (light instanceof DirectionalLight) {
return (DirectionalLight) light;
}
}
for (Spatial child : node.getChildren()) {
if (child instanceof Node) {
return findLight((Node) child);
}
}
return null;
}
@Override
protected void initFilter(AssetManager manager, RenderManager renderManager, ViewPort vp, int w, int h) {
if (reflectionScene == null) {
reflectionScene = vp.getScenes().get(0);
DirectionalLight l = findLight((Node) reflectionScene);
if (l != null) {
lightDirection = l.getDirection();
}
}
this.renderManager = renderManager;
this.viewPort = vp;
reflectionPass = new Pass();
reflectionPass.init(renderManager.getRenderer(), reflectionMapSize, reflectionMapSize, Format.RGBA8, Format.Depth);
reflectionCam = new Camera(reflectionMapSize, reflectionMapSize);
reflectionView = new ViewPort("reflectionView", reflectionCam);
reflectionView.setClearFlags(true, true, true);
reflectionView.attachScene(reflectionScene);
reflectionView.setOutputFrameBuffer(reflectionPass.getRenderFrameBuffer());
plane = new Plane(Vector3f.UNIT_Y, new Vector3f(0, waterHeight, 0).dot(Vector3f.UNIT_Y));
reflectionProcessor = new ReflectionProcessor(reflectionCam, reflectionPass.getRenderFrameBuffer(), plane);
reflectionView.addProcessor(reflectionProcessor);
normalTexture = (Texture2D) manager.loadTexture("Common/MatDefs/Water/Textures/water_normalmap.dds");
if (foamTexture == null) {
foamTexture = (Texture2D) manager.loadTexture("Common/MatDefs/Water/Textures/foam.jpg");
}
if (causticsTexture == null) {
causticsTexture = (Texture2D) manager.loadTexture("Common/MatDefs/Water/Textures/caustics.jpg");
}
heightTexture = (Texture2D) manager.loadTexture("Common/MatDefs/Water/Textures/heightmap.jpg");
normalTexture.setWrap(WrapMode.Repeat);
foamTexture.setWrap(WrapMode.Repeat);
causticsTexture.setWrap(WrapMode.Repeat);
heightTexture.setWrap(WrapMode.Repeat);
material = new Material(manager, "Common/MatDefs/Water/Water.j3md");
material.setTexture("HeightMap", heightTexture);
material.setTexture("CausticsMap", causticsTexture);
material.setTexture("FoamMap", foamTexture);
material.setTexture("NormalMap", normalTexture);
material.setTexture("ReflectionMap", reflectionPass.getRenderedTexture());
material.setFloat("WaterTransparency", waterTransparency);
material.setFloat("NormalScale", normalScale);
material.setFloat("R0", refractionConstant);
material.setFloat("MaxAmplitude", maxAmplitude);
material.setVector3("LightDir", lightDirection);
material.setColor("LightColor", lightColor);
material.setFloat("ShoreHardness", shoreHardness);
material.setFloat("RefractionStrength", refractionStrength);
material.setFloat("WaveScale", waveScale);
material.setVector3("FoamExistence", foamExistence);
material.setFloat("SunScale", sunScale);
material.setVector3("ColorExtinction", colorExtinction);
material.setFloat("Shininess", shininess);
material.setColor("WaterColor", waterColor);
material.setColor("DeepWaterColor", deepWaterColor);
material.setVector2("WindDirection", windDirection);
material.setFloat("FoamHardness", foamHardness);
material.setBoolean("UseRipples", useRipples);
material.setBoolean("UseHQShoreline", useHQShoreline);
material.setBoolean("UseSpecular", useSpecular);
material.setBoolean("UseFoam", useFoam);
material.setBoolean("UseCaustics", useCaustics);
material.setBoolean("UseRefraction", useRefraction);
material.setFloat("ReflectionDisplace", reflectionDisplace);
material.setFloat("FoamIntensity", foamIntensity);
material.setFloat("UnderWaterFogDistance", underWaterFogDistance);
material.setFloat("CausticsIntensity", causticsIntensity);
if (center != null) {
material.setVector3("Center", center);
material.setFloat("Radius", radius * radius);
material.setBoolean("SquareArea", shapeType==AreaShape.Square);
}
}
@Override
protected void cleanUpFilter(Renderer r) {
reflectionPass.cleanup(r);
}
@Override
public void write(JmeExporter ex) throws IOException {
super.write(ex);
OutputCapsule oc = ex.getCapsule(this);
oc.write(speed, "speed", 1f);
oc.write(lightDirection, "lightDirection", new Vector3f(0, -1, 0));
oc.write(lightColor, "lightColor", ColorRGBA.White);
oc.write(waterHeight, "waterHeight", 0.0f);
oc.write(waterColor, "waterColor", new ColorRGBA(0.0078f, 0.3176f, 0.5f, 1.0f));
oc.write(deepWaterColor, "deepWaterColor", new ColorRGBA(0.0039f, 0.00196f, 0.145f, 1.0f));
oc.write(colorExtinction, "colorExtinction", new Vector3f(5.0f, 20.0f, 30.0f));
oc.write(waterTransparency, "waterTransparency", 0.1f);
oc.write(maxAmplitude, "maxAmplitude", 1.5f);
oc.write(shoreHardness, "shoreHardness", 0.1f);
oc.write(useFoam, "useFoam", true);
oc.write(foamIntensity, "foamIntensity", 0.5f);
oc.write(foamHardness, "foamHardness", 1.0f);
oc.write(foamExistence, "foamExistence", new Vector3f(0.45f, 4.35f, 1.5f));
oc.write(waveScale, "waveScale", 0.005f);
oc.write(sunScale, "sunScale", 3.0f);
oc.write(shininess, "shininess", 0.7f);
oc.write(windDirection, "windDirection", new Vector2f(0.0f, -1.0f));
oc.write(reflectionMapSize, "reflectionMapSize", 512);
oc.write(useRipples, "useRipples", true);
oc.write(normalScale, "normalScale", 3.0f);
oc.write(useHQShoreline, "useHQShoreline", true);
oc.write(useSpecular, "useSpecular", true);
oc.write(useRefraction, "useRefraction", true);
oc.write(refractionStrength, "refractionStrength", 0.0f);
oc.write(refractionConstant, "refractionConstant", 0.5f);
oc.write(reflectionDisplace, "reflectionDisplace", 30f);
oc.write(underWaterFogDistance, "underWaterFogDistance", 120f);
oc.write(causticsIntensity, "causticsIntensity", 0.5f);
oc.write(useCaustics, "useCaustics", true);
}
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
InputCapsule ic = im.getCapsule(this);
speed = ic.readFloat("speed", 1f);
lightDirection = (Vector3f) ic.readSavable("lightDirection", new Vector3f(0, -1, 0));
lightColor = (ColorRGBA) ic.readSavable("lightColor", ColorRGBA.White);
waterHeight = ic.readFloat("waterHeight", 0.0f);
waterColor = (ColorRGBA) ic.readSavable("waterColor", new ColorRGBA(0.0078f, 0.3176f, 0.5f, 1.0f));
deepWaterColor = (ColorRGBA) ic.readSavable("deepWaterColor", new ColorRGBA(0.0039f, 0.00196f, 0.145f, 1.0f));
colorExtinction = (Vector3f) ic.readSavable("colorExtinction", new Vector3f(5.0f, 20.0f, 30.0f));
waterTransparency = ic.readFloat("waterTransparency", 0.1f);
maxAmplitude = ic.readFloat("maxAmplitude", 1.5f);
shoreHardness = ic.readFloat("shoreHardness", 0.1f);
useFoam = ic.readBoolean("useFoam", true);
foamIntensity = ic.readFloat("foamIntensity", 0.5f);
foamHardness = ic.readFloat("foamHardness", 1.0f);
foamExistence = (Vector3f) ic.readSavable("foamExistence", new Vector3f(0.45f, 4.35f, 1.5f));
waveScale = ic.readFloat("waveScale", 0.005f);
sunScale = ic.readFloat("sunScale", 3.0f);
shininess = ic.readFloat("shininess", 0.7f);
windDirection = (Vector2f) ic.readSavable("windDirection", new Vector2f(0.0f, -1.0f));
reflectionMapSize = ic.readInt("reflectionMapSize", 512);
useRipples = ic.readBoolean("useRipples", true);
normalScale = ic.readFloat("normalScale", 3.0f);
useHQShoreline = ic.readBoolean("useHQShoreline", true);
useSpecular = ic.readBoolean("useSpecular", true);
useRefraction = ic.readBoolean("useRefraction", true);
refractionStrength = ic.readFloat("refractionStrength", 0.0f);
refractionConstant = ic.readFloat("refractionConstant", 0.5f);
reflectionDisplace = ic.readFloat("reflectionDisplace", 30f);
underWaterFogDistance = ic.readFloat("underWaterFogDistance", 120f);
causticsIntensity = ic.readFloat("causticsIntensity", 0.5f);
useCaustics = ic.readBoolean("useCaustics", true);
}
/**
* gets the height of the water plane
* @return
*/
public float getWaterHeight() {
return waterHeight;
}
/**
* Sets the height of the water plane
* default is 0.0
* @param waterHeight
*/
public void setWaterHeight(float waterHeight) {
this.waterHeight = waterHeight;
this.plane = new Plane(Vector3f.UNIT_Y, waterHeight);
if (material != null) {
material.setFloat("WaterHeight", waterHeight);
}
if (reflectionProcessor != null) {
reflectionProcessor.setReflectionClipPlane(plane);
}
}
/**
* sets the scene to render in the reflection map
* @param reflectionScene
*/
public void setReflectionScene(Spatial reflectionScene) {
this.reflectionScene = reflectionScene;
}
/**
* returns the waterTransparency value
* @return
*/
public float getWaterTransparency() {
return waterTransparency;
}
/**
* Sets how fast will colours fade out. You can also think about this
* values as how clear water is. Therefore use smaller values (eg. 0.05)
* to have crystal clear water and bigger to achieve "muddy" water.
* default is 0.1f
* @param waterTransparency
*/
public void setWaterTransparency(float waterTransparency) {
this.waterTransparency = waterTransparency;
if (material != null) {
material.setFloat("WaterTransparency", waterTransparency);
}
}
/**
* Returns the normal scales applied to the normal map
* @return
*/
public float getNormalScale() {
return normalScale;
}
/**
* Sets the normal scaling factors to apply to the normal map.
* the higher the value the more small ripples will be visible on the waves.
* default is 1.0
* @param normalScale
*/
public void setNormalScale(float normalScale) {
this.normalScale = normalScale;
if (material != null) {
material.setFloat("NormalScale", normalScale);
}
}
/**
* returns the refractoin constant
* @return
*/
public float getRefractionConstant() {
return refractionConstant;
}
/**
* This is a constant related to the index of refraction (IOR) used to compute the fresnel term.
* F = R0 + (1-R0)( 1 - N.V)^5
* where F is the fresnel term, R0 the constant, N the normal vector and V tne view vector.
* It usually depend on the material you are lookinh through (here water).
* Default value is 0.3f
* In practice, the lowest the value and the less the reflection can be seen on water
* @param refractionConstant
*/
public void setRefractionConstant(float refractionConstant) {
this.refractionConstant = refractionConstant;
if (material != null) {
material.setFloat("R0", refractionConstant);
}
}
/**
* return the maximum wave amplitude
* @return
*/
public float getMaxAmplitude() {
return maxAmplitude;
}
/**
* Sets the maximum waves amplitude
* default is 1.0
* @param maxAmplitude
*/
public void setMaxAmplitude(float maxAmplitude) {
this.maxAmplitude = maxAmplitude;
if (material != null) {
material.setFloat("MaxAmplitude", maxAmplitude);
}
}
/**
* gets the light direction
* @return
*/
public Vector3f getLightDirection() {
return lightDirection;
}
/**
* Sets the light direction
* @param lightDirection
*/
public void setLightDirection(Vector3f lightDirection) {
this.lightDirection = lightDirection;
if (material != null) {
material.setVector3("LightDir", lightDirection);
}
}
/**
* returns the light color
* @return
*/
public ColorRGBA getLightColor() {
return lightColor;
}
/**
* Sets the light color to use
* default is white
* @param lightColor
*/
public void setLightColor(ColorRGBA lightColor) {
this.lightColor = lightColor;
if (material != null) {
material.setColor("LightColor", lightColor);
}
}
/**
* Return the shoreHardeness
* @return
*/
public float getShoreHardness() {
return shoreHardness;
}
/**
* The smaller this value is, the softer the transition between
* shore and water. If you want hard edges use very big value.
* Default is 0.1f.
* @param shoreHardness
*/
public void setShoreHardness(float shoreHardness) {
this.shoreHardness = shoreHardness;
if (material != null) {
material.setFloat("ShoreHardness", shoreHardness);
}
}
/**
* returns the foam hardness
* @return
*/
public float getFoamHardness() {
return foamHardness;
}
/**
* Sets the foam hardness : How much the foam will blend with the shore to avoid hard edged water plane.
* Default is 1.0
* @param foamHardness
*/
public void setFoamHardness(float foamHardness) {
this.foamHardness = foamHardness;
if (material != null) {
material.setFloat("FoamHardness", foamHardness);
}
}
/**
* returns the refractionStrenght
* @return
*/
public float getRefractionStrength() {
return refractionStrength;
}
/**
* This value modifies current fresnel term. If you want to weaken
* reflections use bigger value. If you want to empasize them use
* value smaller then 0. Default is 0.0f.
* @param refractionStrength
*/
public void setRefractionStrength(float refractionStrength) {
this.refractionStrength = refractionStrength;
if (material != null) {
material.setFloat("RefractionStrength", refractionStrength);
}
}
/**
* returns the scale factor of the waves height map
* @return
*/
public float getWaveScale() {
return waveScale;
}
/**
* Sets the scale factor of the waves height map
* the smaller the value the bigger the waves
* default is 0.005f
* @param waveScale
*/
public void setWaveScale(float waveScale) {
this.waveScale = waveScale;
if (material != null) {
material.setFloat("WaveScale", waveScale);
}
}
/**
* returns the foam existance vector
* @return
*/
public Vector3f getFoamExistence() {
return foamExistence;
}
/**
* Describes at what depth foam starts to fade out and
* at what it is completely invisible. The third value is at
* what height foam for waves appear (+ waterHeight).
* default is (0.45, 4.35, 1.0);
* @param foamExistence
*/
public void setFoamExistence(Vector3f foamExistence) {
this.foamExistence = foamExistence;
if (material != null) {
material.setVector3("FoamExistence", foamExistence);
}
}
/**
* gets the scale of the sun
* @return
*/
public float getSunScale() {
return sunScale;
}
/**
* Sets the scale of the sun for specular effect
* @param sunScale
*/
public void setSunScale(float sunScale) {
this.sunScale = sunScale;
if (material != null) {
material.setFloat("SunScale", sunScale);
}
}
/**
* Returns the color exctinction vector of the water
* @return
*/
public Vector3f getColorExtinction() {
return colorExtinction;
}
/**
* Return at what depth the refraction color extinct
* the first value is for red
* the second is for green
* the third is for blue
* Play with thos parameters to "trouble" the water
* default is (5.0, 20.0, 30.0f);
* @param colorExtinction
*/
public void setColorExtinction(Vector3f colorExtinction) {
this.colorExtinction = colorExtinction;
if (material != null) {
material.setVector3("ColorExtinction", colorExtinction);
}
}
/**
* Sets the foam texture
* @param foamTexture
*/
public void setFoamTexture(Texture2D foamTexture) {
this.foamTexture = foamTexture;
foamTexture.setWrap(WrapMode.Repeat);
if (material != null) {
material.setTexture("FoamMap", foamTexture);
}
}
/**
* Sets the height texture
* @param heightTexture
*/
public void setHeightTexture(Texture2D heightTexture) {
this.heightTexture = heightTexture;
heightTexture.setWrap(WrapMode.Repeat);
if (material != null) {
material.setTexture("HeightMap", heightTexture);
}
}
/**
* Sets the normal Texture
* @param normalTexture
*/
public void setNormalTexture(Texture2D normalTexture) {
this.normalTexture = normalTexture;
normalTexture.setWrap(WrapMode.Repeat);
if (material != null) {
material.setTexture("NormalMap", normalTexture);
}
}
/**
* return the shininess factor of the water
* @return
*/
public float getShininess() {
return shininess;
}
/**
* Sets the shinines factor of the water
* default is 0.7f
* @param shininess
*/
public void setShininess(float shininess) {
this.shininess = shininess;
if (material != null) {
material.setFloat("Shininess", shininess);
}
}
/**
* retruns the speed of the waves
* @return
*/
public float getSpeed() {
return speed;
}
/**
* Set the speed of the waves (0.0 is still) default is 1.0
* @param speed
*/
public void setSpeed(float speed) {
this.speed = speed;
}
/**
* returns the color of the water
*
* @return
*/
public ColorRGBA getWaterColor() {
return waterColor;
}
/**
* Sets the color of the water
* see setDeepWaterColor for deep water color
* default is (0.0078f, 0.5176f, 0.5f,1.0f) (greenish blue)
* @param waterColor
*/
public void setWaterColor(ColorRGBA waterColor) {
this.waterColor = waterColor;
if (material != null) {
material.setColor("WaterColor", waterColor);
}
}
/**
* returns the deep water color
* @return
*/
public ColorRGBA getDeepWaterColor() {
return deepWaterColor;
}
/**
* sets the deep water color
* see setWaterColor for general color
* default is (0.0039f, 0.00196f, 0.145f,1.0f) (very dark blue)
* @param deepWaterColor
*/
public void setDeepWaterColor(ColorRGBA deepWaterColor) {
this.deepWaterColor = deepWaterColor;
if (material != null) {
material.setColor("DeepWaterColor", deepWaterColor);
}
}
/**
* returns the wind direction
* @return
*/
public Vector2f getWindDirection() {
return windDirection;
}
/**
* sets the wind direction
* the direction where the waves move
* default is (0.0f, -1.0f)
* @param windDirection
*/
public void setWindDirection(Vector2f windDirection) {
this.windDirection = windDirection;
if (material != null) {
material.setVector2("WindDirection", windDirection);
}
}
/**
* returns the size of the reflection map
* @return
*/
public int getReflectionMapSize() {
return reflectionMapSize;
}
/**
* Sets the size of the reflection map
* default is 512, the higher, the better quality, but the slower the effect.
* @param reflectionMapSize
*/
public void setReflectionMapSize(int reflectionMapSize) {
this.reflectionMapSize = reflectionMapSize;
//if reflection pass is already initialized we must update it
if(reflectionPass != null){
reflectionPass.init(renderManager.getRenderer(), reflectionMapSize, reflectionMapSize, Format.RGBA8, Format.Depth);
reflectionCam.resize(reflectionMapSize, reflectionMapSize, true);
reflectionProcessor.setReflectionBuffer(reflectionPass.getRenderFrameBuffer());
material.setTexture("ReflectionMap", reflectionPass.getRenderedTexture());
}
}
/**
* Whether or not the water uses foam
* @return true if the water uses foam
*/
public boolean isUseFoam() {
return useFoam;
}
/**
* set to true to use foam with water
* default true
* @param useFoam
*/
public void setUseFoam(boolean useFoam) {
this.useFoam = useFoam;
if (material != null) {
material.setBoolean("UseFoam", useFoam);
}
}
/**
* sets the texture to use to render caustics on the ground underwater
* @param causticsTexture
*/
public void setCausticsTexture(Texture2D causticsTexture) {
this.causticsTexture = causticsTexture;
if (material != null) {
material.setTexture("causticsMap", causticsTexture);
}
}
/**
* Whether or not caustics are rendered
* @return true if caustics are rendered
*/
public boolean isUseCaustics() {
return useCaustics;
}
/**
* set to true if you want caustics to be rendered on the ground underwater, false otherwise
* @param useCaustics
*/
public void setUseCaustics(boolean useCaustics) {
this.useCaustics = useCaustics;
if (material != null) {
material.setBoolean("UseCaustics", useCaustics);
}
}
/**
* Whether or not the shader is set to use high-quality shoreline.
* @return true if high-quality shoreline is enabled
*/
public boolean isUseHQShoreline() {
return useHQShoreline;
}
public void setUseHQShoreline(boolean useHQShoreline) {
this.useHQShoreline = useHQShoreline;
if (material != null) {
material.setBoolean("UseHQShoreline", useHQShoreline);
}
}
/**
* Whether or not the water uses the refraction
* @return true if the water uses refraction
*/
public boolean isUseRefraction() {
return useRefraction;
}
/**
* set to true to use refraction (default is true)
* @param useRefraction
*/
public void setUseRefraction(boolean useRefraction) {
this.useRefraction = useRefraction;
if (material != null) {
material.setBoolean("UseRefraction", useRefraction);
}
}
/**
* Whether or not the water uses ripples
* @return true if the water is set to use ripples
*/
public boolean isUseRipples() {
return useRipples;
}
/**
*
* Set to true to use ripples
* @param useRipples
*/
public void setUseRipples(boolean useRipples) {
this.useRipples = useRipples;
if (material != null) {
material.setBoolean("UseRipples", useRipples);
}
}
/**
* Whether or not the water is using specular
* @return true if the water is set to use specular
*/
public boolean isUseSpecular() {
return useSpecular;
}
/**
* Set to true to use specular lightings on the water
* @param useSpecular
*/
public void setUseSpecular(boolean useSpecular) {
this.useSpecular = useSpecular;
if (material != null) {
material.setBoolean("UseSpecular", useSpecular);
}
}
/**
* returns the foam intensity
* @return
*/
public float getFoamIntensity() {
return foamIntensity;
}
/**
* sets the foam intensity default is 0.5f
* @param foamIntensity
*/
public void setFoamIntensity(float foamIntensity) {
this.foamIntensity = foamIntensity;
if (material != null) {
material.setFloat("FoamIntensity", foamIntensity);
}
}
/**
* returns the reflection displace
* see {@link #setReflectionDisplace(float) }
* @return
*/
public float getReflectionDisplace() {
return reflectionDisplace;
}
/**
* Sets the reflection displace. define how troubled will look the reflection in the water. default is 30
* @param reflectionDisplace
*/
public void setReflectionDisplace(float reflectionDisplace) {
this.reflectionDisplace = reflectionDisplace;
if (material != null) {
material.setFloat("ReflectionDisplace", reflectionDisplace);
}
}
/**
* Whether or not the camera is under the water level
* @return true if the camera is under the water level
*/
public boolean isUnderWater() {
return underWater;
}
/**
* returns the distance of the fog when under water
* @return
*/
public float getUnderWaterFogDistance() {
return underWaterFogDistance;
}
/**
* sets the distance of the fog when under water.
* default is 120 (120 world units) use a high value to raise the view range under water
* @param underWaterFogDistance
*/
public void setUnderWaterFogDistance(float underWaterFogDistance) {
this.underWaterFogDistance = underWaterFogDistance;
if (material != null) {
material.setFloat("UnderWaterFogDistance", underWaterFogDistance);
}
}
/**
* get the intensity of caustics under water
* @return
*/
public float getCausticsIntensity() {
return causticsIntensity;
}
/**
* sets the intensity of caustics under water. goes from 0 to 1, default is 0.5f
* @param causticsIntensity
*/
public void setCausticsIntensity(float causticsIntensity) {
this.causticsIntensity = causticsIntensity;
if (material != null) {
material.setFloat("CausticsIntensity", causticsIntensity);
}
}
/**
* returns the center of this effect
* @return the center of this effect
*/
public Vector3f getCenter() {
return center;
}
/**
* Set the center of the effect.
* By default the water will extent to the entire scene.
* By setting a center and a radius you can restrain it to a portion of the scene.
* @param center the center of the effect
*/
public void setCenter(Vector3f center) {
this.center = center;
if (material != null) {
material.setVector3("Center", center);
}
}
/**
* returns the radius of this effect
* @return the radius of this effect
*/
public float getRadius() {
return radius;
}
/**
* Set the radius of the effect.
* By default the water will extent to the entire scene.
* By setting a center and a radius you can restrain it to a portion of the scene.
* @param radius the radius of the effect
*/
public void setRadius(float radius) {
this.radius = radius;
if (material != null) {
material.setFloat("Radius", radius * radius);
}
}
/**
* returns the shape of the water area
* @return the shape of the water area
*/
public AreaShape getShapeType() {
return shapeType;
}
/**
* Set the shape of the water area (Circular (default) or Square).
* if the shape is square the radius is considered as an extent.
* @param shapeType the shape type
*/
public void setShapeType(AreaShape shapeType) {
this.shapeType = shapeType;
if (material != null) {
material.setBoolean("SquareArea", shapeType==AreaShape.Square);
}
}
}
|
package com.newsblur.activity;
import android.os.Bundle;
import android.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.Bind;
import com.newsblur.R;
import com.newsblur.fragment.ItemListFragment;
import com.newsblur.fragment.ReadFilterDialogFragment;
import com.newsblur.fragment.StoryOrderDialogFragment;
import com.newsblur.fragment.TextSizeDialogFragment;
import com.newsblur.service.NBSyncService;
import com.newsblur.util.AppConstants;
import com.newsblur.util.FeedSet;
import com.newsblur.util.FeedUtils;
import com.newsblur.util.PrefsUtils;
import com.newsblur.util.ReadFilter;
import com.newsblur.util.ReadFilterChangedListener;
import com.newsblur.util.StateFilter;
import com.newsblur.util.StoryOrder;
import com.newsblur.util.StoryOrderChangedListener;
import com.newsblur.util.UIUtils;
public abstract class ItemsList extends NbActivity implements StoryOrderChangedListener, ReadFilterChangedListener, OnSeekBarChangeListener {
public static final String EXTRA_FEED_SET = "feed_set";
private static final String STORY_ORDER = "storyOrder";
private static final String READ_FILTER = "readFilter";
private static final String DEFAULT_FEED_VIEW = "defaultFeedView";
private static final String BUNDLE_ACTIVE_SEARCH_QUERY = "activeSearchQuery";
protected ItemListFragment itemListFragment;
protected FragmentManager fragmentManager;
@Bind(R.id.itemlist_sync_status) TextView overlayStatusText;
@Bind(R.id.itemlist_search_query) EditText searchQueryInput;
protected StateFilter intelState;
protected FeedSet fs;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
fs = (FeedSet) getIntent().getSerializableExtra(EXTRA_FEED_SET);
intelState = PrefsUtils.getStateFilter(this);
getWindow().setBackgroundDrawableResource(android.R.color.transparent);
setContentView(R.layout.activity_itemslist);
ButterKnife.bind(this);
fragmentManager = getFragmentManager();
if (PrefsUtils.isAutoOpenFirstUnread(this)) {
if (FeedUtils.dbHelper.getUnreadCount(fs, intelState) > 0) {
UIUtils.startReadingActivity(fs, Reading.FIND_FIRST_UNREAD, this);
}
}
if (bundle != null) {
String activeSearchQuery = bundle.getString(BUNDLE_ACTIVE_SEARCH_QUERY);
if (activeSearchQuery != null) {
searchQueryInput.setText(activeSearchQuery);
searchQueryInput.setVisibility(View.VISIBLE);
fs.setSearchQuery(activeSearchQuery);
}
}
searchQueryInput.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
searchQueryInput.setVisibility(View.GONE);
searchQueryInput.setText("");
checkSearchQuery();
return true;
}
if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
checkSearchQuery();
return true;
}
return false;
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (searchQueryInput != null) {
String q = searchQueryInput.getText().toString().trim();
if (q.length() > 0) {
outState.putString(BUNDLE_ACTIVE_SEARCH_QUERY, q);
}
}
}
public FeedSet getFeedSet() {
return this.fs;
}
@Override
protected void onResume() {
super.onResume();
if (NBSyncService.isHousekeepingRunning()) finish();
updateStatusIndicators();
// this is not strictly necessary, since our first refresh with the fs will swap in
// the correct session, but that can be delayed by sync backup, so we try here to
// reduce UI lag, or in case somehow we got redisplayed in a zero-story state
FeedUtils.prepareReadingSession(fs);
// Reading activities almost certainly changed the read/unread state of some stories. Ensure
// we reflect those changes promptly.
itemListFragment.hasUpdated();
}
@Override
protected void onPause() {
super.onPause();
NBSyncService.addRecountCandidates(fs);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (fs.isFilterSaved()) {
menu.findItem(R.id.menu_mark_all_as_read).setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
} else if (item.getItemId() == R.id.menu_mark_all_as_read) {
FeedUtils.markRead(this, fs, null, null, R.array.mark_all_read_options, true);
return true;
} else if (item.getItemId() == R.id.menu_story_order) {
StoryOrder currentValue = getStoryOrder();
StoryOrderDialogFragment storyOrder = StoryOrderDialogFragment.newInstance(currentValue);
storyOrder.show(getFragmentManager(), STORY_ORDER);
return true;
} else if (item.getItemId() == R.id.menu_read_filter) {
ReadFilter currentValue = getReadFilter();
ReadFilterDialogFragment readFilter = ReadFilterDialogFragment.newInstance(currentValue);
readFilter.show(getFragmentManager(), READ_FILTER);
return true;
} else if (item.getItemId() == R.id.menu_textsize) {
TextSizeDialogFragment textSize = TextSizeDialogFragment.newInstance(PrefsUtils.getListTextSize(this), TextSizeDialogFragment.TextSizeType.ListText);
textSize.show(getFragmentManager(), TextSizeDialogFragment.class.getName());
return true;
} else if (item.getItemId() == R.id.menu_search_stories) {
if (searchQueryInput.getVisibility() != View.VISIBLE) {
searchQueryInput.setVisibility(View.VISIBLE);
searchQueryInput.requestFocus();
} else {
searchQueryInput.setVisibility(View.GONE);
checkSearchQuery();
}
}
return false;
}
public StoryOrder getStoryOrder() {
return PrefsUtils.getStoryOrder(this, fs);
}
protected void updateStoryOrderPreference(StoryOrder newOrder) {
PrefsUtils.updateStoryOrder(this, fs, newOrder);
}
protected abstract ReadFilter getReadFilter();
@Override
public void handleUpdate(int updateType) {
if ((updateType & UPDATE_REBUILD) != 0) {
finish();
}
if ((updateType & UPDATE_STATUS) != 0) {
updateStatusIndicators();
}
if ((updateType & UPDATE_STORY) != 0) {
if (itemListFragment != null) {
itemListFragment.hasUpdated();
}
}
}
private void updateStatusIndicators() {
boolean isLoading = NBSyncService.isFeedSetSyncing(this.fs, this);
if (itemListFragment != null) {
itemListFragment.setLoading(isLoading);
}
if (overlayStatusText != null) {
String syncStatus = NBSyncService.getSyncStatusMessage(this, true);
if (syncStatus != null) {
if (AppConstants.VERBOSE_LOG) {
syncStatus = syncStatus + UIUtils.getMemoryUsageDebug(this);
}
overlayStatusText.setText(syncStatus);
overlayStatusText.setVisibility(View.VISIBLE);
} else {
overlayStatusText.setVisibility(View.GONE);
}
}
}
private void checkSearchQuery() {
String oldQuery = fs.getSearchQuery();
String q = searchQueryInput.getText().toString().trim();
if (q.length() < 1) {
q = null;
}
fs.setSearchQuery(q);
if (!TextUtils.equals(q, oldQuery)) {
itemListFragment.resetEmptyState();
itemListFragment.hasUpdated();
itemListFragment.scrollToTop();
NBSyncService.resetReadingSession();
NBSyncService.resetFetchState(fs);
}
}
@Override
public void storyOrderChanged(StoryOrder newValue) {
updateStoryOrderPreference(newValue);
itemListFragment.resetEmptyState();
itemListFragment.hasUpdated();
itemListFragment.scrollToTop();
NBSyncService.resetFetchState(fs);
triggerSync();
}
@Override
public void readFilterChanged(ReadFilter newValue) {
updateReadFilterPreference(newValue);
itemListFragment.resetEmptyState();
itemListFragment.hasUpdated();
itemListFragment.scrollToTop();
NBSyncService.resetFetchState(fs);
triggerSync();
}
// NB: this callback is for the text size slider
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float size = AppConstants.LIST_FONT_SIZE[progress];
PrefsUtils.setListTextSize(this, size);
if (itemListFragment != null) itemListFragment.setTextSize(size);
}
// unused OnSeekBarChangeListener method
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
// unused OnSeekBarChangeListener method
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
protected abstract void updateReadFilterPreference(ReadFilter newValue);
@Override
public void finish() {
if (itemListFragment != null) {
// since v6.0 of Android, the ListView in the fragment likes to crash if the underlying
// dataset changes rapidly as happens when marking-all-read and when the fragment is
// stopping. do a manual hard-stop of the loaders in the fragment before we finish
itemListFragment.stopLoader();
}
super.finish();
/*
* Animate out the list by sliding it to the right and the Main activity in from
* the left. Do this when going back to Main as a subtle hint to the swipe gesture,
* to make the gesture feel more natural, and to override the really ugly transition
* used in some of the newer platforms.
*/
overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right);
}
}
|
package com.datatorrent.stram;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.JarFinder;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.hadoop.yarn.api.protocolrecords.GetClusterMetricsRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetClusterMetricsResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodesRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodesResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetQueueUserAclsInfoRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetQueueUserAclsInfoResponse;
import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationRequest;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.api.records.LocalResourceType;
import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
import org.apache.hadoop.yarn.api.records.NodeReport;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.QueueACL;
import org.apache.hadoop.yarn.api.records.QueueUserACLInfo;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.apache.hadoop.yarn.util.Records;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.api.annotation.ShipContainingJars;
import com.datatorrent.stram.cli.StramClientUtils.ClientRMHelper;
import com.datatorrent.stram.cli.StramClientUtils.YarnClientHelper;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import com.datatorrent.stram.plan.logical.LogicalPlanConfiguration;
import com.esotericsoftware.kryo.Kryo;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
/**
*
* Submits application to YARN<p>
* <br>
*
* @since 0.3.2
*/
@InterfaceAudience.Public
@InterfaceStability.Unstable
public class StramClient
{
private static final Logger LOG = LoggerFactory.getLogger(StramClient.class);
// Configuration
private final Configuration conf;
// Handle to talk to the Resource Manager/Applications Manager
private ClientRMHelper rmClient;
// Application master specific info to register a new Application with RM/ASM
// App master priority
private int amPriority = 0;
// Queue for App master
private String amQueue = "default";
private ApplicationId appId;
private LogicalPlan dag;
public String javaCmd = "${JAVA_HOME}" + "/bin/java";
// log4j.properties file
// if available, add to local resources and set into classpath
private String log4jPropFile = "";
// Timeout threshold for client. Kill app after time interval expires.
private long clientTimeout = 600000;
private static final String DEFAULT_APPNAME = "Stram";
public static final String YARN_APPLICATION_TYPE = "DataTorrent";
/**
* @param args Command line arguments
*/
public static void main(String[] args)
{
boolean result = false;
try {
StramClient client = new StramClient();
LOG.info("Initializing StramClient");
boolean doRun = client.init(args);
if (!doRun) {
System.exit(0);
}
client.startApplication();
result = client.monitorApplication();
}
catch (Throwable t) {
LOG.error("Error running CLient", t);
System.exit(1);
}
if (result) {
LOG.info("Application finished successfully.");
System.exit(0);
}
LOG.error("Application failed!");
System.exit(2);
}
/**
*
* @param conf
* @throws Exception
*/
public StramClient(Configuration conf) throws Exception
{
// Set up the configuration and RPC
this.conf = conf;
}
/**
*
* @throws Exception
*/
public StramClient() throws Exception
{
this(new Configuration());
}
public StramClient(LogicalPlan dag) throws Exception
{
this(new Configuration());
this.dag = dag;
dag.validate();
}
/**
* Helper function to print out usage
*
* @param opts Parsed command line options
*/
private void printUsage(Options opts)
{
new HelpFormatter().printHelp("StramClient", opts);
}
/**
* Parse command line options
*
* @param args Parsed command line options
* @return Whether the init was successful to run the client
*/
public boolean init(String[] args) throws Exception
{
Options opts = new Options();
opts.addOption("appname", true, "Application Name. Default value - Stram");
opts.addOption("priority", true, "Application Priority. Default 0");
opts.addOption("queue", true, "RM Queue in which this application is to be submitted");
opts.addOption("user", true, "User to run the application as");
opts.addOption("timeout", true, "Application timeout in milliseconds");
opts.addOption("master_memory", true, "Amount of memory in MB to be requested to run the application master");
opts.addOption("topologyProperties", true, "Property file defining the dag");
opts.addOption("container_memory", true, "Amount of memory in MB per child container");
opts.addOption("num_containers", true, "No. of containers to use for dag");
opts.addOption("log_properties", true, "log4j.properties file");
opts.addOption("debug", false, "Dump out debug information");
opts.addOption("help", false, "Print usage");
CommandLine cliParser = new GnuParser().parse(opts, args);
if (args.length == 0) {
printUsage(opts);
throw new IllegalArgumentException("No args specified for client to initialize");
}
if (cliParser.hasOption("help")) {
printUsage(opts);
return false;
}
// dag properties
String propertyFileName = cliParser.getOptionValue("topologyProperties");
if (propertyFileName == null) {
throw new IllegalArgumentException("No dag property file specified, exiting.");
}
LOG.info("Configuration: " + propertyFileName);
dag = new LogicalPlan();
Configuration appConf = new Configuration(false);
StreamingApplication app = LogicalPlanConfiguration.create(appConf, propertyFileName);
app.populateDAG(dag, appConf);
dag.validate();
if (cliParser.hasOption("debug")) {
dag.getAttributes().attr(LogicalPlan.DEBUG).set(true);
}
amPriority = Integer.parseInt(cliParser.getOptionValue("priority", String.valueOf(amPriority)));
amQueue = cliParser.getOptionValue("queue", amQueue);
int amMemory = Integer.parseInt(cliParser.getOptionValue("master_memory", ""+dag.getMasterMemoryMB()));
if (amMemory < 0) {
throw new IllegalArgumentException("Invalid memory specified for application master, exiting."
+ " Specified memory=" + amMemory);
}
int containerMemory = Integer.parseInt(cliParser.getOptionValue("container_memory", ""+dag.getContainerMemoryMB()));
int containerCount = Integer.parseInt(cliParser.getOptionValue("num_containers", ""+ dag.getMaxContainerCount()));
if (containerMemory < 0 || dag.getMaxContainerCount() < 1) {
throw new IllegalArgumentException("Invalid no. of containers or container memory specified, exiting."
+ " Specified containerMemory=" + containerMemory
+ ", numContainer=" + containerCount);
}
dag.getAttributes().attr(LogicalPlan.CONTAINERS_MAX_COUNT).set(containerCount);
dag.getAttributes().attr(LogicalPlan.MASTER_MEMORY_MB).set(amMemory);
dag.getAttributes().attr(LogicalPlan.CONTAINER_MEMORY_MB).set(containerMemory);
clientTimeout = Integer.parseInt(cliParser.getOptionValue("timeout", "600000"));
if (clientTimeout == 0) {
clientTimeout = Long.MAX_VALUE;
}
log4jPropFile = cliParser.getOptionValue("log_properties", "");
return true;
}
public static LinkedHashSet<String> findJars(LogicalPlan dag) {
// platform dependencies that are not part of Hadoop and need to be deployed,
// entry below will cause containing jar file from client to be copied to cluster
Class<?>[] defaultClasses = new Class<?>[]{
com.datatorrent.common.util.Slice.class,
com.datatorrent.netlet.EventLoop.class,
com.datatorrent.bufferserver.server.Server.class,
com.datatorrent.stram.StramAppMaster.class,
com.datatorrent.api.StreamCodec.class,
javax.validation.ConstraintViolationException.class,
org.eclipse.jetty.websocket.WebSocketFactory.class,
org.eclipse.jetty.io.nio.SelectorManager.class,
org.eclipse.jetty.http.HttpParser.class,
Kryo.class,
org.apache.bval.jsr303.ApacheValidationProvider.class,
org.apache.bval.BeanValidationContext.class,
org.apache.commons.lang3.ClassUtils.class
};
List<Class<?>> jarClasses = new ArrayList<Class<?>>();
jarClasses.addAll(Arrays.asList(defaultClasses));
for (String className : dag.getClassNames()) {
try {
Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
jarClasses.add(clazz);
}
catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Failed to load class " + className, e);
}
}
for (Class<?> clazz : Lists.newArrayList(jarClasses)) {
// process class and super classes (super does not require deploy annotation)
for (Class<?> c = clazz; c != Object.class && c != null; c = c.getSuperclass()) {
//LOG.debug("checking " + c);
jarClasses.add(c);
// check for annotated dependencies
try {
ShipContainingJars shipJars = c.getAnnotation(ShipContainingJars.class);
if (shipJars != null) {
for (Class<?> depClass : shipJars.classes()) {
jarClasses.add(depClass);
LOG.info("Including {} as deploy dependency of {}", depClass, c);
}
}
}
catch (ArrayStoreException e) {
LOG.error("Failed to process ShipContainingJars annotation for class " + c.getName(), e);
}
}
}
if (dag.isDebug()) {
LOG.info("Deploy dependencies: {}", jarClasses);
}
LinkedHashSet<String> localJarFiles = new LinkedHashSet<String>(); // avoid duplicates
HashMap<String, String> sourceToJar = new HashMap<String, String>();
for (Class<?> jarClass : jarClasses) {
if (jarClass.getProtectionDomain().getCodeSource() == null) {
// system class
continue;
}
//LOG.debug("{} {}", jarClass, jarClass.getProtectionDomain().getCodeSource());
String sourceLocation = jarClass.getProtectionDomain().getCodeSource().getLocation().toString();
String jar = sourceToJar.get(sourceLocation);
if (jar == null) {
// don't create jar file from folders multiple times
jar = JarFinder.getJar(jarClass);
sourceToJar.put(sourceLocation, jar);
LOG.debug("added sourceLocation {} as {}", sourceLocation, jar);
}
if (jar == null) {
throw new AssertionError("Cannot resolve jar file for " + jarClass);
}
localJarFiles.add(jar);
}
String libJarsPath = dag.attrValue(LogicalPlan.LIBRARY_JARS, null);
if (!StringUtils.isEmpty(libJarsPath)) {
String[] libJars = StringUtils.splitByWholeSeparator(libJarsPath, ",");
localJarFiles.addAll(Arrays.asList(libJars));
}
LOG.info("Local jar file dependencies: " + localJarFiles);
return localJarFiles;
}
/**
* Launch application for the dag represented by this client.
*
* @throws IOException
*/
public void startApplication() throws YarnException, IOException
{
// process dependencies
LinkedHashSet<String> localJarFiles = findJars(dag);
// Connect to ResourceManager
YarnClientHelper yarnClient = new YarnClientHelper(conf);
rmClient = new ClientRMHelper(yarnClient);
assert(rmClient.clientRM != null);
// Use ClientRMProtocol handle to general cluster information
GetClusterMetricsRequest clusterMetricsReq = Records.newRecord(GetClusterMetricsRequest.class);
GetClusterMetricsResponse clusterMetricsResp = rmClient.clientRM.getClusterMetrics(clusterMetricsReq);
LOG.info("Got Cluster metric info from ASM"
+ ", numNodeManagers=" + clusterMetricsResp.getClusterMetrics().getNumNodeManagers());
GetClusterNodesRequest clusterNodesReq = Records.newRecord(GetClusterNodesRequest.class);
GetClusterNodesResponse clusterNodesResp = rmClient.clientRM.getClusterNodes(clusterNodesReq);
LOG.info("Got Cluster node info from ASM");
for (NodeReport node : clusterNodesResp.getNodeReports()) {
LOG.info("Got node report from ASM for"
+ ", nodeId=" + node.getNodeId()
+ ", nodeAddress" + node.getHttpAddress()
+ ", nodeRackName" + node.getRackName()
+ ", nodeNumContainers" + node.getNumContainers()
+ ", nodeHealthStatus" + node.getHealthReport());
}
/*
* This is NPE in 2.0-alpha as request needs to provide specific queue name GetQueueInfoRequest queueInfoReq = Records.newRecord(GetQueueInfoRequest.class);
* GetQueueInfoResponse queueInfoResp = rmClient.getQueueInfo(queueInfoReq); QueueInfo queueInfo = queueInfoResp.getQueueInfo(); LOG.info("Queue
* info" + ", queueName=" + queueInfo.getQueueName() + ", queueCurrentCapacity=" + queueInfo.getCurrentCapacity() + ", queueMaxCapacity=" +
* queueInfo.getMaximumCapacity() + ", queueApplicationCount=" + queueInfo.getApplications().size() + ", queueChildQueueCount=" +
* queueInfo.getChildQueues().size());
*/
GetQueueUserAclsInfoRequest queueUserAclsReq = Records.newRecord(GetQueueUserAclsInfoRequest.class);
GetQueueUserAclsInfoResponse queueUserAclsResp = rmClient.clientRM.getQueueUserAcls(queueUserAclsReq);
List<QueueUserACLInfo> listAclInfo = queueUserAclsResp.getUserAclsInfoList();
for (QueueUserACLInfo aclInfo : listAclInfo) {
for (QueueACL userAcl : aclInfo.getUserAcls()) {
LOG.info("User ACL Info for Queue"
+ ", queueName=" + aclInfo.getQueueName()
+ ", userAcl=" + userAcl.name());
}
}
// Get a new application id
GetNewApplicationResponse newApp = getNewApplication();
appId = newApp.getApplicationId();
// Dump out information about cluster capability as seen by the resource manager
int maxMem = newApp.getMaximumResourceCapability().getMemory();
LOG.info("Max mem capabililty of resources in this cluster " + maxMem);
int amMemory = dag.getMasterMemoryMB();
if (amMemory > maxMem) {
LOG.info("AM memory specified above max threshold of cluster. Using max value."
+ ", specified=" + amMemory
+ ", max=" + maxMem);
amMemory = maxMem;
}
dag.getAttributes().attr(LogicalPlan.APPLICATION_NAME).setIfAbsent(DEFAULT_APPNAME);
dag.getAttributes().attr(LogicalPlan.APPLICATION_ID).setIfAbsent(appId.toString());
// Create launch context for app master
LOG.info("Setting up application submission context for ASM");
ApplicationSubmissionContext appContext = Records.newRecord(ApplicationSubmissionContext.class);
// set the application id
appContext.setApplicationId(appId);
// set the application name
appContext.setApplicationName(dag.getAttributes().attr(LogicalPlan.APPLICATION_NAME).get());
appContext.setApplicationType(YARN_APPLICATION_TYPE);
// Set up the container launch context for the application master
ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class);
// Setup security tokens
if (UserGroupInformation.isSecurityEnabled()) {
Credentials credentials = new Credentials();
String tokenRenewer = conf.get(YarnConfiguration.RM_PRINCIPAL);
if (tokenRenewer == null || tokenRenewer.length() == 0) {
throw new IOException(
"Can't get Master Kerberos principal for the RM to use as renewer");
}
// For now, only getting tokens for the default file-system.
FileSystem fs = FileSystem.get(conf);
final Token<?> tokens[] = fs.addDelegationTokens(tokenRenewer, credentials);
if (tokens != null) {
for (Token<?> token : tokens) {
LOG.info("Got dt for " + fs.getUri() + "; " + token);
}
}
DataOutputBuffer dob = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dob);
ByteBuffer fsTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
amContainer.setTokens(fsTokens);
}
/*
// If Kerberos security is enabled get ResourceManager and NameNode delegation tokens.
// Set these tokens on the container so that they are sent as part of application submission.
// This also sets them up for renewal by ResourceManager. The NameNode delegation rmToken
// is also used by ResourceManager to fetch the jars from HDFS and set them up for the
// application master launch.
if (UserGroupInformation.isSecurityEnabled()) {
YarnConfiguration yarnConf = new YarnConfiguration(conf);
InetSocketAddress rmAddress = ConfigUtils.getRMAddress(yarnConf);
//String tokenRenewer = conf.get(YarnConfiguration.RM_PRINCIPAL);
String tokenRenewer = ConfigUtils.getRMUsername(yarnConf);
// Get the ResourceManager delegation rmToken
GetDelegationTokenRequest gdtr = Records.newRecord(GetDelegationTokenRequest.class);
gdtr.setRenewer(tokenRenewer);
GetDelegationTokenResponse gdresp = rmClient.clientRM.getDelegationToken(gdtr);
org.apache.hadoop.yarn.api.records.Token rmDelToken = gdresp.getRMDelegationToken();
Token<RMDelegationTokenIdentifier> rmToken = ConverterUtils.convertFromYarn(rmDelToken, rmAddress);
// Get the NameNode delegation rmToken
FileSystem dfs = FileSystem.get(conf);
Token<?> hdfsToken = dfs.getDelegationToken(tokenRenewer);
// Setup the credentials to serialize the tokens which can be set on the container.
Credentials credentials = new Credentials();
credentials.addToken(rmToken.getService(), rmToken);
credentials.addToken(hdfsToken.getService(), hdfsToken);
DataOutputBuffer dataOutput = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dataOutput);
byte[] tokensBytes = dataOutput.getData();
ByteBuffer tokensBuf = ByteBuffer.wrap(tokensBytes);
amContainer.setTokens(tokensBuf);
}
*/
String pathSuffix = DEFAULT_APPNAME + "/" + appId.toString();
// copy required jar files to dfs, to be localized for containers
FileSystem fs = FileSystem.get(conf);
String libJarsCsv = "";
for (String localJarFile : localJarFiles) {
Path src = new Path(localJarFile);
String jarName = src.getName();
Path dst = new Path(fs.getHomeDirectory(), pathSuffix + "/" + jarName);
LOG.info("Copy {} from local filesystem to {}", localJarFile, dst);
fs.copyFromLocalFile(false, true, src, dst);
if (libJarsCsv.length() > 0) {
libJarsCsv += ",";
}
libJarsCsv += dst.toString();
}
LOG.info("libjars: {}", libJarsCsv);
dag.getAttributes().attr(LogicalPlan.LIBRARY_JARS).set(libJarsCsv);
dag.getAttributes().attr(LogicalPlan.APPLICATION_PATH).set(new Path(fs.getHomeDirectory(), pathSuffix).toString());
// set local resources for the application master
// local files or archives as needed
// In this scenario, the jar file for the application master is part of the local resources
Map<String, LocalResource> localResources = new HashMap<String, LocalResource>();
LaunchContainerRunnable.addLibJarsToLocalResources(libJarsCsv, localResources, fs);
// Set the log4j properties if needed
if (!log4jPropFile.isEmpty()) {
Path log4jSrc = new Path(log4jPropFile);
Path log4jDst = new Path(fs.getHomeDirectory(), "log4j.props");
fs.copyFromLocalFile(false, true, log4jSrc, log4jDst);
FileStatus log4jFileStatus = fs.getFileStatus(log4jDst);
LocalResource log4jRsrc = Records.newRecord(LocalResource.class);
log4jRsrc.setType(LocalResourceType.FILE);
log4jRsrc.setVisibility(LocalResourceVisibility.APPLICATION);
log4jRsrc.setResource(ConverterUtils.getYarnUrlFromURI(log4jDst.toUri()));
log4jRsrc.setTimestamp(log4jFileStatus.getModificationTime());
log4jRsrc.setSize(log4jFileStatus.getLen());
localResources.put("log4j.properties", log4jRsrc);
}
// push application configuration to dfs location
Path cfgDst = new Path(fs.getHomeDirectory(), pathSuffix + "/" + LogicalPlan.SER_FILE_NAME);
FSDataOutputStream outStream = fs.create(cfgDst, true);
LogicalPlan.write(this.dag, outStream);
outStream.close();
FileStatus topologyFileStatus = fs.getFileStatus(cfgDst);
LocalResource topologyRsrc = Records.newRecord(LocalResource.class);
topologyRsrc.setType(LocalResourceType.FILE);
topologyRsrc.setVisibility(LocalResourceVisibility.APPLICATION);
topologyRsrc.setResource(ConverterUtils.getYarnUrlFromURI(cfgDst.toUri()));
topologyRsrc.setTimestamp(topologyFileStatus.getModificationTime());
topologyRsrc.setSize(topologyFileStatus.getLen());
localResources.put(LogicalPlan.SER_FILE_NAME, topologyRsrc);
// Set local resource info into app master container launch context
amContainer.setLocalResources(localResources);
// Set the necessary security tokens as needed
//amContainer.setContainerTokens(containerToken);
// Set the env variables to be setup in the env where the application master will be run
LOG.info("Set the environment for the application master");
Map<String, String> env = new HashMap<String, String>();
// Add application jar(s) location to classpath
// At some point we should not be required to add
// the hadoop specific classpaths to the env.
// It should be provided out of the box.
// For now setting all required classpaths including
// the classpath to "." for the application jar(s)
/**
* Monitor the submitted application for completion. Kill application if time expires.
*
* @return true if application completed successfully
* @throws YarnRemoteException
*/
public boolean monitorApplication() throws YarnException, IOException
{
ClientRMHelper.AppStatusCallback callback = new ClientRMHelper.AppStatusCallback() {
@Override
public boolean exitLoop(ApplicationReport report) {
LOG.info("Got application report from ASM for"
+ ", appId=" + appId.getId()
+ ", clientToken=" + report.getClientToAMToken()
+ ", appDiagnostics=" + report.getDiagnostics()
+ ", appMasterHost=" + report.getHost()
+ ", appQueue=" + report.getQueue()
+ ", appMasterRpcPort=" + report.getRpcPort()
+ ", appStartTime=" + report.getStartTime()
+ ", yarnAppState=" + report.getYarnApplicationState().toString()
+ ", distributedFinalState=" + report.getFinalApplicationStatus().toString()
+ ", appTrackingUrl=" + report.getTrackingUrl()
+ ", appUser=" + report.getUser());
return false;
}
};
return rmClient.waitForCompletion(appId, callback, clientTimeout);
}
/**
* Get a new application from the ASM
*
* @return New Application
* @throws YarnRemoteException
*/
private GetNewApplicationResponse getNewApplication() throws YarnException, IOException
{
GetNewApplicationRequest request = Records.newRecord(GetNewApplicationRequest.class);
GetNewApplicationResponse response = rmClient.clientRM.getNewApplication(request);
LOG.info("Got new application id=" + response.getApplicationId());
return response;
}
}
|
package scalac.atree;
import java.util.List;
import java.util.ArrayList;
import scalac.Unit;
import scalac.ast.Tree;
import scalac.ast.Tree.Ident;
import scalac.ast.Tree.Template;
import scalac.symtab.Definitions;
import scalac.symtab.Symbol;
import scalac.util.Debug;
/** This class translates syntax trees into attributed trees. */
public class ATreeFromSTree {
//
// Private Fields
/** The global definitions */
private final Definitions definitions;
/** The attributed tree factory */
private final ATreeFactory make;
//
// Public Constructors
/** Initializes this instance. */
public ATreeFromSTree(Definitions definitions) {
this.definitions = definitions;
this.make = new ATreeFactory();
}
//
// Public Methods - Translating units
/** Translates the unit's body and stores the result in it. */
public void translate(Unit unit) {
template(unit.repository = new ARepository(), unit.body);
}
//
// Private Methods - Translating templates
/** Translates the templates and adds them to the repository. */
private void template(ARepository repository, Tree[] trees) {
for (int i = 0; i < trees.length; i++) template(repository, trees[i]);
}
/** Translates the template and adds it to the repository. */
private void template(ARepository repository, Tree tree) {
switch (tree) {
case Empty:
return;
case ClassDef(_, _, _, _, _, Template(_, Tree[] body)):
AClass clasz = new AClass(tree.symbol());
repository.addClass(clasz);
member(clasz, body);
return;
case PackageDef(_, Template(_, Tree[] body)):
template(repository, body);
return;
case ValDef(_, _, _, Tree rhs):
return;
default:
throw Debug.abort("illegal case", tree);
}
}
//
// Private Methods - Translating members
/** Translates the members and adds them to the class. */
private void member(AClass clasz, Tree[] trees) {
for (int i = 0; i < trees.length; i++) member(clasz, trees[i]);
}
/** Translates the member and adds it to the class. */
private void member(AClass clasz, Tree tree) {
switch (tree) {
case Empty:
return;
case ClassDef(_, _, _, _, _, _):
template(clasz, tree);
return;
case ValDef(_, _, _, Tree rhs):
AField field = new AField(tree.symbol(), false);
clasz.addField(field);
return;
case DefDef(_, _, _, _, _, Tree rhs):
AMethod method = new AMethod(tree.symbol(), false);
clasz.addMethod(method);
if (!method.isAbstract()) method.setCode(expression(rhs));
return;
default:
throw Debug.abort("illegal case", tree);
}
}
//
// Private Methods - Translating statements
/** Translates the statements. */
private ACode[] statement(List locals, Tree[] trees, int start, int count){
List codes = new ArrayList();
for (int i = start; i < start + count; i++) {
ACode code = statement(locals, trees[i]);
if (code != ACode.Void) codes.add(code);
}
return (ACode[])codes.toArray(new ACode[codes.size()]);
}
/** Translates the statement. */
private ACode statement(List locals, Tree tree) {
switch (tree) {
case Empty:
return make.Void;
case ValDef(_, _, _, Tree rhs):
Symbol symbol = tree.symbol();
locals.add(symbol);
ALocation location = ALocation.Local(symbol, false);
return make.Store(tree, location, expression(rhs));
default:
return ACode.Drop(expression(tree), tree.type());
}
}
//
// Private Methods - Translating expressions
/** Translates the expressions. */
private ACode[] expression(Tree[] trees) {
ACode[] codes = new ACode[trees.length];
for (int i = 0; i < codes.length; i++) codes[i] = expression(trees[i]);
return codes;
}
/** Translates the expression. */
private ACode expression(Tree tree) {
switch (tree) {
case LabelDef(_, Ident[] idents, Tree rhs):
Symbol[] locals = Tree.symbolOf(idents);
return make.Label(tree, tree.symbol(), locals, expression(rhs));
case Block(Tree[] statements):
if (statements.length == 0) return make.Void;
int statement_count = statements.length - 1;
List locals = new ArrayList();
ACode[] codes = statement(locals,statements,0, statement_count);
ACode value = expression(statements[statement_count]);
if (locals.size() == 0 && codes.length == 0) return value;
Symbol[] symbols =
(Symbol[])locals.toArray(new Symbol[locals.size()]);
return make.Block(tree, symbols, codes, value);
case Assign(Tree lhs, Tree rhs):
return make.Block(tree, Symbol.EMPTY_ARRAY, new ACode[] {
make.Store(tree, location(lhs), expression(rhs))},
make.Void);
case If(Tree cond, Tree thenp, Tree elsep):
ACode test = expression(cond);
return make.If(tree, test, expression(thenp), expression(elsep));
case Switch(Tree test, int[] tags, Tree[] bodies, Tree otherwise):
int[][] tagss = new int[tags.length][];
for (int i = 0; i < tagss.length; i++)
tagss[i] = new int[] {tags[i]};
ACode[] codes = new ACode[bodies.length + 1];
for (int i = 0; i < bodies.length; i++)
codes[i] = expression(bodies[i]);
codes[tags.length] = expression(otherwise);
return make.Switch(tree, expression(test), tagss, codes);
case Return(Tree value):
return make.Return(tree, tree.symbol(), expression(value));
case Throw(Tree value):
return make.Throw(tree, expression(value));
case New(Template(Tree[] bases, _)):
switch (bases[0]) {
case Apply(TypeApply(Tree fun, Tree[] targs), Tree[] vargs):
return apply(tree, method(fun), targs, vargs);
case Apply(Tree fun, Tree[] vargs):
return apply(tree, method(fun), Tree.EMPTY_ARRAY, vargs);
default:
throw Debug.abort("illegal case", bases[0]);
}
case Apply(TypeApply(Tree fun, Tree[] targs), Tree[] vargs):
return apply(tree, fun, targs, vargs);
case Apply(Tree fun, Tree[] vargs):
return apply(tree, fun, Tree.EMPTY_ARRAY, vargs);
case Super(_, _):
case This(_):
return make.This(tree, tree.symbol());
case Select(_, _):
return make.Load(tree, location(tree));
case Ident(_):
if (tree.symbol() == definitions.NULL)
return make.Constant(tree, make.NULL);
if (tree.symbol() == definitions.ZERO)
return make.Constant(tree, make.ZERO);
return make.Load(tree, location(tree));
case Literal(Object value):
return make.Constant(tree, constant(value));
default:
throw Debug.abort("illegal case", tree);
}
}
/** Translates the application. */
private ACode apply(Tree tree, Tree fun, Tree[] targs, Tree[] vargs) {
switch (fun) {
case Ident(_):
if ("".equals("")) return ACode.Void;
Symbol symbol = tree.symbol();
assert symbol.isLabel() && targs.length == 0: tree;
return make.Goto(tree, symbol, expression(vargs));
}
return apply(tree, method(fun), targs, vargs);
}
/** Translates the application. */
private ACode apply(Tree tree, AFunction function,Tree[]targs,Tree[]vargs){
return make.Apply(tree, function,Tree.typeOf(targs),expression(vargs));
}
//
// Private Methods - Translating functions
/** Translates the method. */
private AFunction method(Tree tree) {
switch (tree) {
case Select(Tree qualifier, _):
Symbol symbol = tree.symbol();
if (symbol.isJava() && symbol.owner().isModuleClass())
return AFunction.Method(make.Void, symbol, AInvokeStyle.Static); // !!! qualifier is ignored !
ACode object = expression(qualifier);
return AFunction.Method(object, symbol, invokeStyle(qualifier));
case Ident(_):
Symbol symbol = tree.symbol();
assert symbol.isInitializer();
return AFunction.Method(make.Void, symbol, AInvokeStyle.New);
default:
throw Debug.abort("illegal case", tree);
}
}
/** Returns the InvokeStyle to use for the qualifier. */
private AInvokeStyle invokeStyle(Tree qualifier) {
switch (qualifier) {
case Super(_, _):
return AInvokeStyle.Static;
default:
return AInvokeStyle.Dynamic;
}
}
//
// Private Methods - Translating locations
/** Translates the location. */
private ALocation location(Tree tree) {
switch (tree) {
case Select(Tree qualifier, _):
Symbol symbol = tree.symbol();
if (symbol.isModule())
return ALocation.Module(symbol); // !!! qualifier is ignored !
if (symbol.isJava() && symbol.owner().isModuleClass())
return ALocation.Field(make.Void, symbol, true); // !!! qualifier is ignored !
return ALocation.Field(expression(qualifier), symbol, false);
case Ident(_):
Symbol symbol = tree.symbol();
if (symbol.isModule()) return ALocation.Module(symbol);
return ALocation.Local(symbol, symbol.isParameter());
default:
throw Debug.abort("illegal case", tree);
}
}
//
// Private Methods - Translating constants
/** Translates the constant. */
private AConstant constant(Object value) {
if (value instanceof Boolean ) return make.BOOLEAN((Boolean )value);
if (value instanceof Byte ) return make.BYTE (((Byte )value));
if (value instanceof Short ) return make.SHORT ((Short )value);
if (value instanceof Character) return make.CHAR ((Character)value);
if (value instanceof Integer ) return make.INT ((Integer )value);
if (value instanceof Long ) return make.LONG ((Long )value);
if (value instanceof Float ) return make.FLOAT ((Float )value);
if (value instanceof Double ) return make.DOUBLE ((Double )value);
if (value instanceof String ) return make.STRING ((String )value);
throw Debug.abort("illegal constant", value +" -- "+ value.getClass());
}
//
}
|
package com.ysu.zyw.tc.api.test;
import com.ysu.zyw.tc.api.dao.mappers.TcItemMapper;
import com.ysu.zyw.tc.api.svc.items.TcItemService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.Arrays;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath*:/config/tc-spring-deploy.xml",
"classpath*:/config/tc-spring-cache-redis.xml",
"classpath*:/config/tc-spring-se-elasticsearch.xml"
})
@Slf4j
public class TcItemTest {
private static final String ES_INDEX = "demo_index";
private static final String ES_TYPE = "demo_doc";
@Resource
private TcItemService tcItemService;
@Resource
private TcItemMapper tcItemMapper;
@Resource
private TransportClient transportClient;
@Test
public void testES() {
// TcItem tcItem = tcItemMapper.selectByPrimaryKey("00002D472C7B48D896A48B5F5FE0A522");
// IndexResponse indexResponse = transportClient.prepareIndex(ES_INDEX, ES_DOCUMENT, "00002D472C7B48D896A48B5F5FE0A522")
// .setSource(TcSerializationUtils.writeJson(tcItem))
// .get();
// System.out.println(indexResponse.getId());
// System.out.println(indexResponse.getIndex());
// System.out.println(indexResponse.getType());
// System.out.println(indexResponse.getVersion());
// System.out.println(indexResponse.getResult());
SearchResponse searchResponse = transportClient.prepareSearch(ES_INDEX)
.setTypes(ES_TYPE)
.setQuery(QueryBuilders.matchQuery("shopId", "A1861BD5CCE44B399E891DAAD99BAE27"))
.get();
System.out.println(searchResponse.getHits().getHits().length);
Arrays.stream(searchResponse.getHits().getHits())
.forEach(searchHitFields -> System.out.println(searchHitFields.getId()));
}
}
|
// todo: (0) propagate target type in cast.
// todo: eliminate Typed nodes.
// todo: use SELECTOR flag to avoid access methods for privates
// todo: use mangled name or drop.
// todo: emit warnings for unchecked.
// todo: qualified super.
// todo: pattern definitions with 0 or 1 bound variable.
// todo: phase sync
package scalac.typechecker;
import ch.epfl.lamp.util.Position;
import scalac.*;
import scalac.util.*;
import scalac.ast.*;
import scalac.ast.printer.*;
import scalac.symtab.*;
import Tree.*;
import java.util.HashMap;
/** The main attribution phase.
*/
public class Analyzer extends Transformer implements Modifiers, Kinds {
private final Definitions definitions;
private final DeSugarize desugarize;
private final AnalyzerPhase descr;
final Infer infer;
public Analyzer(Global global, AnalyzerPhase descr) {
super(global);
this.definitions = global.definitions;
this.descr = descr;
this.infer = new Infer(this);
this.desugarize = new DeSugarize(this, global);
}
private Unit unit;
private Context context;
private Type pt;
private int mode;
private boolean inAlternative; // for pattern matching;
private HashMap patternVars; // for pattern matching; maps x to {true,false}
public void apply() {
for (int i = 0; i < global.units.length; i++) {
enterUnit(global.units[i]);
}
super.apply(); // this calls apply(u) for every unit `u'.
int n = descr.newSources.size();
while (n > 0) {
int l = global.units.length;
Unit[] newUnits = new Unit[l + n];
System.arraycopy(global.units, 0, newUnits, 0, l);
for (int i = 0; i < n; i++)
newUnits[i + l] = (Unit)descr.newSources.get(i);
global.units = newUnits;
descr.newSources.clear();
for (int i = l; i < newUnits.length; i++) {
apply(newUnits[i]);
}
n = descr.newSources.size();
}
}
public void enterUnit(Unit unit) {
enter(new Context(Tree.Empty, unit.console ? descr.consoleContext : descr.startContext), unit);
}
public void enter(Context context, Unit unit) {
assert this.unit == null : "start unit non null for " + unit;
this.unit = unit;
this.context = context;
this.patternVars = new HashMap();
ImportList prevImports = context.imports;
descr.contexts.put(unit, context);
enterSyms(unit.body);
context.imports = prevImports;
this.unit = null;
this.context = null;
}
public void lateEnter(Unit unit, Symbol sym) {
assert sym.pos == Position.NOPOS : sym;
enterUnit(unit);
if (sym.pos == Position.NOPOS) {
sym.setInfo(Type.ErrorType);
String kind;
if (sym.name.isTermName()) kind = "object or method ";
else if (sym.name.isTypeName()) kind = "class ";
else kind = "constructor ";
throw new Type.Error("file " + unit.source + " does not define public " +
kind + sym.fullName());
} else {
descr.newSources.add(unit);
}
}
public void apply(Unit unit) {
global.log("checking " + unit);
assert this.unit == null : "start unit non null for " + unit;
this.unit = unit;
this.context = (Context)descr.contexts.remove(unit);
assert this.context != null : "could not find context for " + unit;
unit.body = transformStatSeq(unit.body, Symbol.NONE);
/** todo: check what this is for
if (global.target == global.TARGET_JAVA && unit.errors == 0) {
unit.symdata = new SymData(unit);
}
*/
this.unit = null;
this.context = null;
global.operation("checked " + unit);
}
/** Mode constants
*/
static final int NOmode = 0x000;
static final int EXPRmode = 0x001; // these 4 modes are mutually exclusive.
static final int PATTERNmode = 0x002;
static final int CONSTRmode = 0x004;
static final int TYPEmode = 0x008;
static final int FUNmode = 0x10; // orthogonal to above. When set
// we are looking for a method or constructor
static final int POLYmode = 0x020; // orthogonal to above. When set
// expression types can be polymorphic.
static final int QUALmode = 0x040; // orthogonal to above. When set
// expressions may be packages and
// Java statics modules.
static final int SUPERmode = 0x080; // Goes with CONSTRmode. When set
// we are checking a superclass
// constructor invocation.
static final int baseModes = EXPRmode | PATTERNmode | CONSTRmode;
static final int SEQUENCEmode = 0x1000; // orthogonal to above. When set
// we turn "x" into "x@_"
static final int notSEQUENCEmode = Integer.MAX_VALUE - SEQUENCEmode;
Tree errorTree(int pos) {
return make.Bad(pos).setSymbol(Symbol.ERROR).setType(Type.ErrorType);
}
Tree error(int pos, String msg) {
unit.error(pos, msg);
return errorTree(pos);
}
void typeError(int pos, Type found, Type req) {
String msg = infer.typeErrorMsg("type mismatch", found, req);
Type foundResult = found.resultType();
if (foundResult != found && infer.isCompatible(foundResult, req))
msg = msg +
"\n possible cause: missing arguments for method or constructor";
error(pos, msg);
}
void reportTypeError(int pos, Type.Error ex) {
if (ex instanceof CyclicReference) {
if (global.debug) ex.printStackTrace();
CyclicReference cyc = (CyclicReference) ex;
if (cyc.info instanceof LazyTreeType) {
switch (((LazyTreeType) cyc.info).tree) {
case ValDef(_, _, Tree.Empty, _):
error(pos, "recursive " + cyc.sym + " needs type");
return;
case DefDef(_, _, _, _, Tree.Empty, _):
error(pos, "recursive function " + cyc.sym.name + " needs result type");
return;
}
}
}
//throw ex;//DEBUG
error(pos, ex.msg);
}
String decode(Name name) {
if (name.isTypeName()) return "type " + NameTransformer.decode(name);
else if (name.isConstrName()) return "constructor " + NameTransformer.decode(name);
else return "value " + NameTransformer.decode(name);
}
/** Check that `sym' accessible as a member of tree `site' in current context.
*/
void checkAccessible(int pos, Symbol sym, Tree site) {
if (!isAccessible(sym, site)) {
error(pos, sym + " cannot be accessed in " + site.type);
}
if (site instanceof Tree.Super && (sym.flags & DEFERRED) != 0) {
Symbol sym1 = context.enclClass.owner.thisSym().info().lookup(sym.name);
if ((sym1.flags & OVERRIDE) == 0 || (sym1.flags & DEFERRED) != 0)
error(pos, "symbol accessed from super may not be abstract");
}
}
/** Is `sym' accessible as a member of tree `site' in current context?
*/
boolean isAccessible(Symbol sym, Tree site) {
return
(sym.flags & (PRIVATE | PROTECTED)) == 0
||
accessWithin(sym.owner())
||
((sym.flags & PRIVATE) == 0) &&
site.type.symbol().isSubClass(sym.owner()) &&
(site instanceof Tree.Super ||
isSubClassOfEnclosing(site.type.symbol()));
} //where
/** Are we inside definition of `owner'?
*/
boolean accessWithin(Symbol owner) {
Context c = context;
while (c != Context.NONE && c.owner != owner) {
c = c.outer.enclClass;
}
return c != Context.NONE;
}
/** Is `clazz' a subclass of an enclosing class?
*/
boolean isSubClassOfEnclosing(Symbol clazz) {
Context c = context;
while (c != Context.NONE && !clazz.isSubClass(c.owner)) {
c = c.outer.enclClass;
}
return c != Context.NONE;
}
/** Check that symbol's definition is well-formed. This means:
* - no conflicting modifiers
* - `abstract' modifier only for classes
* - `override' modifier never for classes
* - `def' modifier never for parameters of case classes
* - declarations only in traits or abstract classes
* - symbols with `override' modifier override some other symbol.
*/
void validate(Symbol sym) {
checkNoConflict(sym, DEFERRED, PRIVATE);
checkNoConflict(sym, FINAL, PRIVATE);
checkNoConflict(sym, FINAL, SEALED);
checkNoConflict(sym, PRIVATE, PROTECTED);
checkNoConflict(sym, PRIVATE, OVERRIDE);
checkNoConflict(sym, DEFERRED, FINAL);
if ((sym.flags & ABSTRACTCLASS) != 0 && sym.kind != CLASS) {
error(sym.pos, "`abstract' modifier can be used only for classes; " +
"\nit should be omitted for abstract members");
}
if ((sym.flags & OVERRIDE) != 0 && sym.kind == CLASS) {
error(sym.pos, "`override' modifier not allowed for classes");
}
if ((sym.flags & DEF) != 0 && sym.owner().isPrimaryConstructor() &&
(sym.owner().primaryConstructorClass().flags & CASE) != 0) {
error(sym.pos, "`def' modifier not allowed for case class parameters");
}
/*!!!
if ((sym.flags & REPEATED) != 0 && sym.owner().isPrimaryConstructor()) {
error(sym.pos, "`*' modifier not allowed for class parameters");
}
*/
if ((sym.flags & DEFERRED) != 0) {
if (sym.owner().kind != CLASS ||
(sym.owner().flags & MODUL) != 0 ||
sym.owner().isAnonymousClass()) {
error(sym.pos,
"only classes can have declared but undefined members" +
(((sym.flags & MUTABLE) == 0) ? ""
: "\n(Note that variables need to be initialized to be defined)"));
sym.flags &= ~DEFERRED;
}
}
if ((sym.flags & OVERRIDE) != 0) {
int i = -1;
if (sym.owner().kind == CLASS) {
Type[] parents = sym.owner().info().parents();
i = parents.length - 1;
while (i >= 0 &&
parents[i].lookupNonPrivate(sym.name).kind == NONE)
i
}
if (i < 0) {
error(sym.pos, sym + " overrides nothing");
sym.flags &= ~OVERRIDE;
}
}
}
/** Check that
* - all parents are class types
* - supertype conforms to supertypes of all mixin types.
* - final classes are only inherited by classes which are
* nested within definition of base class, or that occur within same
* statement sequence.
* - self-type of current class is a subtype of self-type of each parent class.
* - parent constructors do not refer to value parameters of class.
*/
void validateParentClasses(Tree[] constrs, Type[] parents, Type selfType) {
for (int i = 0; i < parents.length; i++) {
if (!checkClassType(constrs[i].pos, parents[i])) return;
Symbol bsym = parents[i].symbol();
if (i == 0) {
if ((bsym.flags & (JAVA | INTERFACE)) == (JAVA | INTERFACE))
error(constrs[0].pos, "superclass may not be a Java interface");
} else {
if ((bsym.flags & (JAVA | INTERFACE)) == JAVA)
error(constrs[i].pos, "Java class may not be used as mixin");
Type[] grandparents = parents[i].parents();
if (grandparents.length > 0 &&
!parents[0].isSubType(grandparents[0]))
error(constrs[i].pos, "illegal inheritance;\n " + parents[0] +
" does not conform to " + parents[i] + "'s supertype");
}
if ((bsym.flags & FINAL) != 0) {
error(constrs[i].pos, "illegal inheritance from final class");
} else if ((bsym.flags & SEALED) != 0) {
// are we in same scope as base type definition?
Scope.Entry e = context.scope.lookupEntry(bsym.name);
if (e.sym != bsym || e.owner != context.scope) {
// we are not within same statement sequence
Context c = context;
while (c != Context.NONE && c.owner != bsym)
c = c.outer;
if (c == Context.NONE) {
error(constrs[i].pos, "illegal inheritance from sealed class");
}
}
}
if (!selfType.isSubType(parents[i].instanceType())) {
error(constrs[i].pos, "illegal inheritance;\n self-type " +
selfType + " does not conform to " + parents[i] +
"'s selftype " + parents[i].instanceType());
}
}
}
/** Check that type is a class type.
*/
private boolean checkClassType(int pos, Type tp) {
switch (tp.unalias()) {
case TypeRef(_, Symbol sym, _):
if (sym.kind == CLASS) return true;
else if (sym.kind == ERROR) return false;
break;
case ErrorType:
return false;
}
error(pos, "class type expected");
return false;
}
/** Check that type is an object type
*/
private Type checkObjectType(int pos, Type tp) {
if (tp.isObjectType()) return tp;
else {
if (tp != Type.ErrorType) error(pos, "object type expected");
return Type.ErrorType;
}
}
/** Check that type is eta-expandable (i.e. no `def' or `*' parameters)
*/
void checkEtaExpandable(int pos, Type tp) {
switch (tp) {
case MethodType(Symbol[] params, Type restype):
for (int i = 0; i < params.length; i++) {
if ((params[i].flags & DEF) != 0)
error(pos, "method with `def' parameters needs to be fully applied");
if ((params[i].flags & REPEATED) != 0)
error(pos, "method with `*' parameters needs to be fully applied");
}
checkEtaExpandable(pos, restype);
}
}
/** Check that `sym' does not contain both `flag1' and `flag2'
*/
void checkNoConflict(Symbol sym, int flag1, int flag2) {
if ((sym.flags & (flag1 | flag2)) == (flag1 | flag2)) {
if (flag1 == DEFERRED)
error(sym.pos, "abstract member may not have " +
Modifiers.Helper.toString(flag2) + " modifier");
else
error(sym.pos, "illegal combination of modifiers: " +
Modifiers.Helper.toString(flag1) + " and " +
Modifiers.Helper.toString(flag2));
}
}
/** Check that type `tp' is not a subtype of itself.
*/
public void checkNonCyclic(int pos, Type tp) {
switch (tp) {
case TypeRef(Type pre, Symbol sym, Type[] args):
sym.initialize();
if ((sym.flags & LOCKED) != 0) {
error(pos, "cyclic aliasing or subtyping involving " + sym);
} else if (sym.kind == ALIAS || sym.kind == TYPE) {
sym.flags |= LOCKED;
checkNonCyclic(
pos, pre.memberInfo(sym).subst(sym.typeParams(), args));
if (sym.kind == TYPE)
checkNonCyclic(
pos, pre.memberLoBound(sym).subst(sym.typeParams(), args));
sym.flags &= ~LOCKED;
}
break;
case CompoundType(Type[] parents, Scope members):
for (int i = 0; i < parents.length; i++) {
checkNonCyclic(pos, parents[i]);
}
break;
case SingleType(Type pre, Symbol sym):
sym.initialize();
if ((sym.flags & LOCKED) != 0) {
error(pos, "cyclic aliasing or subtyping involving " + sym);
}
}
}
/** Check that type does not refer to components defined in current scope.
*/
Type checkNoEscape(int pos, Type tp) {
try {
return checkNoEscapeMap.apply(tp);
} catch (Type.Error ex) {
error(pos, ex.msg + " as part of " + tp.unalias());
return Type.ErrorType;
}
}
//where
private Type.Map checkNoEscapeMap = new Type.Map() {
public Type apply(Type t) {
switch (t) {
case TypeRef(Type pre, Symbol sym, Type[] args):
if (sym.kind == ALIAS) return apply(t.unalias());
else if (pre instanceof Type.ThisType) checkNoEscape(t, sym);
break;
case SingleType(ThisType(_), Symbol sym):
checkNoEscape(t, sym);
break;
}
return map(t);
}
private void checkNoEscape(Type t, Symbol sym) {
Scope.Entry e = context.scope.lookupEntry(sym.name);
if (e.sym == sym && e.owner == context.scope &&
!(e.sym.kind == TYPE && (e.sym.flags & PARAM) != 0)) {
throw new Type.Error(
"type " + t + " escapes its defining scope");
}
}
};
/** Check that tree represents a pure definition.
*/
void checkPureDef(Tree tree, Symbol clazz) {
if (!TreeInfo.isPureDef(tree) && tree.type != Type.ErrorType)
error(tree.pos, clazz + " may contain only pure definitions");
}
/** Check that tree represents a pure constructor.
*/
void checkPureConstr(Tree tree, Symbol clazz) {
if (!TreeInfo.isPureConstr(tree) && tree.type != Type.ErrorType)
error(tree.pos, clazz + " may invoke only pure superclass constructors");
}
/** Check that tree represents a trait constructor.
*/
void checkTrait(Tree tree, Symbol clazz) {
if (!tree.type.symbol().isTrait() && tree.type != Type.ErrorType)
error(tree.pos, " " + clazz + " may inherit only traits as mixins");
}
/** Check that tree is a stable expression .p
*/
Tree checkStable(Tree tree) {
if (TreeInfo.isPureExpr(tree) || tree.type == Type.ErrorType)
return tree;
else
return error(tree.pos, "stable identifier required, but " +
tree + " found.");
}
/** Check that class can be instantiated.
*/
void checkInstantiatable(int pos, Type tp) {
Symbol clazz = tp.symbol();
if (clazz.kind == CLASS) {
if (clazz.isAbstractClass())
error(pos, clazz + " is abstract, so it cannot be instantiated");
else if (!tp.isSubType(tp.instanceType()))
error(pos, tp + " does not conform to its self-type " +
tp.instanceType() + ", so it cannot be instantiated");
}
}
/** Check that all subtrees have their types defined.
* Used for asserting an internal invariant
*/
private static class CheckDefined extends Traverser {
Tree all;
public void traverse(Tree tree) {
assert tree.type != null : tree + " in " + all;
if (tree.type != Type.ErrorType)
super.traverse(tree);
}
}
private static CheckDefined checkDefined = new CheckDefined();
/** The qualifier type of a potential application of the `match' method.
* or NoType, if this is something else.
*/
private Type matchQualType(Tree fn) {
switch (fn) {
case Select(Tree qual, _):
if (fn.symbol() == definitions.OBJECT_TYPE.lookup(Names.match))
return qual.type.widen();
break;
case TypeApply(Tree fn1, _):
return matchQualType(fn1);
case Ident(_):
if (fn.symbol() == definitions.OBJECT_TYPE.lookup(Names.match))
return context.enclClass.owner.typeOfThis();
break;
}
return fn.type == Type.ErrorType ? Type.ErrorType : Type.NoType;
}
private Type value2Type(Object value) {
if (value instanceof Character) return definitions.CHAR_TYPE;
else if (value instanceof Integer) return definitions.INT_TYPE;
else if (value instanceof Long) return definitions.LONG_TYPE;
else if (value instanceof Float) return definitions.FLOAT_TYPE;
else if (value instanceof Double) return definitions.DOUBLE_TYPE;
else if (value instanceof String) return definitions.JAVA_STRING_TYPE;
else if (value instanceof Boolean) return definitions.BOOLEAN_TYPE;
else throw new ApplicationError();
}
/** Push new context associated with given tree, owner, and scope on stack.
* Fields `imports' and, possibly, `enclClass' are inherited from parent.
*/
void pushContext(Tree tree, Symbol owner, Scope scope) {
context = new Context(tree, owner, scope, context);
}
/** Pop context from stack.
*/
void popContext() {
context = context.outer;
}
/** A lazy type which, when forced returns the type of a symbol defined
* in `tree'.
*/
class LazyTreeType extends Type.LazyType {
Tree tree;
Unit u;
Context c;
LazyTreeType(Tree tree) {
this.tree = tree;
this.u = unit;
this.c = context;
}
public void complete(Symbol sym) {
//System.out.println("completing " + sym);//DEBUG
//if (sym.isConstructor()) sym.constructorClass().initialize();
//else if (sym.isModule()) sym.moduleClass().initialize();
defineSym(tree, u, c);
}
}
/** A lazy type for case constructor methods (whose name is a term name)
* which sets the method's type to the class constructor type.
*/
class LazyConstrMethodType extends LazyTreeType {
LazyConstrMethodType(Tree tree) {
super(tree);
}
public void complete(Symbol sym) {
Type constrtype = tree.symbol().constructor().type().instanceType();
switch (tree) {
case ClassDef(_, _, _, ValDef[][] vparams, _, _):
if (vparams.length == 0) {
constrtype = removeMethod(constrtype);
}
}
sym.setInfo(constrtype);
}
private Type removeMethod(Type tp) {
switch (tp) {
case MethodType(_, Type restp):
return restp;
case PolyType(Symbol[] tparams, Type restp):
return Type.PolyType(tparams, removeMethod(restp));
default:
return tp;
}
}
}
/** A lazy type for self types
*/
class LazySelfType extends LazyTreeType {
LazySelfType(Tree tree) {
super(tree);
}
public void complete(Symbol sym) {
defineSelfType(sym, tree, u, c);
}
}
Tree transformPackageId(Tree tree) {
switch (tree) {
case Ident(Name name):
return tree
.setSymbol(packageSymbol(tree.pos, definitions.ROOT, name))
.setType(tree.symbol().type());
case Select(Tree qual, Name name):
Tree qual1 = transformPackageId(qual);
Symbol sym = packageSymbol(tree.pos, qual1.symbol(), name);
return copy.Select(tree, sym, qual1).setType(sym.type());
default:
return transform(tree);
}
}
Symbol packageSymbol(int pos, Symbol base, Name name) {
Symbol p = base.members().lookup(name);
if (p.kind == NONE) {
p = TermSymbol.newJavaPackageModule(name, base.moduleClass(), null);
base.members().enter(p);
} else if (!p.isPackage()) {
error(pos, "package and class with same name");
p = Symbol.ERROR;
}
return p;
}
/** If `tree' is a definition, create a symbol for it with a lazily
* constructed type, and enter into current scope.
*/
Symbol enterSym(Tree tree) {
Symbol owner = context.owner;
switch (tree) {
case PackageDef(Tree packaged, Tree.Template templ):
switch (templ) {
case Template(_, Tree[] body):
pushContext(tree, context.owner, context.scope);
context.imports = null;
((PackageDef) tree).packaged = packaged = transformPackageId(packaged);
popContext();
Symbol pkg = checkStable(packaged).symbol();
if (pkg != null && pkg.kind != ERROR) {
if (pkg.isPackage()) {
pushContext(templ, pkg.moduleClass(), pkg.members());
enterSyms(body);
popContext();
} else {
error(tree.pos, "only Java packages allowed for now");
}
}
templ.setSymbol(Symbol.NONE);
return null;
default:
throw new ApplicationError();
}
case ClassDef(int mods, Name name, Tree.TypeDef[] tparams, Tree.ValDef[][] vparams, _, Tree.Template templ):
ClassSymbol clazz = new ClassSymbol(tree.pos, name, owner, mods);
if (clazz.isLocalClass()) unit.mangler.setMangledName(clazz);
enterSym(tree, clazz.constructor());
if ((mods & CASE) != 0) {
if (vparams.length == 0) {
error(tree.pos, "case class needs () parameter section");
} else if ((mods & ABSTRACTCLASS) == 0) {
// enter case constructor method.
enterInScope(
new TermSymbol(
tree.pos, name.toTermName(), owner, mods & (ACCESSFLAGS | CASE))
.setInfo(new LazyConstrMethodType(tree)));
}
}
return enterSym(tree, clazz);
case ModuleDef(int mods, Name name, _, _):
TermSymbol modul = TermSymbol.newModule(tree.pos, name, owner, mods);
Symbol clazz = modul.moduleClass();
clazz.setInfo(new LazyTreeType(tree));
if (clazz.isLocalClass()) unit.mangler.setMangledName(clazz);
return enterSym(tree, modul);
case ValDef(int mods, Name name, _, _):
return enterSym(tree, new TermSymbol(tree.pos, name, owner, mods));
case DefDef(int mods, Name name, _, _, _, _):
return enterSym(tree, new TermSymbol(tree.pos, name, owner, mods));
case TypeDef(int mods, Name name, _, _):
Symbol tsym = ((mods & (DEFERRED | PARAM)) != 0)
? new AbsTypeSymbol( tree.pos, name, owner, mods)
: new TypeSymbol(ALIAS, tree.pos, name, owner, mods);
return enterSym(tree, tsym);
case Import(Tree expr, Name[] selectors):
return enterImport(tree,
new TermSymbol(
tree.pos,
Name.fromString("import " + expr),
Symbol.NONE, SYNTHETIC));
default:
return null;
}
}//where
/** Enter `sym' in current scope and make it the symbol of `tree'.
*/
private Symbol enterSym(Tree tree, Symbol sym) {
//if (global.debug) System.out.println("entering " + sym);//DEBUG
sym.setInfo(new LazyTreeType(tree));
sym = enterInScope(sym);
tree.setSymbol(sym);
return sym;
}
/** Make `sym' the symbol of import `tree' and create an entry in
* current imports list.
*/
private Symbol enterImport(Tree tree, Symbol sym) {
sym.setInfo(new LazyTreeType(tree));
tree.setSymbol(sym);
context.imports = new ImportList(tree, context.scope, context.imports);
return sym;
}
/** Enter symbol `sym' in current scope. Check for double definitions.
* Handle overloading.
*/
private Symbol enterInScope(Symbol sym) {
// handle double and overloaded definitions
Symbol result = sym;
Scope.Entry e = context.scope.lookupEntry(sym.name);
if (e.owner == context.scope) {
Symbol other = e.sym;
if (other.isPreloaded()) {
// symbol was preloaded from package;
// need to overwrite definition.
if (global.debug) System.out.println(sym + " overwrites " + other);//debug
sym.copyTo(other);
if (sym.isModule()) {
sym.moduleClass().copyTo(
other.moduleClass());
sym.moduleClass().constructor().copyTo(
other.moduleClass().constructor());
other.moduleClass().constructor().setInfo(
Type.MethodType(
Symbol.EMPTY_ARRAY,
other.moduleClass().typeConstructor()));
}
result = other;
} else if (sym.owner().isPackage()) {
if (global.compiledNow.get(other) != null) {
error(sym.pos, sym + " is compiled twice");
}
context.scope.unlink(e);
context.scope.enter(sym);
} else if (sym.kind == VAL && other.kind == VAL) {
// it's an overloaded definition
if (((sym.flags ^ other.flags) & SOURCEFLAGS) != 0) {
// todo: refine, DEFERRED, MUTABLE and OVERRIDE should be
// treated specially; maybe only PRIVATE and PROTECTED?
error(sym.pos,
"illegal overloaded definition of " + sym +
": modifier lists differ in " +
Modifiers.Helper.toString(
(sym.flags ^ other.flags) & SOURCEFLAGS));
} else {
e.setSymbol(other.overloadWith(sym));
}
} else {
error(sym.pos,
sym.nameString() + " is already defined as " +
other + other.locationString());
}
} else {
context.scope.enter(sym);
}
if (result.owner().isPackage())
global.compiledNow.put(result, unit.source);
return result;
}
/** Enter all symbols in statement list
*/
public void enterSyms(Tree[] stats) {
for (int i = 0; i < stats.length; i++)
enterSym(stats[i]);
}
Symbol[] enterParams(Tree[] params) {
for (int i = 0; i < params.length; i++) {
enterSym(params[i]);
switch (params[i]) {
case ValDef(int mods, _, _, _):
if ((mods & REPEATED) != 0 && params.length > 1)
error(params[i].pos,
"`*' parameter must be the only parameter of a `('...`)' section");
}
}
return Tree.symbolOf(params);
}
Symbol[][] enterParams(Tree[][] vparams) {
Symbol[][] vparamSyms = new Symbol[vparams.length][];
for (int i = 0; i < vparams.length; i++) {
vparamSyms[i] = enterParams(vparams[i]);
}
return vparamSyms;
}
/** Re-enter type parameters in current scope.
*/
void reenterParams(Tree[] params) {
for (int i = 0; i < params.length; i++) {
context.scope.enter(params[i].symbol());
}
}
/** Re-enter value parameters in current scope.
*/
void reenterParams(Tree[][] vparams) {
for (int i = 0; i < vparams.length; i++)
reenterParams(vparams[i]);
}
/** Define symbol associated with `tree' using given `unit' and `context'.
*/
void defineSym(Tree tree, Unit unit, Context curcontext) {
Unit savedUnit = this.unit;
this.unit = unit;
Context savedContext = this.context;
this.context = curcontext;
int savedMode = this.mode;
this.mode = EXPRmode;
Type savedPt = this.pt;
this.pt = Type.AnyType;
int savedId = global.currentPhase.id;
global.currentPhase.id = descr.id;
try {
Symbol sym = tree.symbol();
if (global.debug) global.log("defining " + sym);
Type owntype;
switch (tree) {
case ClassDef(int mods, Name name, Tree.TypeDef[] tparams, Tree.ValDef[][] vparams, Tree tpe, Tree.Template templ):
pushContext(tree, sym.constructor(), new Scope(context.scope));
Symbol[] tparamSyms = enterParams(tparams);
Symbol[][] vparamSyms = enterParams(vparams);
if (vparamSyms.length == 0)
vparamSyms = new Symbol[][]{Symbol.EMPTY_ARRAY};
if ((mods & CASE) != 0 && vparams.length > 0)
templ.body = desugarize.addCaseElements(templ.body, vparams[0]);
Type constrtype = makeMethodType(
tparamSyms,
vparamSyms,
Type.TypeRef(sym.owner().thisType(), sym, Symbol.type(tparamSyms)));
sym.constructor().setInfo(constrtype);
// necessary so that we can access tparams
sym.constructor().flags |= INITIALIZED;
if (tpe != Tree.Empty)
sym.setTypeOfThis(new LazySelfType(tpe));
defineTemplate(templ, sym);
owntype = templ.type;
popContext();
break;
case ModuleDef(int mods, Name name, Tree tpe, Tree.Template templ):
Symbol clazz = sym.moduleClass();
defineTemplate(templ, clazz);
clazz.setInfo(templ.type);
((ModuleDef) tree).tpe = tpe = transform(tpe, TYPEmode);
owntype = (tpe == Tree.Empty) ? clazz.type() : tpe.type;
break;
case ValDef(int mods, Name name, Tree tpe, Tree rhs):
if (tpe != Tree.Empty) {
((ValDef) tree).tpe = tpe = transform(tpe, TYPEmode);
} else {
pushContext(tree, sym, context.scope);
if (rhs == Tree.Empty) {
if ((sym.owner().flags & ACCESSOR) != 0) {
// this is the parameter of a variable setter method.
assert (sym.flags & PARAM) != 0;
((ValDef) tree).tpe = tpe =
gen.mkType(tree.pos, sym.owner().accessed().type());
} else {
error(tree.pos, "missing parameter type");
((ValDef) tree).tpe = tpe =
gen.mkType(tree.pos, Type.ErrorType);
}
} else {
((ValDef) tree).rhs = rhs = transform(rhs, EXPRmode);
((ValDef) tree).tpe = tpe = gen.mkType(tree.pos, rhs.type);
}
popContext();
}
//checkNonCyclic(tree.pos, tpe.type);
owntype = tpe.type;
break;
case DefDef(int mods, Name name, Tree.TypeDef[] tparams, Tree.ValDef[][] vparams, Tree tpe, Tree rhs):
pushContext(tree, sym, new Scope(context.scope));
Symbol[] tparamSyms = enterParams(tparams);
Symbol[][] vparamSyms = enterParams(vparams);
if (tpe != Tree.Empty) {
((DefDef) tree).tpe = tpe = transform(tpe, TYPEmode);
} else {
int rhsmode = name.isConstrName() ? CONSTRmode : EXPRmode;
((DefDef) tree).rhs = rhs = transform(rhs, rhsmode);
((DefDef) tree).tpe = tpe = gen.mkType(tree.pos, rhs.type);
}
Type restype = checkNoEscape(tpe.pos, tpe.type);
popContext();
//checkNonCyclic(tree.pos, tpe.type);
owntype = makeMethodType(tparamSyms, vparamSyms, restype);
//System.out.println("methtype " + name + ":" + owntype);//DEBUG
break;
case TypeDef(int mods, Name name, Tree rhs, Tree lobound):
if (sym.kind == TYPE) {
//can't have `sym' as owner since checkNonCyclic would fail.
((TypeDef) tree).rhs = rhs = transform(rhs, TYPEmode);
((TypeDef) tree).lobound = lobound = transform(lobound, TYPEmode);
owntype = rhs.type;
sym.setLoBound(lobound.type);
owntype.symbol().initialize();//to detect cycles todo: needed?
} else { // sym.kind == ALIAS
pushContext(tree, sym, context.scope);
((TypeDef) tree).rhs = rhs = transform(rhs, TYPEmode | FUNmode);
owntype = rhs.type;
popContext();
}
//checkNonCyclic(tree.pos, owntype);
break;
case Import(Tree expr, Name[] selectors):
((Import) tree).expr = expr = transform(expr, EXPRmode | QUALmode);
checkStable(expr);
owntype = expr.type;
Type tp = owntype.widen();
for (int i = 0; i < selectors.length; i = i + 2) {
if (selectors[i] != Names.WILDCARD &&
tp.lookup(selectors[i]) == Symbol.NONE &&
tp.lookup(selectors[i].toTypeName()) == Symbol.NONE &&
tp.lookup(selectors[i].toConstrName()) == Symbol.NONE)
error(tree.pos, selectors[i] + " is not a member of " + expr);
}
break;
default:
throw new ApplicationError();
}
sym.setInfo(owntype);
validate(sym);
if (global.debug) global.log("defined " + sym);//debug
} catch (Type.Error ex) {
reportTypeError(tree.pos, ex);
tree.type = Type.ErrorType;
if (tree.hasSymbol() && tree.symbol() == null) tree.setSymbol(Symbol.ERROR);
}
this.unit = savedUnit;
this.context = savedContext;
this.mode = savedMode;
this.pt = savedPt;
global.currentPhase.id = savedId;
}
/** Definition phase for a template. This enters all symbols in template
* into symbol table.
*/
void defineTemplate(Tree.Template templ, Symbol clazz) {
// attribute parent constructors
Tree[] constrs = transformConstrInvocations(templ.pos, templ.parents);
Type[] parents = Tree.typeOf(constrs);
// enter all members
Scope members = new Scope();
pushContext(templ, clazz, members);
templ.body = desugarize.Statements(templ.body, false);
enterSyms(templ.body);
popContext();
templ.type = Type.compoundType(parents, members, clazz);
}
Type makeMethodType(Symbol[] tparams, Symbol[][] vparams, Type restpe) {
if (tparams.length == 0 && vparams.length == 0) {
return Type.PolyType(tparams, restpe);
} else {
Type result = restpe;
for (int i = vparams.length - 1; i >= 0; i
result = Type.MethodType(vparams[i], result);
if (tparams.length != 0)
result = Type.PolyType(tparams, result);
return result;
}
}
Tree makeStableId(int pos, Type tp) {
if (tp.symbol().isCompoundSym())
return make.This(pos, Tree.Empty).setType(tp);
else
return gen.mkStableId(pos, tp);
}
/** Define self type of class or module `sym'
* associated with `tree' using given `unit' and `context'.
*/
void defineSelfType(Symbol sym, Tree tree, Unit unit, Context curcontext) {
Unit savedUnit = this.unit;
this.unit = unit;
Context savedContext = this.context;
this.context = curcontext;
sym.setInfo(transform(tree, TYPEmode).type);
this.unit = savedUnit;
this.context= savedContext;
}
/** Adapt tree to given mode and given prototype
*/
Tree adapt(Tree tree, int mode, Type pt) {
//new TextTreePrinter().Print(tree).print(" adapt " + pt).println().end();//DEBUG
switch (tree.type) {
case OverloadedType(Symbol[] alts, Type[] alttypes):
// resolve overloading
if ((mode & FUNmode) == 0) {
try {
infer.exprAlternative(tree, alts, alttypes, pt);
} catch (Type.Error ex) {
error(tree.pos, ex.msg);
}
switch (tree.type) {
case OverloadedType(_, _):
// overload resolution failed bcs no alternative matched prototype.
typeError(tree.pos, tree.type, pt);
tree.setSymbol(Symbol.ERROR).setType(Type.ErrorType);
break;
default:
return adapt(tree, mode, pt);
}
}
break;
case PolyType(Symbol[] tparams, Type restp):
// apply parameterless functions
// instantiate polymorphic expressions
if (tparams.length == 0) {
return adapt(tree.setType(restp), mode, pt);
} else if ((mode & (FUNmode | POLYmode)) == 0) {
try {
tree = infer.exprInstance(tree, tparams, restp, pt);
} catch (Type.Error ex) {
tree = error(tree.pos, ex.msg);
}
return adapt(tree, mode, pt);
}
break;
case MethodType(_, _):
// convert unapplied methods to functions.
if ((mode & (EXPRmode | FUNmode)) == EXPRmode &&
infer.isCompatible(tree.type, pt)) {
checkEtaExpandable(tree.pos, tree.type);
return transform(desugarize.etaExpand(tree, tree.type), mode, pt);
} else if ((mode & (CONSTRmode | FUNmode)) == CONSTRmode) {
return error(tree.pos, "missing arguments for class constructor");
}
}
if ((mode & PATTERNmode) != 0) {
if (tree.isType()) {
Symbol clazz = tree.type.unalias().symbol();
if (clazz.isCaseClass()) {
// set type to instantiated case class constructor
tree.type = clazz.constructor().type();
switch (tree.type) {
case PolyType(Symbol[] tparams, Type restp):
try {
infer.constructorInstance(tree, tparams, restp, pt);
} catch (Type.Error ex) {
if (pt != Type.ErrorType) error(tree.pos, ex.msg);
return tree.setType(Type.ErrorType);
}
/*
if (!(tree.type instanceof Type.MethodType))
tree = make.Apply(tree.pos, tree, Tree.EMPTY_ARRAY)
.setType(tree.type);
*/
}
} else if (clazz.isSubClass(definitions.SEQ_CLASS)) {
// set type to instantiated sequence class constructor
// todo: should we admit even supertypes of the target type?
Type seqtp = pt.baseType(clazz);
if (seqtp != Type.NoType) {
tree.type = seqConstructorType(seqtp, pt);
} else {
error(tree.pos, "expected pattern type " + pt +
" does not conform to sequence " + clazz);
}
} else if (tree.type != Type.ErrorType) {
error(tree.pos, tree.type.symbol() +
" is neither a case class constructor nor a sequence class constructor");
}
}
if ((mode & FUNmode) != 0) {
return tree;
} else {
Symbol sym = tree.symbol();
// check that idents or selects are stable.
switch (tree) {
case Ident(_):
case Select(_, _):
checkStable(tree);
}
}
} else if ((mode & EXPRmode) != 0) {
if ((mode & FUNmode) != 0) {
if (tree.type.isObjectType()) {
// insert apply method
Symbol applyMeth = tree.type.lookup(Names.apply);
if (applyMeth != Symbol.NONE && isAccessible(applyMeth, tree)) {
applyMeth.flags |= (ACCESSED | SELECTOR);
tree = make.Select(tree.pos, tree, Names.apply)
.setSymbol(applyMeth)
.setType(tree.type.memberType(applyMeth));
return adapt(tree, mode, pt);
}
}
} else if ((mode & QUALmode) == 0) {
// check that packages and static modules are not used as values
Symbol sym = tree.symbol();
if (tree.isTerm() &&
sym != null && sym.kind != ERROR && !sym.isValue()) {
error(tree.pos, tree.symbol() + " is not a value");
}
}
}
Type owntype = tree.type;
if ((mode & (CONSTRmode | FUNmode)) == (CONSTRmode)) {
owntype = owntype.instanceType();
// this works as for superclass constructor calls the expected
// type `pt' is always AnyType (see transformConstrInvocations).
}
if (!(owntype instanceof Type.PolyType || owntype.isSubType(pt))) {
typeError(tree.pos, owntype, pt);
Type.explainTypes(owntype, pt);
tree.type = Type.ErrorType;
}
return tree;
}
//where
Type seqConstructorType(Type paramtp, Type resulttp) {
Symbol constr = resulttp.symbol().constructor();
Symbol param = new TermSymbol(
Position.NOPOS, Names.WILDCARD, constr, PARAM | REPEATED).setInfo(
paramtp.baseType(definitions.SEQ_CLASS));
return Type.MethodType(new Symbol[]{param}, resulttp);
}
/** Attribute an identifier consisting of a simple name or an outer reference.
* @param tree The tree representing the identifier.
* @param name The name of the identifier.
*/
Tree transformIdent(Tree tree, Name name) {
//System.out.println("transforming " + name);//DEBUG
// find applicable definition and assign to `sym'
Symbol sym = Symbol.NONE;
Type pre;
Type symtype;
int stopPos = Integer.MIN_VALUE;
Context nextcontext = context;
while (sym.kind == NONE && nextcontext != Context.NONE) {
sym = nextcontext.scope.lookup(name);
if (sym.kind != NONE) {
stopPos = sym.pos;
} else {
nextcontext = nextcontext.enclClass;
if (nextcontext != Context.NONE) {
sym = nextcontext.owner.thisSym().info().lookup(name);
if (sym.kind != NONE) {
stopPos = nextcontext.owner.pos;
} else {
nextcontext = nextcontext.outer;
}
}
}
}
// find applicable import and assign to `sym1'
ImportList nextimports = context.imports;
ImportList lastimports = null;
Symbol sym1 = Symbol.NONE;
// System.out.println("name = " + name + ", pos = " + tree.pos + ", importlist = ");//DEBUG
// for (ImportList imp = nextimports; imp != null; imp = imp.prev) {
// new TextTreePrinter().print(" ").print(imp.tree).println().end();//DEBUG
while (nextimports != null && nextimports.tree.pos >= tree.pos) {
nextimports = nextimports.prev;
}
while (sym1.kind == NONE &&
nextimports != null && nextimports.tree.pos > stopPos) {
sym1 = nextimports.importedSymbol(name);
lastimports = nextimports;
nextimports = nextimports.prev;
}
// evaluate what was found
if (sym1.kind == NONE) {
if (sym.kind == NONE) {
//System.out.println(name);//debug
return error(tree.pos, "not found: " + decode(name));
} else {
sym.flags |= ACCESSED;
if (sym.owner().kind == CLASS) {
pre = nextcontext.enclClass.owner.thisType();
if (!sym.owner().isPackage()) {
Tree qual = makeStableId(tree.pos, pre);
tree = make.Select(tree.pos, qual, name);
if (context.enclClass != nextcontext.enclClass)
sym.flags |= SELECTOR;
//System.out.println(name + " :::> " + tree + " " + qual.symbol());//DEBUG
}
} else {
pre = Type.localThisType;
}
}
} else if (sym.kind != NONE && !sym.isPreloaded()) {
return error(tree.pos,
"reference to " + name + " is ambiguous;\n" +
"it is both defined in " + sym.owner() +
" and imported subsequently by \n" + nextimports.tree);
} else {
// check that there are no other applicable imports in same scope.
while (nextimports != null &&
nextimports.enclscope == lastimports.enclscope) {
if (!nextimports.sameImport(lastimports) &&
nextimports.importedSymbol(name).kind != NONE) {
return error(tree.pos,
"reference to " + name + " is ambiguous;\n" +
"it is imported twice in the same scope by\n " +
lastimports.tree + "\nand " + nextimports.tree);
}
nextimports = nextimports.prev;
}
sym = sym1;
sym.flags |= (ACCESSED | SELECTOR);
Tree qual = lastimports.importPrefix().duplicate();
pre = qual.type;
//new TextTreePrinter().print(name + " => ").print(lastimports.tree).print("." + name).println().end();//DEBUG
tree = make.Select(tree.pos, qual, name);
checkAccessible(tree.pos, sym, qual);
}
symtype = pre.memberType(sym);
if ((pt != null && pt.isStable() || (mode & QUALmode) != 0) && sym.isStable()) {
//System.out.println("making single " + sym + ":" + symtype);//DEBUG
symtype = Type.singleType(pre, sym);
}
//System.out.println(name + ":" + symtype);//DEBUG
return tree.setSymbol(sym).setType(symtype);
}
/** Attribute a selection where `tree' is `qual.name'.
* `qual' is already attributed.
*/
Tree transformSelect(Tree tree, Tree qual, Name name) {
Symbol[] uninst = Symbol.EMPTY_ARRAY;
switch (qual.type) {
case PolyType(Symbol[] tparams, Type restype):
qual = infer.mkTypeApply(qual, tparams, restype, Symbol.type(tparams));
uninst = tparams;
}
Symbol sym = qual.type.lookup(name);
if (sym.kind == NONE) {
//System.out.println(qual.type + " has members " + qual.type.members());//DEBUG
return error(tree.pos,
decode(name) + " is not a member of " + qual.type.widen());
} else {
checkAccessible(tree.pos, sym, qual);
sym.flags |= ACCESSED;
if (!TreeInfo.isSelf(qual, context.enclClass.owner))
sym.flags |= SELECTOR;
Type symtype = qual.type.memberType(sym);
//System.out.println(sym.name + ":" + symtype);//DEBUG
if (uninst.length != 0) {
switch (symtype) {
case PolyType(Symbol[] tparams, Type restype):
symtype = Type.PolyType(
tparams, Type.PolyType(uninst, restype));
break;
default:
symtype = Type.PolyType(uninst, symtype);
}
}
if ((pt != null && pt.isStable() || (mode & QUALmode) != 0) &&
sym.isStable() && qual.type.isStable())
symtype = Type.singleType(qual.type, sym);
//System.out.println(qual.type + ".member: " + sym + ":" + symtype);//DEBUG
return copy.Select(tree, sym, qual).setType(symtype);
}
}
/** Attribute a pattern matching expression where `pattpe' is the
* expected type of the patterns and `pt' is the expected type of the
* results.
*/
Tree transformVisitor(Tree tree, Type pattpe, Type pt) {
//System.out.println("trans visitor with " + pt);//DEBUG
switch (tree) {
case Visitor(Tree.CaseDef[] cases):
Tree.CaseDef[] cases1 = cases;
for (int i = 0; i < cases.length; i++)
cases1[i] = transformCase(cases[i], pattpe, pt);
return copy.Visitor(tree, cases1)
.setType(Type.lub(Tree.typeOf(cases1)));
default:
throw new ApplicationError();
}
}
/** Attribute a case where `pattpe' is the expected type of the pattern
* and `pt' is the expected type of the result.
*/
Tree.CaseDef transformCase(Tree.CaseDef tree, Type pattpe, Type pt) {
switch (tree) {
case CaseDef(Tree pat, Tree guard, Tree body):
pushContext(tree, context.owner, new Scope(context.scope));
this.inAlternative = false; // no vars allowed below Alternative
Tree pat1 = transform(pat, PATTERNmode, pattpe);
Tree guard1 = (guard == Tree.Empty) ? Tree.Empty
: transform(guard, EXPRmode, definitions.BOOLEAN_TYPE);
Tree body1 = transform(body, EXPRmode, pt);
popContext();
return (Tree.CaseDef) copy.CaseDef(tree, pat1, guard1, body1)
.setType(body1.type);
default:
throw new ApplicationError();
}
}
Tree[] transformStatSeq(Tree[] stats, Symbol exprOwner) {
Tree[] stats1 = stats;
for (int i = 0; i < stats.length; i++) {
Tree stat = stats[i];
if (context.owner.isCompoundSym() && !TreeInfo.isDeclaration(stat)) {
error(stat.pos, "only declarations allowed here");
}
Tree stat1;
int mode = TreeInfo.isDefinition(stat) ? NOmode : EXPRmode;
if (exprOwner.kind != NONE && !TreeInfo.isDefinition(stat)) {
pushContext(stat, exprOwner, context.scope);
stat1 = transform(stat, mode);
popContext();
} else {
stat1 = transform(stat, mode);
}
// todo: if we comment next 4 lines out, test/pos/scoping2 fails.
// find out why
if (stat1 != stat && stats1 == stats) {
stats1 = new Tree[stats.length];
System.arraycopy(stats, 0, stats1, 0, i);
}
stats1[i] = stat1;
}
return stats1;
}
/** Attribute a sequence of constructor invocations.
*/
Tree[] transformConstrInvocations(int pos, Tree[] constrs) {
for (int i = 0; i < constrs.length; i++) {
//!!!pushContext(constrs[i], context.owner, context.scope);
constrs[i] = transform(constrs[i], CONSTRmode | SUPERmode, Type.AnyType);
Symbol f = TreeInfo.methSymbol(constrs[i]);
if (f != null) {
Symbol c = f.primaryConstructorClass();
if (c.kind == CLASS) c.initialize();//to detect cycles
}
//!!!popContext();
}
return constrs;
}
void transformConstrInvocationArgs(Tree[] constrs) {
for (int i = 0; i < constrs.length; i++) {
switch (constrs[i]) {
case Apply(Tree fn, Tree[] args):
if (fn.type instanceof Type.MethodType)
transformArgs(
constrs[i].pos, TreeInfo.methSymbol(fn), Symbol.EMPTY_ARRAY,
fn.type, EXPRmode, args, Type.AnyType);
}
}
}
/** Attribute a template
*/
public Tree.Template transformTemplate(Tree.Template templ, Symbol owner) {
if (global.debug) global.log("transforming " + owner);//debug
//System.out.println(owner.info());//DEBUG
Tree[] parents = templ.parents;
transformConstrInvocationArgs(parents);
if (owner.kind != ERROR) {
validateParentClasses(parents, owner.info().parents(), owner.typeOfThis());
}
pushContext(templ, owner, owner.members());
templ.setSymbol(gen.localDummy(templ.pos, owner));
Tree[] body1 = transformStatSeq(templ.body, templ.symbol());
popContext();
if (owner.isTrait()) {
for (int i = 0; i < parents.length; i++) {
checkPureConstr(parents[i], owner);
if (i >= 1) checkTrait(parents[i], owner);
}
for (int i = 0; i < templ.body.length; i++)
checkPureDef(body1[i], owner);
}
Tree.Template templ1 = copy.Template(templ, parents, body1);
templ1.setType(owner.type());
return templ1;
}
/** Attribute an argument list.
* @param pos Position for error reporting
* @param meth The symbol of the called method, or `null' if none exists.
* @param tparams The type parameters that need to be instantiated
* @param methtype The method's type w/o type parameters
* @param argMode The argument mode (either EXPRmode or PATTERNmode)
* @param args The actual arguments
* @param pt The proto-resulttype.
* @return The vector of instantiated argument types, or null if error.
*/
Type[] transformArgs(int pos, Symbol meth, Symbol[] tparams, Type methtype,
int argMode, Tree[] args, Type pt) {
//System.out.println("trans args " + meth + ArrayApply.toString(tparams) + ":" + methtype + "," + pt);//DEBUG
Type[] argtypes = new Type[args.length];
switch (methtype) {
case MethodType(Symbol[] params, Type restp):
if (meth != null && meth.isConstructor() &&
params.length == 1 && params[0] == Symbol.NONE) {
error(pos, meth + " is inaccessible");
return null;
}
Type[] formals = infer.formalTypes(params, args.length);
if (formals.length != args.length) {
error(pos, "wrong number of arguments for " +
(meth == null ? "<function>" : meth) +
ArrayApply.toString(formals, "(", ",", ")"));
return null;
}
if (tparams.length == 0) {
for (int i = 0; i < args.length; i++) {
args[i] = transform(args[i], argMode, formals[i]);
argtypes[i] = args[i].type;
}
} else {
// targs: the type arguments inferred from the prototype
Type[] targs = infer.protoTypeArgs(tparams, restp, pt, params);
// argpts: prototypes for arguments
Type[] argpts = new Type[formals.length];
for (int i = 0; i < formals.length; i++)
argpts[i] = formals[i].subst(tparams, targs);
// transform arguments with [targs/tparams]formals as prototypes
for (int i = 0; i < args.length; i++)
args[i] = transform(
args[i], argMode | POLYmode, formals[i].subst(tparams, targs));
// targs1: same as targs except that every AnyType is mapped to
// formal parameter type.
Type[] targs1 = new Type[targs.length];
for (int i = 0; i < targs.length; i++)
targs1[i] = (targs[i] != Type.AnyType) ? targs[i]
: tparams[i].type();
for (int i = 0; i < args.length; i++) {
argtypes[i] = args[i].type;
switch (argtypes[i]) {
case PolyType(Symbol[] tparams1, Type restype1):
argtypes[i] = infer.argumentTypeInstance(
tparams1, restype1,
formals[i].subst(tparams, targs1),
argpts[i]);
}
}
}
return argtypes;
case PolyType(Symbol[] tparams1, Type restp):
Symbol[] tparams2;
if (tparams.length == 0) tparams2 = tparams1;
else {
tparams2 = new Symbol[tparams.length + tparams1.length];
System.arraycopy(tparams, 0, tparams2, 0, tparams.length);
System.arraycopy(tparams1, 0, tparams2, tparams.length, tparams1.length);
}
return transformArgs(pos, meth, tparams2, restp, argMode, args, pt);
default:
for (int i = 0; i < args.length; i++) {
args[i] = transform(args[i], argMode, Type.AnyType);
argtypes[i] = args[i].type;
}
return argtypes;
}
}
/** Atribute an expression or pattern with prototype `pt'.
* Check that expression's type conforms to `pt'.
* Resolve overloading and apply parameterless functions.
* Insert `apply' function if needed.
*/
Tree transform(Tree tree, int mode, Type pt) {
int savedMode = this.mode;
Type savedPt = this.pt;
this.mode = mode;
this.pt = pt;
Tree tree1 = adapt(transform(tree), mode, pt);
//new TextTreePrinter().print(tree1).print(": " + tree1.type).println().end();//DEBUG
this.mode = savedMode;
this.pt = savedPt;
return tree1;
}
/** Transform expression or type with a given mode.
*/
public Tree transform(Tree tree, int mode) {
if ((mode & (EXPRmode | PATTERNmode | CONSTRmode)) != 0)
return transform(tree, mode, Type.AnyType);
int savedMode = this.mode;
this.mode = mode;
Tree tree1 = transform(tree);
this.mode = savedMode;
if ((mode & TYPEmode) != 0) {
// todo: generalize to type constructors?
Symbol sym = tree1.symbol();
if ((mode & FUNmode) == 0 && sym != null && sym.typeParams().length != 0)
return error(tree.pos, sym + " takes type parameters.");
// else if (tree1.isType())
// return gen.mkType(tree1.pos, tree1.type);
}
return tree1;
}
Tree[] transform(Tree[] trees, int mode) {
for (int i = 0; i < trees.length; i++)
trees[i] = transform(trees[i], mode);
return trees;
}
/** The main attribution function
*/
public Tree transform(Tree tree) {
//System.out.println("transforming " + tree);//DEBUG
if (tree.type != null) {
checkDefined.all = tree; checkDefined.traverse(tree);//debug
return tree;
}
Symbol sym = tree.symbol();
if (sym != null && !sym.isInitialized()) sym.initialize();
if (global.debug && TreeInfo.isDefinition(tree)) global.log("transforming " + sym);
try {
switch (tree) {
case Bad():
return tree.setSymbol(Symbol.ERROR).setType(Type.ErrorType);
case Empty:
tree.type = Type.NoType;
return tree;
case PackageDef(Tree pkg, Tree.Template templ):
switch (templ) {
case Template(Tree[] parents, Tree[] body):
Symbol pkgSym = pkg.symbol();
if (pkgSym != null && pkgSym.isPackage()) {
pushContext(templ, pkgSym, pkgSym.members());
Tree[] body1 = transform(body);
popContext();
Tree.Template templ1 = copy.Template(templ, parents, body1);
templ1.setType(Type.NoType).setSymbol(Symbol.NONE);
return copy.PackageDef(tree, pkg, templ1)
.setType(definitions.UNIT_TYPE);
}
}
return tree.setType(Type.ErrorType);
case ClassDef(_, _, Tree.TypeDef[] tparams, Tree.ValDef[][] vparams, Tree tpe, Tree.Template templ):
pushContext(tree, sym.constructor(), new Scope(context.scope));
reenterParams(tparams);
Tree.TypeDef[] tparams1 = transform(tparams);
reenterParams(vparams);
Tree.ValDef[][] vparams1 = transform(vparams);
Tree tpe1 = transform(tpe);
Tree.Template templ1 = transformTemplate(templ, sym);
popContext();
return copy.ClassDef(tree, sym, tparams1, vparams1, tpe1, templ1)
.setType(definitions.UNIT_TYPE);
case ModuleDef(_, _, Tree tpe, Tree.Template templ):
Tree.Template templ1 = transformTemplate(templ, sym.moduleClass());
return copy.ModuleDef(tree, sym, tpe, templ1)
.setType(definitions.UNIT_TYPE);
case ValDef(_, _, Tree tpe, Tree rhs):
Tree rhs1 = rhs;
if (rhs != Tree.Empty) {
pushContext(tree, sym, context.scope);
rhs1 = transform(rhs, EXPRmode, tpe.type);
popContext();
}
sym.flags |= LOCKED;
checkNonCyclic(tree.pos, tpe.type);
sym.flags &= ~LOCKED;
return copy.ValDef(tree, sym, tpe, rhs1)
.setType(definitions.UNIT_TYPE);
case DefDef(_, _, Tree.TypeDef[] tparams, Tree.ValDef[][] vparams, Tree tpe, Tree rhs):
pushContext(tree, sym, new Scope(context.scope));
reenterParams(tparams);
Tree.TypeDef[] tparams1 = transform(tparams);
reenterParams(vparams);
Tree.ValDef[][] vparams1 = transform(vparams);
Tree rhs1 = rhs;
if (rhs != Tree.Empty)
rhs1 = transform(rhs, EXPRmode, tpe.type);
popContext();
sym.flags |= LOCKED;
checkNonCyclic(tree.pos, tpe.type);
sym.flags &= ~LOCKED;
return copy.DefDef(tree, sym, tparams1, vparams1, tpe, rhs1)
.setType(definitions.UNIT_TYPE);
case TypeDef(_, _, _, _):
checkNonCyclic(tree.pos, sym.type());
return tree
.setType(definitions.UNIT_TYPE);
case Import(Tree expr, Name[] selectors):
context.imports = new ImportList(tree, context.scope, context.imports);
return Tree.Empty;
case Block(Tree[] stats):
pushContext(tree, context.owner, new Scope(context.scope));
int lastmode = mode & ~FUNmode;
Tree[] stats1 = desugarize.Statements(stats, true);
enterSyms(stats1);
context.imports = context.outer.imports;
for (int i = 0; i < stats1.length - 1; i++)
stats1[i] = transform(stats1[i], EXPRmode);
Type owntype;
if (stats1.length > 0) {
stats1[stats1.length - 1] =
transform(stats1[stats1.length - 1], lastmode, pt);
owntype = checkNoEscape(tree.pos, stats1[stats1.length - 1].type);
} else {
owntype = definitions.UNIT_TYPE;
}
popContext();
return copy.Block(tree, stats1)
.setType(owntype);
case Sequence(Tree[] trees):
//System.err.println("sequence with pt "+pt);
Symbol seqSym = definitions.getType( Name.fromString("scala.Seq") ).symbol();
assert seqSym != Symbol.NONE : "did not find Seq";
Type seqType = pt.baseType( seqSym );
Type elemType;
switch( seqType ) {
case TypeRef(_, _, Type[] args):
assert args.length == 1;
elemType = args[ 0 ];
break;
default:
// make a sequence type
elemType = pt;
seqType = new Type.TypeRef(definitions.SCALA_TYPE, seqSym, new Type[] { pt });
break;
/*
System.out.println( pt.isSameAs(definitions.ANY_TYPE ));
System.out.println(pt.getClass());
System.out.println(pt.toString());
System.out.println(seqType.toString());
return error(tree.pos, "not a sequence");
*/
}
for( int i = 0; i < trees.length; i++ ) {
Type tpe = revealSeqOrElemType( trees[ i ],
pt,
pt,
elemType);
//System.err.println("subtree ["+i+"] has tpe "+tpe);
trees[ i ] = transform( trees[ i ],
this.mode | SEQUENCEmode,
tpe);
}
return copy.Sequence( tree, trees ).setType( pt );
/*
case Subsequence(Tree[] trees):
//System.err.println("subsequence with pt "+pt);
Type seqType = pt;
Type elemType;
switch( seqType ) {
case TypeRef(_, _, Type[] args):
//assert args.length == 1:"encountered "+seqType.toString();
// HACK
if( args.length == 1 )
elemType = args[ 0 ];
else
elemType = pt;
break;
default:
return error( tree.pos, "not a (sub)sequence" );
}
for( int i = 0; i < trees.length; i++ ) {
Type tpe = revealSeqOrElemType( trees[ i ], pt, seqType, elemType);
//System.out.println("hello");
trees[ i ] = transform( trees[ i ], this.mode, tpe);
}
System.err.println("subsequence pattern with type: "+seqType);
return copy.Subsequence( tree, trees ).setType( seqType );
*/
case Alternative(Tree[] choices):
//System.err.println("alternative with pt "+pt);
boolean save = this.inAlternative;
this.inAlternative = true;
Tree[] newts = new Tree[ choices.length ];
for (int i = 0; i < choices.length; i++ )
newts[ i ] = transform( choices[ i ], this.mode, pt );
Type tpe = Type.lub( Tree.typeOf( newts ));
this.inAlternative = save;
return copy.Alternative( tree, newts )
.setType( tpe );
case Bind( Name name, Tree body ):
Symbol vble = new TermSymbol(tree.pos,
name,
context.owner,
0x00000000 ).setType( pt );
vble = enterInScope( vble );
//System.out.println("Bind("+name+",...) enters in scope:"+vble.fullNameString());
patternVars.put( vble, new Boolean( this.inAlternative ));
//System.out.println("case Bind.. put symbol vble="+vble+" in scope and patternVars.");
body = transform( body );
//assert body.type != null;
vble.setType( body.type );
return copy.Bind( tree, name, body )
.setSymbol( vble ).setType( body.type );
case Visitor(Tree.CaseDef[] cases):
if (pt.symbol().isSubClass(definitions.PARTIALFUNCTION_CLASS)) {
Type pft = pt.baseType(definitions.PARTIALFUNCTION_CLASS);
Type[] pftargs = pft.typeArgs();
if (pftargs.length == 2 && infer.isFullyDefined(pftargs[0])) {
Type pattype = pftargs[0];
Type restype = pftargs[1];
Tree isDefinedAtVisitor = transformVisitor(
desugarize.isDefinedAtVisitor(tree),
pattype, definitions.BOOLEAN_TYPE);
Tree applyVisitor = transformVisitor(tree, pattype, restype);
if (!infer.isFullyDefined(restype)) restype = applyVisitor.type;
return gen.mkPartialFunction(
tree.pos, applyVisitor, isDefinedAtVisitor,
pattype, restype, context.owner);
} else {
return error(tree.pos, "expected pattern type of cases could not be determined");
}
} else {
return transform(desugarize.Visitor(tree));
}
case Assign(Apply(_, _), _):
return transform(desugarize.Update(tree));
case Assign(Tree lhs, Tree rhs):
Tree lhs1 = transform(lhs, EXPRmode);
Symbol varsym = lhs1.symbol();
if (varsym != null && (varsym.flags & ACCESSOR) != 0) {
return transform(desugarize.Assign(tree.pos, lhs, rhs));
} else if (varsym == null || (varsym.flags & MUTABLE) == 0) {
return error(tree.pos, "assignment to non-variable");
} else {
Tree rhs1 = transform(rhs, EXPRmode, lhs1.type);
return copy.Assign(tree, lhs1, rhs1)
.setType(definitions.UNIT_TYPE);
}
case If(Tree cond, Tree thenp, Tree elsep):
Tree cond1 = transform(cond, EXPRmode, definitions.BOOLEAN_TYPE);
Tree thenp1, elsep1;
if (elsep == Tree.Empty) {
thenp1 = transform(thenp, EXPRmode, definitions.UNIT_TYPE);
elsep1 = make.Block(tree.pos, Tree.EMPTY_ARRAY)
.setType(definitions.UNIT_TYPE);
} else {
thenp1 = transform(thenp, EXPRmode, pt);
elsep1 = transform(elsep, EXPRmode, pt);
}
return copy.If(tree, cond1, thenp1, elsep1)
.setType(Type.lub(new Type[]{thenp1.type, elsep1.type}));
case New(Tree.Template templ):
switch (templ) {
case Template(Tree[] parents, Tree[] body):
if (parents.length == 1 && body.length == 0) {
Tree parent1 = transform(parents[0], CONSTRmode, pt);
Type owntype = parent1.type;
Tree.Template templ1 = (Tree.Template)
copy.Template(templ, Symbol.NONE, new Tree[]{parent1}, body)
.setType(owntype);
checkInstantiatable(tree.pos, owntype);
return copy.New(tree, templ1)
.setType(owntype.instanceType());
} else {
pushContext(tree, context.owner, new Scope(context.scope));
Tree cd = make.ClassDef(
templ.pos,
0,
Names.ANON_CLASS_NAME.toTypeName(),
Tree.TypeDef_EMPTY_ARRAY,
new ValDef[][]{Tree.ValDef_EMPTY_ARRAY},
Tree.Empty,
templ);
//new TextTreePrinter().print(cd).println().end();//DEBUG
enterSym(cd);
cd = transform(cd);
Symbol clazz = cd.symbol();
if (clazz.kind != CLASS) return errorTree(tree.pos);
// compute template's type with new refinement scope.
Type[] parentTypes = clazz.info().parents();
Scope refinement = new Scope();
Type base = Type.compoundType(parentTypes, Scope.EMPTY);
Type owntype = Type.compoundType(
parentTypes, refinement, clazz);
Scope.SymbolIterator it = clazz.members().iterator();
while (it.hasNext()) {
Symbol sym1 = it.next();
Symbol basesym1 = base.lookupNonPrivate(sym1.name);
if (basesym1.kind != NONE &&
!base.symbol().thisType().memberType(basesym1)
.isSameAs(sym1.type()))
refinement.enter(sym1);
}
if (refinement.elems == Scope.Entry.NONE &&
parentTypes.length == 1)
owntype = parentTypes[0];
else
owntype = checkNoEscape(tree.pos, owntype);
Tree alloc = gen.New(
gen.Apply(
gen.mkRef(tree.pos,
Type.localThisType, clazz.constructor()),
Tree.EMPTY_ARRAY))
.setType(owntype);
popContext();
return make.Block(tree.pos, new Tree[]{cd, alloc})
.setType(owntype);
}
default:
throw new ApplicationError();
}
case Typed(Tree expr, Tree tpe):
Tree tpe1 = transform(tpe, TYPEmode);
Tree expr1 = transform(expr, mode & baseModes, tpe1.type);
return copy.Typed(tree, expr1, tpe1).setType(tpe1.type);
case Function(Tree.ValDef[] vparams, Tree body):
pushContext(tree, context.owner, new Scope(context.scope));
Type restype = desugarize.preFunction(vparams, pt);
enterParams(vparams);
Tree.ValDef[] vparams1 = transform(vparams);
Tree body1 = transform(body, EXPRmode, restype);
if (!infer.isFullyDefined(restype)) restype = body1.type;
popContext();
return gen.mkFunction(
tree.pos, vparams1, body1, restype, context.owner);
case TypeApply(Tree fn, Tree[] args):
Tree fn1 = transform(fn, EXPRmode | FUNmode, Type.AnyType);
Tree[] args1 = transform(args, TYPEmode);
Type[] argtypes = Tree.typeOf(args1);
// resolve overloading
switch (fn1.type) {
case OverloadedType(Symbol[] alts, Type[] alttypes):
try {
infer.polyAlternative(fn1, alts, alttypes, args.length);
} catch (Type.Error ex) {
error(tree.pos, ex.msg);
}
}
// match against arguments
switch (fn1.type) {
case PolyType(Symbol[] tparams, Type restp):
if (tparams.length == argtypes.length)
return copy.TypeApply(tree, fn1, args1)
.setType(restp.subst(tparams, argtypes));
break;
case ErrorType:
return tree.setType(Type.ErrorType);
}
return error(tree.pos,
infer.toString(fn1.symbol(), fn1.type) +
" cannot be applied to " +
ArrayApply.toString(argtypes, "[", ",", "]"));
case Apply(Tree fn, Tree[] args):
Tree fn1;
int argMode;
//todo: Should we pass in both cases a methodtype with
// AnyType's for args as a prototype?
if ((mode & (EXPRmode | CONSTRmode)) != 0) {
fn1 = transform(fn, mode | FUNmode, Type.AnyType);
argMode = EXPRmode;
} else {
assert (mode & PATTERNmode) != 0;
fn1 = transform(fn, mode | FUNmode, pt);
argMode = PATTERNmode;
}
// if function is overloaded with one alternative whose arity matches
// argument length, preselect this alternative.
switch (fn1.type) {
case OverloadedType(Symbol[] alts, Type[] alttypes):
int matching1 = -1;
int matching2 = -1;
for (int i = 0; i < alttypes.length; i++) {
Type alttp = alttypes[i];
switch (alttp) {
case PolyType(_, Type restp): alttp = restp;
}
switch (alttp) {
case MethodType(Symbol[] params, _):
if (params.length == args.length ||
params.length == 1 && (params[0].flags & REPEATED) != 0) {
matching2 = matching1;
matching1 = i;
}
}
}
if (matching1 >= 0 && matching2 < 0)
fn1.setSymbol(alts[matching1]).setType(alttypes[matching1]);
}
// handle the case of application of match to a visitor specially
if (args.length == 1 && args[0] instanceof Visitor) {
Type pattp = matchQualType(fn1);
if (pattp == Type.ErrorType) {
return tree.setType(Type.ErrorType);
} else if (pattp != Type.NoType) {
if (infer.isFullyDefined(pattp) &&
!(fn1.type instanceof Type.PolyType &&
pattp.containsSome(fn1.type.typeParams()))) {
Tree fn2 = desugarize.postMatch(fn1, context.enclClass.owner);
Tree arg1 = transformVisitor(args[0], pattp, pt);
return copy.Apply(tree, fn2, new Tree[]{arg1})
.setType(arg1.type);
} else {
return error(tree.pos, "expected pattern type of cases could not be determined");
}
}
}
// return prematurely if function is a superclass constructor
// and no type arguments need to be inferred.
if ((mode & SUPERmode) != 0 && fn1.type instanceof Type.MethodType)
return copy.Apply(tree, fn1, args).setType(fn1.type.resultType());
// type arguments with formals as prototypes if they exist.
fn1.type = infer.freshInstance(fn1.type);
Type[] argtypes = transformArgs(
tree.pos, fn1.symbol(), Symbol.EMPTY_ARRAY, fn1.type, argMode, args, pt);
// propagate errors in arguments
if (argtypes == null) {
return tree.setType(Type.ErrorType);
}
for (int i = 0; i < argtypes.length; i++) {
if (argtypes[i] == Type.ErrorType) {
return tree.setType(Type.ErrorType);
}
}
// resolve overloading
switch (fn1.type) {
case OverloadedType(Symbol[] alts, Type[] alttypes):
try {
infer.methodAlternative(fn1, alts, alttypes, argtypes, pt);
} catch (Type.Error ex) {
error(tree.pos, ex.msg);
}
}
switch (fn1.type) {
case PolyType(Symbol[] tparams, Type restp):
// if method is polymorphic,
// infer instance, and adapt arguments to instantiated formals
try {
fn1 = infer.methodInstance(fn1, tparams, restp, argtypes, pt);
//System.out.println(fn1 + ":" + fn1.type);//DEBUG
} catch (Type.Error ex) {
error(tree.pos, ex.msg);
}
switch (fn1.type) {
case MethodType(Symbol[] params, Type restp1):
Type[] formals = infer.formalTypes(params, args.length);
for (int i = 0; i < args.length; i++) {
args[i] = adapt(args[i], argMode, formals[i]);
}
return copy.Apply(tree, fn1, args)
.setType(restp1);
}
break;
case MethodType(Symbol[] params, Type restp):
// if method is monomorphic,
// check that it can be applied to arguments.
if (infer.isApplicable(fn1.type, argtypes, Type.AnyType)) {
return copy.Apply(tree, fn1, args)
.setType(restp);
}
}
if (fn1.type == Type.ErrorType)
return tree.setType(Type.ErrorType);
//new TextTreePrinter().print(tree).println().end();//DEBUG
return error(tree.pos,
infer.applyErrorMsg(
"", fn1, " cannot be applied to ", argtypes, pt));
case Super(Tree qual):
Symbol clazz;
Tree qual1;
if (qual == Tree.Empty) {
clazz = context.enclClass.owner;
if (clazz != null) {
qual1 = gen.Ident(tree.pos, clazz);
} else {
return error(
tree.pos,
"super can be used only in a class, object, or template");
}
} else {
qual1 = transform(qual, TYPEmode | FUNmode);
clazz = qual1.symbol();
}
switch (clazz.info()) {
case CompoundType(Type[] parents, _):
return copy.Super(tree, qual1)
.setType(Type.compoundType(parents, Scope.EMPTY).symbol().thisType());
case ErrorType:
return tree.setType(Type.ErrorType);
default:
return error(qual.pos, "class identifier expected");
}
case This(Tree qual):
Symbol clazz;
Tree tree1;
if (qual == Tree.Empty) {
clazz = context.enclClass.owner;
if (clazz != null) {
tree1 = makeStableId(tree.pos, clazz.thisType());
} else {
return error(
tree.pos, tree +
" can be used only in a class, object, or template");
}
} else {
Tree qual1 = transform(qual, TYPEmode | FUNmode);
clazz = qual1.symbol();
if (clazz.kind == CLASS) {
Context clazzContext = context.outerContext(clazz);
if (clazzContext != Context.NONE) {
if (!(qual1 instanceof Tree.Ident))
qual1 = gen.Ident(tree.pos, clazz);
tree1 = copy.This(tree, qual1);
} else {
return error(qual.pos,
clazz.name + " is not an enclosing class");
}
} else {
return error(qual.pos, "class identifier expected");
}
}
return tree1.setType(
(pt != null && pt.isStable() || (mode & QUALmode) != 0)
? clazz.thisType() : clazz.typeOfThis());
case Select(Tree qual, Name name):
int qualmode = EXPRmode | POLYmode | QUALmode;
Tree qual1 = transform(qual, qualmode);
if (name.isTypeName()) qual1 = checkStable(qual1);
return transformSelect(
tree, adapt(qual1, qualmode, Type.AnyType), name);
case Ident(Name name):
if (((mode & PATTERNmode) != 0) && name.isVariable()) {
//System.out.println("pat var " + name + ":" + pt);//DEBUG
Symbol vble, vble2 = null;
if( name != Names.WILDCARD )
vble2 = context.scope.lookup(/*false,*/ name );
//System.out.println("looked up \""+name+"\", found symbol "+vble2.fullNameString());
//System.out.println("patternVars.containsKey?"+patternVars.containsKey( vble2 ) );
if ( patternVars.containsKey( vble2 ) )
vble = vble2;
else
vble = new TermSymbol(tree.pos,
name,
context.owner,
0).setType(pt);
if (name != Names.WILDCARD) enterInScope(vble);
return tree.setSymbol(vble).setType(pt);
} else {
return transformIdent(tree, name);
}
case Literal(Object value):
return tree.setType(value2Type(value));
case TypeTerm():
return tree;
case SingletonType(Tree ref):
Tree ref1 = transform(ref, EXPRmode | QUALmode, Type.AnyType);
return copy.SingletonType(tree, ref1)
.setType(checkObjectType(tree.pos, ref1.type.resultType()));
case SelectFromType(Tree qual, Name name):
Tree qual1 = transform(qual, TYPEmode);
return transformSelect(tree, qual1, name);
case CompoundType(Tree[] parents, Tree[] refinements):
Tree[] parents1 = transform(parents, TYPEmode);
Type[] ptypes = Tree.typeOf(parents);
Scope members = new Scope();
Type self = Type.compoundType(ptypes, members);
Symbol clazz = self.symbol();
pushContext(tree, clazz, members);
for (int i = 0; i < refinements.length; i++) {
enterSym(refinements[i]).flags |= OVERRIDE;
}
Tree[] refinements1 = transformStatSeq(refinements, Symbol.NONE);
popContext();
return copy.CompoundType(tree, parents1, refinements1)
.setType(self);
case AppliedType(Tree tpe, Tree[] args):
Tree tpe1 = transform(tpe, TYPEmode | FUNmode);
Tree[] args1 = transform(args, TYPEmode);
Type[] argtypes = Tree.typeOf(args);
//todo: this needs to be refined.
Symbol[] tparams =
(Type.isSameAs(tpe1.type.typeArgs(), Symbol.type(tpe1.type.typeParams())))
? tpe1.type.typeParams()
: Symbol.EMPTY_ARRAY;
Type owntype = Type.ErrorType;
if (tpe1.type != Type.ErrorType) {
if (tparams.length == args.length)
owntype = Type.appliedType(tpe1.type, argtypes);
else if (tparams.length == 0)
error(tree.pos, tpe1.type + " does not take type parameters");
else error(tree.pos, "wrong number of type arguments for " +
tpe1.type);
}
return copy.AppliedType(tree, tpe1, args1).setType(owntype);
case FunType(_, _):
return transform(desugarize.FunType(tree));
default:
throw new ApplicationError("illegal tree: " + tree);
}
} catch (Type.Error ex) {
reportTypeError(tree.pos, ex);
tree.type = Type.ErrorType;
if (tree.hasSymbol() && tree.symbol() == null) tree.setSymbol(Symbol.ERROR);
return tree;
}
}
// sequence helper function
// get first elementary type in a sequence
// precondition: tree is successor of a sequence node
Type revealSeqOrElemType( Tree tree, Type proto, Type seqType, Type elemType ) {
switch( tree ) {
//case Subsequence(_): NEW
//return proto; NEW
case Sequence(_):
return elemType;
case Alternative( Tree[] choices ):
// after normalization, choices.length >= 2
// and if there is one subsequence branch, all
// branches are subsequence nodes
return revealSeqOrElemType( choices[ 0 ], proto, seqType, elemType );
case Bind( _, Tree body ):
// here, we forget the (concrete) prototype (if we have one)
return revealSeqOrElemType( body, seqType, seqType, elemType );
default:
return elemType;
}
}
}
|
package com.tectonica.jonix;
import org.junit.Test;
import repackaged.com.csvreader.CsvWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
/**
* @author Zach Melamed
* @since 1/23/2018
*/
public class CsvWriterTest {
@Test
public void testCsvWriter() throws IOException {
StringWriter sw = new StringWriter();
CsvWriter writer = new CsvWriter(sw, ',');
writer.setRecordDelimiter('\r'); // to avoid Windows/Unix differences
List<List<String>> rows = Arrays.asList(
Arrays.asList("\"header\"1", "h,e,a,d,e,r2", "header:3"),
Arrays.asList("regular", "with,comma", "with\r\nlinebreak"),
Arrays.asList(" start-with-space", "end-of-space ", "withline\nbreak")
);
for (List<String> row : rows) {
for (String cell : row) {
writer.write(cell, true);
}
writer.endRecord();
}
org.junit.Assert.assertEquals(sw.toString().length(), 128);
}
}
|
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle.gui;
import antlr.collections.AST;
import antlr.ASTFactory;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* The model that backs the parse tree in the GUI.
*
* @author Lars Khne
* @version $Id: ParseTreeModel.java,v 1.2 2002-10-19 06:25:45 oburn Exp $
*/
public class ParseTreeModel extends AbstractTreeTableModel
{
private static final String[] COLUMN_NAMES = new String[]{
"Tree", "Type", "Line", "Column", "Text"
};
public ParseTreeModel(DetailAST parseTree)
{
super(createArtificialTreeRoot());
setParseTree(parseTree);
}
private static DetailAST createArtificialTreeRoot()
{
ASTFactory factory = new ASTFactory();
factory.setASTNodeType(DetailAST.class.getName());
// TODO: Need to resolve if need a fake root node....
return (DetailAST) factory.create(1, "ROOT");
}
void setParseTree(DetailAST parseTree)
{
DetailAST root = (DetailAST) getRoot();
root.setFirstChild(parseTree);
Object[] path = {root};
// no need to setup remaining info, as the call results in a
// table structure changed event anyway - we just pass nulls
fireTreeStructureChanged(this, path, null, null);
}
public int getColumnCount()
{
return COLUMN_NAMES.length;
}
public String getColumnName(int column)
{
return COLUMN_NAMES[column];
}
public Class getColumnClass(int column)
{
switch (column) {
case 0:
return TreeTableModel.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Integer.class;
case 4:
return String.class;
}
return Object.class;
}
public Object getValueAt(Object node, int column)
{
DetailAST ast = (DetailAST) node;
switch (column) {
case 0:
return null;
case 1:
return TokenTypes.getTokenName(ast.getType());
case 2:
return new Integer(ast.getLineNo());
case 3:
return new Integer(ast.getColumnNo());
case 4:
return ast.getText();
}
return null;
}
public void setValueAt(Object aValue, Object node, int column)
{
}
public Object getChild(Object parent, int index)
{
DetailAST ast = (DetailAST) parent;
int i = 0;
AST child = ast.getFirstChild();
while (i < index) {
child = child.getNextSibling();
i++;
}
return child;
}
public int getChildCount(Object parent)
{
DetailAST ast = (DetailAST) parent;
return ast.getChildCount();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.